instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: t1_parse_font_matrix( T1_Face face, T1_Loader loader ) { T1_Parser parser = &loader->parser; FT_Matrix* matrix = &face->type1.font_matrix; FT_Vector* offset = &face->type1.font_offset; FT_Face root = (FT_Face)&face->root; FT_Fixed temp[6]; FT_Fixed temp_scale; FT_Int result; result = T1_ToFixedArray( parser, 6, temp, 3 ); if ( result < 0 ) { parser->root.error = FT_THROW( Invalid_File_Format ); return; } temp_scale = FT_ABS( temp[3] ); if ( temp_scale == 0 ) { FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* Set Units per EM based on FontMatrix values. We set the value to */ /* 1000 / temp_scale, because temp_scale was already multiplied by */ /* 1000 (in t1_tofixed, from psobjs.c). */ root->units_per_EM = (FT_UShort)FT_DivFix( 1000, temp_scale ); /* we need to scale the values by 1.0/temp_scale */ if ( temp_scale != 0x10000L ) { temp[0] = FT_DivFix( temp[0], temp_scale ); temp[1] = FT_DivFix( temp[1], temp_scale ); temp[2] = FT_DivFix( temp[2], temp_scale ); temp[4] = FT_DivFix( temp[4], temp_scale ); temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L; } matrix->xx = temp[0]; matrix->yx = temp[1]; matrix->xy = temp[2]; matrix->yy = temp[3]; /* note that the offsets must be expressed in integer font units */ offset->x = temp[4] >> 16; offset->y = temp[5] >> 16; } Commit Message: CWE ID: CWE-20
t1_parse_font_matrix( T1_Face face, T1_Loader loader ) { T1_Parser parser = &loader->parser; FT_Matrix* matrix = &face->type1.font_matrix; FT_Vector* offset = &face->type1.font_offset; FT_Face root = (FT_Face)&face->root; FT_Fixed temp[6]; FT_Fixed temp_scale; FT_Int result; result = T1_ToFixedArray( parser, 6, temp, 3 ); if ( result < 6 ) { parser->root.error = FT_THROW( Invalid_File_Format ); return; } temp_scale = FT_ABS( temp[3] ); if ( temp_scale == 0 ) { FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* Set Units per EM based on FontMatrix values. We set the value to */ /* 1000 / temp_scale, because temp_scale was already multiplied by */ /* 1000 (in t1_tofixed, from psobjs.c). */ root->units_per_EM = (FT_UShort)FT_DivFix( 1000, temp_scale ); /* we need to scale the values by 1.0/temp_scale */ if ( temp_scale != 0x10000L ) { temp[0] = FT_DivFix( temp[0], temp_scale ); temp[1] = FT_DivFix( temp[1], temp_scale ); temp[2] = FT_DivFix( temp[2], temp_scale ); temp[4] = FT_DivFix( temp[4], temp_scale ); temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L; } matrix->xx = temp[0]; matrix->yx = temp[1]; matrix->xy = temp[2]; matrix->yy = temp[3]; /* note that the offsets must be expressed in integer font units */ offset->x = temp[4] >> 16; offset->y = temp[5] >> 16; }
165,342
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int udpv6_recvmsg(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, addr_len); if (np->rxpmtu && np->rxopt.bits.rxpmtu) return ipv6_recv_rxpmtu(sk, msg, len, addr_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_msg(skb, sizeof(struct udphdr), msg, copied); else { err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg); 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) { DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, 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, inet6_iif(skb)); } *addr_len = sizeof(*sin6); } if (np->rxopt.all) ip6_datagram_recv_common_ctl(sk, msg, skb); if (is_udp4) { if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); } else { if (np->rxopt.all) ip6_datagram_recv_specific_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: udp: fix behavior of wrong checksums We have two problems in UDP stack related to bogus checksums : 1) We return -EAGAIN to application even if receive queue is not empty. This breaks applications using edge trigger epoll() 2) Under UDP flood, we can loop forever without yielding to other processes, potentially hanging the host, especially on non SMP. This patch is an attempt to make things better. We might in the future add extra support for rt applications wanting to better control time spent doing a recv() in a hostile environment. For example we could validate checksums before queuing packets in socket receive queue. Signed-off-by: Eric Dumazet <[email protected]> Cc: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
int udpv6_recvmsg(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, addr_len); if (np->rxpmtu && np->rxopt.bits.rxpmtu) return ipv6_recv_rxpmtu(sk, msg, len, addr_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_msg(skb, sizeof(struct udphdr), msg, copied); else { err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg); 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) { DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, 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, inet6_iif(skb)); } *addr_len = sizeof(*sin6); } if (np->rxopt.all) ip6_datagram_recv_common_ctl(sk, msg, skb); if (is_udp4) { if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); } else { if (np->rxopt.all) ip6_datagram_recv_specific_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); /* starting over for a new packet, but check if we need to yield */ cond_resched(); msg->msg_flags &= ~MSG_TRUNC; goto try_again; }
166,597
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: pdf_repair_xref(fz_context *ctx, pdf_document *doc) { int c; pdf_lexbuf *buf = &doc->lexbuf.base; int num_roots = 0; int max_roots = 0; fz_var(encrypt); fz_var(id); fz_var(roots); fz_var(num_roots); fz_var(max_roots); fz_var(info); fz_var(list); fz_var(obj); if (doc->repair_attempted) fz_throw(ctx, FZ_ERROR_GENERIC, "Repair failed already - not trying again"); doc->repair_attempted = 1; doc->dirty = 1; /* Can't support incremental update after repair */ doc->freeze_updates = 1; fz_seek(ctx, doc->file, 0, 0); fz_try(ctx) { pdf_xref_entry *entry; listlen = 0; listcap = 1024; list = fz_malloc_array(ctx, listcap, sizeof(struct entry)); /* look for '%PDF' version marker within first kilobyte of file */ n = fz_read(ctx, doc->file, (unsigned char *)buf->scratch, fz_mini(buf->size, 1024)); fz_seek(ctx, doc->file, 0, 0); if (n >= 4) { for (j = 0; j < n - 4; j++) { if (memcmp(&buf->scratch[j], "%PDF", 4) == 0) { fz_seek(ctx, doc->file, j + 8, 0); /* skip "%PDF-X.Y" */ break; } } } /* skip comment line after version marker since some generators * forget to terminate the comment with a newline */ c = fz_read_byte(ctx, doc->file); while (c >= 0 && (c == ' ' || c == '%')) c = fz_read_byte(ctx, doc->file); fz_unread_byte(ctx, doc->file); while (1) { tmpofs = fz_tell(ctx, doc->file); if (tmpofs < 0) fz_throw(ctx, FZ_ERROR_GENERIC, "cannot tell in file"); fz_try(ctx) { tok = pdf_lex_no_string(ctx, doc->file, buf); } fz_catch(ctx) { fz_rethrow_if(ctx, FZ_ERROR_TRYLATER); fz_warn(ctx, "ignoring the rest of the file"); break; } /* If we have the next token already, then we'll jump * back here, rather than going through the top of * the loop. */ have_next_token: if (tok == PDF_TOK_INT) { if (buf->i < 0) { num = 0; gen = 0; continue; } numofs = genofs; num = gen; genofs = tmpofs; gen = buf->i; } else if (tok == PDF_TOK_OBJ) { pdf_obj *root = NULL; fz_try(ctx) { stm_len = 0; stm_ofs = 0; tok = pdf_repair_obj(ctx, doc, buf, &stm_ofs, &stm_len, &encrypt, &id, NULL, &tmpofs, &root); if (root) add_root(ctx, root, &roots, &num_roots, &max_roots); } fz_always(ctx) { pdf_drop_obj(ctx, root); } fz_catch(ctx) { fz_rethrow_if(ctx, FZ_ERROR_TRYLATER); /* If we haven't seen a root yet, there is nothing * we can do, but give up. Otherwise, we'll make * do. */ if (!roots) fz_rethrow(ctx); fz_warn(ctx, "cannot parse object (%d %d R) - ignoring rest of file", num, gen); break; } if (num <= 0 || num > MAX_OBJECT_NUMBER) { fz_warn(ctx, "ignoring object with invalid object number (%d %d R)", num, gen); goto have_next_token; } gen = fz_clampi(gen, 0, 65535); if (listlen + 1 == listcap) { listcap = (listcap * 3) / 2; list = fz_resize_array(ctx, list, listcap, sizeof(struct entry)); } list[listlen].num = num; list[listlen].gen = gen; list[listlen].ofs = numofs; list[listlen].stm_ofs = stm_ofs; list[listlen].stm_len = stm_len; listlen ++; if (num > maxnum) maxnum = num; goto have_next_token; } /* If we find a dictionary it is probably the trailer, * but could be a stream (or bogus) dictionary caused * by a corrupt file. */ else if (tok == PDF_TOK_OPEN_DICT) { fz_try(ctx) { dict = pdf_parse_dict(ctx, doc, doc->file, buf); } fz_catch(ctx) { fz_rethrow_if(ctx, FZ_ERROR_TRYLATER); /* If this was the real trailer dict * it was broken, in which case we are * in trouble. Keep going though in * case this was just a bogus dict. */ continue; } obj = pdf_dict_get(ctx, dict, PDF_NAME_Encrypt); if (obj) { pdf_drop_obj(ctx, encrypt); encrypt = pdf_keep_obj(ctx, obj); } obj = pdf_dict_get(ctx, dict, PDF_NAME_ID); if (obj && (!id || !encrypt || pdf_dict_get(ctx, dict, PDF_NAME_Encrypt))) { pdf_drop_obj(ctx, id); id = pdf_keep_obj(ctx, obj); } obj = pdf_dict_get(ctx, dict, PDF_NAME_Root); if (obj) add_root(ctx, obj, &roots, &num_roots, &max_roots); obj = pdf_dict_get(ctx, dict, PDF_NAME_Info); if (obj) { pdf_drop_obj(ctx, info); info = pdf_keep_obj(ctx, obj); } pdf_drop_obj(ctx, dict); obj = NULL; } else if (tok == PDF_TOK_EOF) break; else { if (tok == PDF_TOK_ERROR) fz_read_byte(ctx, doc->file); num = 0; gen = 0; } } if (listlen == 0) fz_throw(ctx, FZ_ERROR_GENERIC, "no objects found"); /* make xref reasonable */ /* Dummy access to entry to assure sufficient space in the xref table and avoid repeated reallocs in the loop */ /* Ensure that the first xref table is a 'solid' one from * 0 to maxnum. */ pdf_ensure_solid_xref(ctx, doc, maxnum); for (i = 1; i < maxnum; i++) { entry = pdf_get_populating_xref_entry(ctx, doc, i); if (entry->obj != NULL) continue; entry->type = 'f'; entry->ofs = 0; entry->gen = 0; entry->num = 0; entry->stm_ofs = 0; } for (i = 0; i < listlen; i++) { entry = pdf_get_populating_xref_entry(ctx, doc, list[i].num); entry->type = 'n'; entry->ofs = list[i].ofs; entry->gen = list[i].gen; entry->num = list[i].num; entry->stm_ofs = list[i].stm_ofs; /* correct stream length for unencrypted documents */ if (!encrypt && list[i].stm_len >= 0) { dict = pdf_load_object(ctx, doc, list[i].num); length = pdf_new_int(ctx, doc, list[i].stm_len); pdf_dict_put(ctx, dict, PDF_NAME_Length, length); pdf_drop_obj(ctx, length); pdf_drop_obj(ctx, dict); } } entry = pdf_get_populating_xref_entry(ctx, doc, 0); entry->type = 'f'; entry->ofs = 0; entry->gen = 65535; entry->num = 0; entry->stm_ofs = 0; next = 0; /* correct stream length for unencrypted documents */ if (!encrypt && list[i].stm_len >= 0) { dict = pdf_load_object(ctx, doc, list[i].num); length = pdf_new_int(ctx, doc, list[i].stm_len); pdf_dict_put(ctx, dict, PDF_NAME_Length, length); pdf_drop_obj(ctx, length); pdf_drop_obj(ctx, dict); } } obj = pdf_new_dict(ctx, doc, 5); /* During repair there is only a single xref section */ pdf_set_populating_xref_trailer(ctx, doc, obj); pdf_drop_obj(ctx, obj); obj = NULL; obj = pdf_new_int(ctx, doc, maxnum + 1); pdf_dict_put(ctx, pdf_trailer(ctx, doc), PDF_NAME_Size, obj); pdf_drop_obj(ctx, obj); obj = NULL; if (roots) { int i; for (i = num_roots-1; i > 0; i--) { if (pdf_is_dict(ctx, roots[i])) break; } if (i >= 0) { pdf_dict_put(ctx, pdf_trailer(ctx, doc), PDF_NAME_Root, roots[i]); } } if (info) { pdf_dict_put(ctx, pdf_trailer(ctx, doc), PDF_NAME_Info, info); pdf_drop_obj(ctx, info); info = NULL; } if (encrypt) { if (pdf_is_indirect(ctx, encrypt)) { /* create new reference with non-NULL xref pointer */ obj = pdf_new_indirect(ctx, doc, pdf_to_num(ctx, encrypt), pdf_to_gen(ctx, encrypt)); pdf_drop_obj(ctx, encrypt); encrypt = obj; obj = NULL; } pdf_dict_put(ctx, pdf_trailer(ctx, doc), PDF_NAME_Encrypt, encrypt); pdf_drop_obj(ctx, encrypt); encrypt = NULL; } if (id) { if (pdf_is_indirect(ctx, id)) { /* create new reference with non-NULL xref pointer */ obj = pdf_new_indirect(ctx, doc, pdf_to_num(ctx, id), pdf_to_gen(ctx, id)); pdf_drop_obj(ctx, id); id = obj; obj = NULL; } pdf_dict_put(ctx, pdf_trailer(ctx, doc), PDF_NAME_ID, id); pdf_drop_obj(ctx, id); id = NULL; } fz_free(ctx, list); } Commit Message: CWE ID: CWE-416
pdf_repair_xref(fz_context *ctx, pdf_document *doc) { int c; pdf_lexbuf *buf = &doc->lexbuf.base; int num_roots = 0; int max_roots = 0; fz_var(encrypt); fz_var(id); fz_var(roots); fz_var(num_roots); fz_var(max_roots); fz_var(info); fz_var(list); fz_var(obj); if (doc->repair_attempted) fz_throw(ctx, FZ_ERROR_GENERIC, "Repair failed already - not trying again"); doc->repair_attempted = 1; doc->dirty = 1; /* Can't support incremental update after repair */ doc->freeze_updates = 1; fz_seek(ctx, doc->file, 0, 0); fz_try(ctx) { pdf_xref_entry *entry; listlen = 0; listcap = 1024; list = fz_malloc_array(ctx, listcap, sizeof(struct entry)); /* look for '%PDF' version marker within first kilobyte of file */ n = fz_read(ctx, doc->file, (unsigned char *)buf->scratch, fz_mini(buf->size, 1024)); fz_seek(ctx, doc->file, 0, 0); if (n >= 4) { for (j = 0; j < n - 4; j++) { if (memcmp(&buf->scratch[j], "%PDF", 4) == 0) { fz_seek(ctx, doc->file, j + 8, 0); /* skip "%PDF-X.Y" */ break; } } } /* skip comment line after version marker since some generators * forget to terminate the comment with a newline */ c = fz_read_byte(ctx, doc->file); while (c >= 0 && (c == ' ' || c == '%')) c = fz_read_byte(ctx, doc->file); fz_unread_byte(ctx, doc->file); while (1) { tmpofs = fz_tell(ctx, doc->file); if (tmpofs < 0) fz_throw(ctx, FZ_ERROR_GENERIC, "cannot tell in file"); fz_try(ctx) { tok = pdf_lex_no_string(ctx, doc->file, buf); } fz_catch(ctx) { fz_rethrow_if(ctx, FZ_ERROR_TRYLATER); fz_warn(ctx, "ignoring the rest of the file"); break; } /* If we have the next token already, then we'll jump * back here, rather than going through the top of * the loop. */ have_next_token: if (tok == PDF_TOK_INT) { if (buf->i < 0) { num = 0; gen = 0; continue; } numofs = genofs; num = gen; genofs = tmpofs; gen = buf->i; } else if (tok == PDF_TOK_OBJ) { pdf_obj *root = NULL; fz_try(ctx) { stm_len = 0; stm_ofs = 0; tok = pdf_repair_obj(ctx, doc, buf, &stm_ofs, &stm_len, &encrypt, &id, NULL, &tmpofs, &root); if (root) add_root(ctx, root, &roots, &num_roots, &max_roots); } fz_always(ctx) { pdf_drop_obj(ctx, root); } fz_catch(ctx) { fz_rethrow_if(ctx, FZ_ERROR_TRYLATER); /* If we haven't seen a root yet, there is nothing * we can do, but give up. Otherwise, we'll make * do. */ if (!roots) fz_rethrow(ctx); fz_warn(ctx, "cannot parse object (%d %d R) - ignoring rest of file", num, gen); break; } if (num <= 0 || num > MAX_OBJECT_NUMBER) { fz_warn(ctx, "ignoring object with invalid object number (%d %d R)", num, gen); goto have_next_token; } gen = fz_clampi(gen, 0, 65535); if (listlen + 1 == listcap) { listcap = (listcap * 3) / 2; list = fz_resize_array(ctx, list, listcap, sizeof(struct entry)); } list[listlen].num = num; list[listlen].gen = gen; list[listlen].ofs = numofs; list[listlen].stm_ofs = stm_ofs; list[listlen].stm_len = stm_len; listlen ++; if (num > maxnum) maxnum = num; goto have_next_token; } /* If we find a dictionary it is probably the trailer, * but could be a stream (or bogus) dictionary caused * by a corrupt file. */ else if (tok == PDF_TOK_OPEN_DICT) { fz_try(ctx) { dict = pdf_parse_dict(ctx, doc, doc->file, buf); } fz_catch(ctx) { fz_rethrow_if(ctx, FZ_ERROR_TRYLATER); /* If this was the real trailer dict * it was broken, in which case we are * in trouble. Keep going though in * case this was just a bogus dict. */ continue; } obj = pdf_dict_get(ctx, dict, PDF_NAME_Encrypt); if (obj) { pdf_drop_obj(ctx, encrypt); encrypt = pdf_keep_obj(ctx, obj); } obj = pdf_dict_get(ctx, dict, PDF_NAME_ID); if (obj && (!id || !encrypt || pdf_dict_get(ctx, dict, PDF_NAME_Encrypt))) { pdf_drop_obj(ctx, id); id = pdf_keep_obj(ctx, obj); } obj = pdf_dict_get(ctx, dict, PDF_NAME_Root); if (obj) add_root(ctx, obj, &roots, &num_roots, &max_roots); obj = pdf_dict_get(ctx, dict, PDF_NAME_Info); if (obj) { pdf_drop_obj(ctx, info); info = pdf_keep_obj(ctx, obj); } pdf_drop_obj(ctx, dict); obj = NULL; } else if (tok == PDF_TOK_EOF) break; else { if (tok == PDF_TOK_ERROR) fz_read_byte(ctx, doc->file); num = 0; gen = 0; } } if (listlen == 0) fz_throw(ctx, FZ_ERROR_GENERIC, "no objects found"); /* make xref reasonable */ /* Dummy access to entry to assure sufficient space in the xref table and avoid repeated reallocs in the loop */ /* Ensure that the first xref table is a 'solid' one from * 0 to maxnum. */ pdf_ensure_solid_xref(ctx, doc, maxnum); for (i = 1; i < maxnum; i++) { entry = pdf_get_populating_xref_entry(ctx, doc, i); if (entry->obj != NULL) continue; entry->type = 'f'; entry->ofs = 0; entry->gen = 0; entry->num = 0; entry->stm_ofs = 0; } for (i = 0; i < listlen; i++) { entry = pdf_get_populating_xref_entry(ctx, doc, list[i].num); entry->type = 'n'; entry->ofs = list[i].ofs; entry->gen = list[i].gen; entry->num = list[i].num; entry->stm_ofs = list[i].stm_ofs; /* correct stream length for unencrypted documents */ if (!encrypt && list[i].stm_len >= 0) { dict = pdf_load_object(ctx, doc, list[i].num); length = pdf_new_int(ctx, doc, list[i].stm_len); pdf_dict_put(ctx, dict, PDF_NAME_Length, length); pdf_drop_obj(ctx, length); pdf_drop_obj(ctx, dict); } } entry = pdf_get_populating_xref_entry(ctx, doc, 0); entry->type = 'f'; entry->ofs = 0; entry->gen = 65535; entry->num = 0; entry->stm_ofs = 0; next = 0; /* correct stream length for unencrypted documents */ if (!encrypt && list[i].stm_len >= 0) { pdf_obj *old_obj = NULL; dict = pdf_load_object(ctx, doc, list[i].num); length = pdf_new_int(ctx, doc, list[i].stm_len); pdf_dict_get_put_drop(ctx, dict, PDF_NAME_Length, length, &old_obj); if (old_obj) orphan_object(ctx, doc, old_obj); pdf_drop_obj(ctx, dict); } } obj = pdf_new_dict(ctx, doc, 5); /* During repair there is only a single xref section */ pdf_set_populating_xref_trailer(ctx, doc, obj); pdf_drop_obj(ctx, obj); obj = NULL; obj = pdf_new_int(ctx, doc, maxnum + 1); pdf_dict_put(ctx, pdf_trailer(ctx, doc), PDF_NAME_Size, obj); pdf_drop_obj(ctx, obj); obj = NULL; if (roots) { int i; for (i = num_roots-1; i > 0; i--) { if (pdf_is_dict(ctx, roots[i])) break; } if (i >= 0) { pdf_dict_put(ctx, pdf_trailer(ctx, doc), PDF_NAME_Root, roots[i]); } } if (info) { pdf_dict_put(ctx, pdf_trailer(ctx, doc), PDF_NAME_Info, info); pdf_drop_obj(ctx, info); info = NULL; } if (encrypt) { if (pdf_is_indirect(ctx, encrypt)) { /* create new reference with non-NULL xref pointer */ obj = pdf_new_indirect(ctx, doc, pdf_to_num(ctx, encrypt), pdf_to_gen(ctx, encrypt)); pdf_drop_obj(ctx, encrypt); encrypt = obj; obj = NULL; } pdf_dict_put(ctx, pdf_trailer(ctx, doc), PDF_NAME_Encrypt, encrypt); pdf_drop_obj(ctx, encrypt); encrypt = NULL; } if (id) { if (pdf_is_indirect(ctx, id)) { /* create new reference with non-NULL xref pointer */ obj = pdf_new_indirect(ctx, doc, pdf_to_num(ctx, id), pdf_to_gen(ctx, id)); pdf_drop_obj(ctx, id); id = obj; obj = NULL; } pdf_dict_put(ctx, pdf_trailer(ctx, doc), PDF_NAME_ID, id); pdf_drop_obj(ctx, id); id = NULL; } fz_free(ctx, list); }
165,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_video::allocate_input_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned i = 0; DEBUG_PRINT_HIGH("allocate_input_buffer()::"); if (bytes != m_sInPortDef.nBufferSize) { DEBUG_PRINT_ERROR("ERROR: Buffer size mismatch error: bytes[%u] != nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize); return OMX_ErrorBadParameter; } if (!m_inp_mem_ptr) { DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__, (unsigned int)m_sInPortDef.nBufferSize, (unsigned int)m_sInPortDef.nBufferCountActual); m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \ calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual); if (m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr"); return OMX_ErrorInsufficientResources; } DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr); m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual); if (m_pInput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem"); return OMX_ErrorInsufficientResources; } #ifdef USE_ION m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual); if (m_pInput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion"); return OMX_ErrorInsufficientResources; } #endif for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { m_pInput_pmem[i].fd = -1; #ifdef USE_ION m_pInput_ion[i].ion_device_fd =-1; m_pInput_ion[i].fd_ion_data.fd =-1; m_pInput_ion[i].ion_alloc_data.handle = 0; #endif } } for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_inp_bm_count,i)) { break; } } if (i < m_sInPortDef.nBufferCountActual) { *bufferHdr = (m_inp_mem_ptr + i); (*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE); (*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION; (*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize; (*bufferHdr)->pAppPrivate = appData; (*bufferHdr)->nInputPortIndex = PORT_INDEX_IN; (*bufferHdr)->pInputPortPrivate = (OMX_PTR)&m_pInput_pmem[i]; #ifdef USE_ION #ifdef _MSM8974_ m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,0); #else m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pInput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd; #else m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pInput_pmem[i].fd == 0) { m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pInput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed"); return OMX_ErrorInsufficientResources; } #endif m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].offset = 0; m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { m_pInput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pInput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pInput_pmem[i].fd,0); if (m_pInput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: mmap FAILED= %d", errno); close(m_pInput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } else { m_pInput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); } (*bufferHdr)->pBuffer = (OMX_U8 *)m_pInput_pmem[i].buffer; DEBUG_PRINT_LOW("Virtual address in allocate buffer is %p", m_pInput_pmem[i].buffer); BITMASK_SET(&m_inp_bm_count,i); if (!mUseProxyColorFormat && (dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true)) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for i/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All i/p buffers are allocated, invalid allocate buf call" "for index [%d]", i); eRet = OMX_ErrorInsufficientResources; } return eRet; } Commit Message: DO NOT MERGE Fix wrong nAllocLen Set nAllocLen to the size of the opaque handle itself. Bug: 28816964 Bug: 28816827 Change-Id: Id410e324bee291d4a0018dddb97eda9bbcded099 CWE ID: CWE-119
OMX_ERRORTYPE omx_video::allocate_input_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned i = 0; DEBUG_PRINT_HIGH("allocate_input_buffer()::"); if (bytes != m_sInPortDef.nBufferSize) { DEBUG_PRINT_ERROR("ERROR: Buffer size mismatch error: bytes[%u] != nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize); return OMX_ErrorBadParameter; } if (!m_inp_mem_ptr) { DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__, (unsigned int)m_sInPortDef.nBufferSize, (unsigned int)m_sInPortDef.nBufferCountActual); m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \ calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual); if (m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr"); return OMX_ErrorInsufficientResources; } DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr); m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual); if (m_pInput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem"); return OMX_ErrorInsufficientResources; } #ifdef USE_ION m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual); if (m_pInput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion"); return OMX_ErrorInsufficientResources; } #endif for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { m_pInput_pmem[i].fd = -1; #ifdef USE_ION m_pInput_ion[i].ion_device_fd =-1; m_pInput_ion[i].fd_ion_data.fd =-1; m_pInput_ion[i].ion_alloc_data.handle = 0; #endif } } for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_inp_bm_count,i)) { break; } } if (i < m_sInPortDef.nBufferCountActual) { *bufferHdr = (m_inp_mem_ptr + i); (*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE); (*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION; (*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize; (*bufferHdr)->pAppPrivate = appData; (*bufferHdr)->nInputPortIndex = PORT_INDEX_IN; (*bufferHdr)->pInputPortPrivate = (OMX_PTR)&m_pInput_pmem[i]; #ifdef USE_ION #ifdef _MSM8974_ m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,0); #else m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pInput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd; #else m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pInput_pmem[i].fd == 0) { m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pInput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed"); return OMX_ErrorInsufficientResources; } #endif m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].offset = 0; m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { m_pInput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pInput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pInput_pmem[i].fd,0); if (m_pInput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: mmap FAILED= %d", errno); close(m_pInput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } else { m_pInput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); (*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*); } (*bufferHdr)->pBuffer = (OMX_U8 *)m_pInput_pmem[i].buffer; DEBUG_PRINT_LOW("Virtual address in allocate buffer is %p", m_pInput_pmem[i].buffer); BITMASK_SET(&m_inp_bm_count,i); if (!mUseProxyColorFormat && (dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true)) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for i/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All i/p buffers are allocated, invalid allocate buf call" "for index [%d]", i); eRet = OMX_ErrorInsufficientResources; } return eRet; }
173,519
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: pdf_load_xobject(fz_context *ctx, pdf_document *doc, pdf_obj *dict) { pdf_xobject *form; if ((form = pdf_find_item(ctx, pdf_drop_xobject_imp, dict)) != NULL) return form; form->iteration = 0; /* Store item immediately, to avoid possible recursion if objects refer back to this one */ pdf_store_item(ctx, dict, form, pdf_xobject_size(form)); form->obj = pdf_keep_obj(ctx, dict); return form; } Commit Message: CWE ID: CWE-20
pdf_load_xobject(fz_context *ctx, pdf_document *doc, pdf_obj *dict) { pdf_xobject *form; if (!pdf_is_stream(ctx, dict)) fz_throw(ctx, FZ_ERROR_SYNTAX, "XObject must be a stream"); if ((form = pdf_find_item(ctx, pdf_drop_xobject_imp, dict)) != NULL) return form; form->iteration = 0; /* Store item immediately, to avoid possible recursion if objects refer back to this one */ pdf_store_item(ctx, dict, form, pdf_xobject_size(form)); form->obj = pdf_keep_obj(ctx, dict); return form; }
164,582
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
void *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; // Don't load any DLLs that end with the pk3 extension if (COM_CompareExtension(name, ".pk3")) { Com_Printf("Rejecting DLL named \"%s\"", name); return NULL; } if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; }
170,084
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PromoResourceService::PostNotification(int64 delay_ms) { if (web_resource_update_scheduled_) return; if (delay_ms > 0) { web_resource_update_scheduled_ = true; MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PromoResourceService::PromoResourceStateChange, weak_ptr_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(delay_ms)); } else if (delay_ms == 0) { PromoResourceStateChange(); } } Commit Message: Refresh promo notifications as they're fetched The "guard" existed for notification scheduling was preventing "turn-off a promo" and "update a promo" scenarios. Yet I do not believe it was adding any actual safety: if things on a server backend go wrong, the clients will be affected one way or the other, and it is better to have an option to shut the malformed promo down "as quickly as possible" (~in 12-24 hours). BUG= TEST= Review URL: https://chromiumcodereview.appspot.com/10696204 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void PromoResourceService::PostNotification(int64 delay_ms) { // Note that this could cause re-issuing a notification every time // we receive an update from a server if something goes wrong. // Given that this couldn't happen more frequently than every // kCacheUpdateDelay milliseconds, we should be fine. if (delay_ms > 0) { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PromoResourceService::PromoResourceStateChange, weak_ptr_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(delay_ms)); } else if (delay_ms == 0) { PromoResourceStateChange(); } }
170,781
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: fgetwln(FILE *stream, size_t *lenp) { struct filewbuf *fb; wint_t wc; size_t wused = 0; /* Try to diminish the possibility of several fgetwln() calls being * used on different streams, by using a pool of buffers per file. */ fb = &fb_pool[fb_pool_cur]; if (fb->fp != stream && fb->fp != NULL) { fb_pool_cur++; fb_pool_cur %= FILEWBUF_POOL_ITEMS; fb = &fb_pool[fb_pool_cur]; } fb->fp = stream; while ((wc = fgetwc(stream)) != WEOF) { if (!fb->len || wused > fb->len) { wchar_t *wp; if (fb->len) fb->len *= 2; else fb->len = FILEWBUF_INIT_LEN; wp = reallocarray(fb->wbuf, fb->len, sizeof(wchar_t)); if (wp == NULL) { wused = 0; break; } fb->wbuf = wp; } fb->wbuf[wused++] = wc; if (wc == L'\n') break; } *lenp = wused; return wused ? fb->wbuf : NULL; } Commit Message: CWE ID: CWE-119
fgetwln(FILE *stream, size_t *lenp) { struct filewbuf *fb; wint_t wc; size_t wused = 0; /* Try to diminish the possibility of several fgetwln() calls being * used on different streams, by using a pool of buffers per file. */ fb = &fb_pool[fb_pool_cur]; if (fb->fp != stream && fb->fp != NULL) { fb_pool_cur++; fb_pool_cur %= FILEWBUF_POOL_ITEMS; fb = &fb_pool[fb_pool_cur]; } fb->fp = stream; while ((wc = fgetwc(stream)) != WEOF) { if (!fb->len || wused >= fb->len) { wchar_t *wp; if (fb->len) fb->len *= 2; else fb->len = FILEWBUF_INIT_LEN; wp = reallocarray(fb->wbuf, fb->len, sizeof(wchar_t)); if (wp == NULL) { wused = 0; break; } fb->wbuf = wp; } fb->wbuf[wused++] = wc; if (wc == L'\n') break; } *lenp = wused; return wused ? fb->wbuf : NULL; }
165,350
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void exit_io_context(void) { struct io_context *ioc; task_lock(current); ioc = current->io_context; current->io_context = NULL; task_unlock(current); if (atomic_dec_and_test(&ioc->nr_tasks)) { if (ioc->aic && ioc->aic->exit) ioc->aic->exit(ioc->aic); cfq_exit(ioc); } put_io_context(ioc); } Commit Message: block: Fix io_context leak after failure of clone with CLONE_IO With CLONE_IO, parent's io_context->nr_tasks is incremented, but never decremented whenever copy_process() fails afterwards, which prevents exit_io_context() from calling IO schedulers exit functions. Give a task_struct to exit_io_context(), and call exit_io_context() instead of put_io_context() in copy_process() cleanup path. Signed-off-by: Louis Rilling <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-20
void exit_io_context(void) void exit_io_context(struct task_struct *task) { struct io_context *ioc; task_lock(task); ioc = task->io_context; task->io_context = NULL; task_unlock(task); if (atomic_dec_and_test(&ioc->nr_tasks)) { if (ioc->aic && ioc->aic->exit) ioc->aic->exit(ioc->aic); cfq_exit(ioc); } put_io_context(ioc); }
169,885
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int airspy_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct airspy *s; int ret; u8 u8tmp, buf[BUF_SIZE]; s = kzalloc(sizeof(struct airspy), GFP_KERNEL); if (s == NULL) { dev_err(&intf->dev, "Could not allocate memory for state\n"); return -ENOMEM; } mutex_init(&s->v4l2_lock); mutex_init(&s->vb_queue_lock); spin_lock_init(&s->queued_bufs_lock); INIT_LIST_HEAD(&s->queued_bufs); s->dev = &intf->dev; s->udev = interface_to_usbdev(intf); s->f_adc = bands[0].rangelow; s->f_rf = bands_rf[0].rangelow; s->pixelformat = formats[0].pixelformat; s->buffersize = formats[0].buffersize; /* Detect device */ ret = airspy_ctrl_msg(s, CMD_BOARD_ID_READ, 0, 0, &u8tmp, 1); if (ret == 0) ret = airspy_ctrl_msg(s, CMD_VERSION_STRING_READ, 0, 0, buf, BUF_SIZE); if (ret) { dev_err(s->dev, "Could not detect board\n"); goto err_free_mem; } buf[BUF_SIZE - 1] = '\0'; dev_info(s->dev, "Board ID: %02x\n", u8tmp); dev_info(s->dev, "Firmware version: %s\n", buf); /* Init videobuf2 queue structure */ s->vb_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE; s->vb_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ; s->vb_queue.drv_priv = s; s->vb_queue.buf_struct_size = sizeof(struct airspy_frame_buf); s->vb_queue.ops = &airspy_vb2_ops; s->vb_queue.mem_ops = &vb2_vmalloc_memops; s->vb_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC; ret = vb2_queue_init(&s->vb_queue); if (ret) { dev_err(s->dev, "Could not initialize vb2 queue\n"); goto err_free_mem; } /* Init video_device structure */ s->vdev = airspy_template; s->vdev.queue = &s->vb_queue; s->vdev.queue->lock = &s->vb_queue_lock; video_set_drvdata(&s->vdev, s); /* Register the v4l2_device structure */ s->v4l2_dev.release = airspy_video_release; ret = v4l2_device_register(&intf->dev, &s->v4l2_dev); if (ret) { dev_err(s->dev, "Failed to register v4l2-device (%d)\n", ret); goto err_free_mem; } /* Register controls */ v4l2_ctrl_handler_init(&s->hdl, 5); s->lna_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_LNA_GAIN_AUTO, 0, 1, 1, 0); s->lna_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_LNA_GAIN, 0, 14, 1, 8); v4l2_ctrl_auto_cluster(2, &s->lna_gain_auto, 0, false); s->mixer_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO, 0, 1, 1, 0); s->mixer_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_MIXER_GAIN, 0, 15, 1, 8); v4l2_ctrl_auto_cluster(2, &s->mixer_gain_auto, 0, false); s->if_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_IF_GAIN, 0, 15, 1, 0); if (s->hdl.error) { ret = s->hdl.error; dev_err(s->dev, "Could not initialize controls\n"); goto err_free_controls; } v4l2_ctrl_handler_setup(&s->hdl); s->v4l2_dev.ctrl_handler = &s->hdl; s->vdev.v4l2_dev = &s->v4l2_dev; s->vdev.lock = &s->v4l2_lock; ret = video_register_device(&s->vdev, VFL_TYPE_SDR, -1); if (ret) { dev_err(s->dev, "Failed to register as video device (%d)\n", ret); goto err_unregister_v4l2_dev; } dev_info(s->dev, "Registered as %s\n", video_device_node_name(&s->vdev)); dev_notice(s->dev, "SDR API is still slightly experimental and functionality changes may follow\n"); return 0; err_free_controls: v4l2_ctrl_handler_free(&s->hdl); err_unregister_v4l2_dev: v4l2_device_unregister(&s->v4l2_dev); err_free_mem: kfree(s); return ret; } Commit Message: media: fix airspy usb probe error path Fix a memory leak on probe error of the airspy usb device driver. The problem is triggered when more than 64 usb devices register with v4l2 of type VFL_TYPE_SDR or VFL_TYPE_SUBDEV. The memory leak is caused by the probe function of the airspy driver mishandeling errors and not freeing the corresponding control structures when an error occours registering the device to v4l2 core. A badusb device can emulate 64 of these devices, and then through continual emulated connect/disconnect of the 65th device, cause the kernel to run out of RAM and crash the kernel, thus causing a local DOS vulnerability. Fixes CVE-2016-5400 Signed-off-by: James Patrick-Evans <[email protected]> Reviewed-by: Kees Cook <[email protected]> Cc: [email protected] # 3.17+ Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-119
static int airspy_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct airspy *s; int ret; u8 u8tmp, buf[BUF_SIZE]; s = kzalloc(sizeof(struct airspy), GFP_KERNEL); if (s == NULL) { dev_err(&intf->dev, "Could not allocate memory for state\n"); return -ENOMEM; } mutex_init(&s->v4l2_lock); mutex_init(&s->vb_queue_lock); spin_lock_init(&s->queued_bufs_lock); INIT_LIST_HEAD(&s->queued_bufs); s->dev = &intf->dev; s->udev = interface_to_usbdev(intf); s->f_adc = bands[0].rangelow; s->f_rf = bands_rf[0].rangelow; s->pixelformat = formats[0].pixelformat; s->buffersize = formats[0].buffersize; /* Detect device */ ret = airspy_ctrl_msg(s, CMD_BOARD_ID_READ, 0, 0, &u8tmp, 1); if (ret == 0) ret = airspy_ctrl_msg(s, CMD_VERSION_STRING_READ, 0, 0, buf, BUF_SIZE); if (ret) { dev_err(s->dev, "Could not detect board\n"); goto err_free_mem; } buf[BUF_SIZE - 1] = '\0'; dev_info(s->dev, "Board ID: %02x\n", u8tmp); dev_info(s->dev, "Firmware version: %s\n", buf); /* Init videobuf2 queue structure */ s->vb_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE; s->vb_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ; s->vb_queue.drv_priv = s; s->vb_queue.buf_struct_size = sizeof(struct airspy_frame_buf); s->vb_queue.ops = &airspy_vb2_ops; s->vb_queue.mem_ops = &vb2_vmalloc_memops; s->vb_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC; ret = vb2_queue_init(&s->vb_queue); if (ret) { dev_err(s->dev, "Could not initialize vb2 queue\n"); goto err_free_mem; } /* Init video_device structure */ s->vdev = airspy_template; s->vdev.queue = &s->vb_queue; s->vdev.queue->lock = &s->vb_queue_lock; video_set_drvdata(&s->vdev, s); /* Register the v4l2_device structure */ s->v4l2_dev.release = airspy_video_release; ret = v4l2_device_register(&intf->dev, &s->v4l2_dev); if (ret) { dev_err(s->dev, "Failed to register v4l2-device (%d)\n", ret); goto err_free_mem; } /* Register controls */ v4l2_ctrl_handler_init(&s->hdl, 5); s->lna_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_LNA_GAIN_AUTO, 0, 1, 1, 0); s->lna_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_LNA_GAIN, 0, 14, 1, 8); v4l2_ctrl_auto_cluster(2, &s->lna_gain_auto, 0, false); s->mixer_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO, 0, 1, 1, 0); s->mixer_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_MIXER_GAIN, 0, 15, 1, 8); v4l2_ctrl_auto_cluster(2, &s->mixer_gain_auto, 0, false); s->if_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_IF_GAIN, 0, 15, 1, 0); if (s->hdl.error) { ret = s->hdl.error; dev_err(s->dev, "Could not initialize controls\n"); goto err_free_controls; } v4l2_ctrl_handler_setup(&s->hdl); s->v4l2_dev.ctrl_handler = &s->hdl; s->vdev.v4l2_dev = &s->v4l2_dev; s->vdev.lock = &s->v4l2_lock; ret = video_register_device(&s->vdev, VFL_TYPE_SDR, -1); if (ret) { dev_err(s->dev, "Failed to register as video device (%d)\n", ret); goto err_free_controls; } dev_info(s->dev, "Registered as %s\n", video_device_node_name(&s->vdev)); dev_notice(s->dev, "SDR API is still slightly experimental and functionality changes may follow\n"); return 0; err_free_controls: v4l2_ctrl_handler_free(&s->hdl); v4l2_device_unregister(&s->v4l2_dev); err_free_mem: kfree(s); return ret; }
167,138
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType debug, status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFErrorHandler error_handler, warning_handler; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) MagickSetThreadValue(tiff_exception,exception); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); image=DestroyImageList(image); return((Image *) NULL); } debug=IsEventLogging(); (void) debug; if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. */ for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: case PHOTOMETRIC_LOGLUV: { (void) TIFFSetField(tiff,TIFFTAG_SGILOGDATAFMT,SGILOGDATAFMT_FLOAT); break; } case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING, &horizontal,&vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJpegMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; pixels=GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ if ((image->storage_class == PseudoClass) && (photometric == PHOTOMETRIC_PALETTE)) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p)))); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum((unsigned char) (TIFFGetA(*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; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; size_t number_pixels; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass); number_pixels=columns*rows; tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels, sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *restrict q; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); q++; p++; } p+=columns-columns_remaining; q-=(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t) (number_pixels*sizeof(uint32)))) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*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; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } if (image->storage_class == PseudoClass) image->depth=GetImageDepth(image,exception); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* 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,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); TIFFClose(tiff); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType debug, status; MagickSizeType number_pixels; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t pad; ssize_t y; TIFF *tiff; TIFFErrorHandler error_handler, warning_handler; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *pixels; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) MagickSetThreadValue(tiff_exception,exception); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); image=DestroyImageList(image); return((Image *) NULL); } debug=IsEventLogging(); (void) debug; if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. */ for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: case PHOTOMETRIC_LOGLUV: { (void) TIFFSetField(tiff,TIFFTAG_SGILOGDATAFMT,SGILOGDATAFMT_FLOAT); break; } case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING, &horizontal,&vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; default: image->compression=RLECompression; break; } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJpegMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; pixels=GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ if ((image->storage_class == PseudoClass) && (photometric == PHOTOMETRIC_PALETTE)) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ i=0; p=(uint32 *) NULL; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p)))); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum((unsigned char) (TIFFGetA(*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; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; size_t number_pixels; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass); number_pixels=columns*rows; tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels, sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *restrict q; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); q++; p++; } p+=columns-columns_remaining; q-=(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ number_pixels=(MagickSizeType) image->columns*image->rows; if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t) (number_pixels*sizeof(uint32)))) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(uint32)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*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; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } if (image->storage_class == PseudoClass) image->depth=GetImageDepth(image,exception); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* 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,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); TIFFClose(tiff); return(GetFirstImageInList(image)); }
168,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct rds_connection *__rds_conn_create(struct net *net, __be32 laddr, __be32 faddr, struct rds_transport *trans, gfp_t gfp, int is_outgoing) { struct rds_connection *conn, *parent = NULL; struct hlist_head *head = rds_conn_bucket(laddr, faddr); struct rds_transport *loop_trans; unsigned long flags; int ret; rcu_read_lock(); conn = rds_conn_lookup(net, head, laddr, faddr, trans); if (conn && conn->c_loopback && conn->c_trans != &rds_loop_transport && laddr == faddr && !is_outgoing) { /* This is a looped back IB connection, and we're * called by the code handling the incoming connect. * We need a second connection object into which we * can stick the other QP. */ parent = conn; conn = parent->c_passive; } rcu_read_unlock(); if (conn) goto out; conn = kmem_cache_zalloc(rds_conn_slab, gfp); if (!conn) { conn = ERR_PTR(-ENOMEM); goto out; } INIT_HLIST_NODE(&conn->c_hash_node); conn->c_laddr = laddr; conn->c_faddr = faddr; spin_lock_init(&conn->c_lock); conn->c_next_tx_seq = 1; rds_conn_net_set(conn, net); init_waitqueue_head(&conn->c_waitq); INIT_LIST_HEAD(&conn->c_send_queue); INIT_LIST_HEAD(&conn->c_retrans); ret = rds_cong_get_maps(conn); if (ret) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(ret); goto out; } /* * This is where a connection becomes loopback. If *any* RDS sockets * can bind to the destination address then we'd rather the messages * flow through loopback rather than either transport. */ loop_trans = rds_trans_get_preferred(net, faddr); if (loop_trans) { rds_trans_put(loop_trans); conn->c_loopback = 1; if (is_outgoing && trans->t_prefer_loopback) { /* "outgoing" connection - and the transport * says it wants the connection handled by the * loopback transport. This is what TCP does. */ trans = &rds_loop_transport; } } if (trans == NULL) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(-ENODEV); goto out; } conn->c_trans = trans; ret = trans->conn_alloc(conn, gfp); if (ret) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(ret); goto out; } atomic_set(&conn->c_state, RDS_CONN_DOWN); conn->c_send_gen = 0; conn->c_outgoing = (is_outgoing ? 1 : 0); conn->c_reconnect_jiffies = 0; INIT_DELAYED_WORK(&conn->c_send_w, rds_send_worker); INIT_DELAYED_WORK(&conn->c_recv_w, rds_recv_worker); INIT_DELAYED_WORK(&conn->c_conn_w, rds_connect_worker); INIT_WORK(&conn->c_down_w, rds_shutdown_worker); mutex_init(&conn->c_cm_lock); conn->c_flags = 0; rdsdebug("allocated conn %p for %pI4 -> %pI4 over %s %s\n", conn, &laddr, &faddr, trans->t_name ? trans->t_name : "[unknown]", is_outgoing ? "(outgoing)" : ""); /* * Since we ran without holding the conn lock, someone could * have created the same conn (either normal or passive) in the * interim. We check while holding the lock. If we won, we complete * init and return our conn. If we lost, we rollback and return the * other one. */ spin_lock_irqsave(&rds_conn_lock, flags); if (parent) { /* Creating passive conn */ if (parent->c_passive) { trans->conn_free(conn->c_transport_data); kmem_cache_free(rds_conn_slab, conn); conn = parent->c_passive; } else { parent->c_passive = conn; rds_cong_add_conn(conn); rds_conn_count++; } } else { /* Creating normal conn */ struct rds_connection *found; found = rds_conn_lookup(net, head, laddr, faddr, trans); if (found) { trans->conn_free(conn->c_transport_data); kmem_cache_free(rds_conn_slab, conn); conn = found; } else { hlist_add_head_rcu(&conn->c_hash_node, head); rds_cong_add_conn(conn); rds_conn_count++; } } spin_unlock_irqrestore(&rds_conn_lock, flags); out: return conn; } Commit Message: RDS: fix race condition when sending a message on unbound socket Sasha's found a NULL pointer dereference in the RDS connection code when sending a message to an apparently unbound socket. The problem is caused by the code checking if the socket is bound in rds_sendmsg(), which checks the rs_bound_addr field without taking a lock on the socket. This opens a race where rs_bound_addr is temporarily set but where the transport is not in rds_bind(), leading to a NULL pointer dereference when trying to dereference 'trans' in __rds_conn_create(). Vegard wrote a reproducer for this issue, so kindly ask him to share if you're interested. I cannot reproduce the NULL pointer dereference using Vegard's reproducer with this patch, whereas I could without. Complete earlier incomplete fix to CVE-2015-6937: 74e98eb08588 ("RDS: verify the underlying transport exists before creating a connection") Cc: David S. Miller <[email protected]> Cc: [email protected] Reviewed-by: Vegard Nossum <[email protected]> Reviewed-by: Sasha Levin <[email protected]> Acked-by: Santosh Shilimkar <[email protected]> Signed-off-by: Quentin Casasnovas <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static struct rds_connection *__rds_conn_create(struct net *net, __be32 laddr, __be32 faddr, struct rds_transport *trans, gfp_t gfp, int is_outgoing) { struct rds_connection *conn, *parent = NULL; struct hlist_head *head = rds_conn_bucket(laddr, faddr); struct rds_transport *loop_trans; unsigned long flags; int ret; rcu_read_lock(); conn = rds_conn_lookup(net, head, laddr, faddr, trans); if (conn && conn->c_loopback && conn->c_trans != &rds_loop_transport && laddr == faddr && !is_outgoing) { /* This is a looped back IB connection, and we're * called by the code handling the incoming connect. * We need a second connection object into which we * can stick the other QP. */ parent = conn; conn = parent->c_passive; } rcu_read_unlock(); if (conn) goto out; conn = kmem_cache_zalloc(rds_conn_slab, gfp); if (!conn) { conn = ERR_PTR(-ENOMEM); goto out; } INIT_HLIST_NODE(&conn->c_hash_node); conn->c_laddr = laddr; conn->c_faddr = faddr; spin_lock_init(&conn->c_lock); conn->c_next_tx_seq = 1; rds_conn_net_set(conn, net); init_waitqueue_head(&conn->c_waitq); INIT_LIST_HEAD(&conn->c_send_queue); INIT_LIST_HEAD(&conn->c_retrans); ret = rds_cong_get_maps(conn); if (ret) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(ret); goto out; } /* * This is where a connection becomes loopback. If *any* RDS sockets * can bind to the destination address then we'd rather the messages * flow through loopback rather than either transport. */ loop_trans = rds_trans_get_preferred(net, faddr); if (loop_trans) { rds_trans_put(loop_trans); conn->c_loopback = 1; if (is_outgoing && trans->t_prefer_loopback) { /* "outgoing" connection - and the transport * says it wants the connection handled by the * loopback transport. This is what TCP does. */ trans = &rds_loop_transport; } } conn->c_trans = trans; ret = trans->conn_alloc(conn, gfp); if (ret) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(ret); goto out; } atomic_set(&conn->c_state, RDS_CONN_DOWN); conn->c_send_gen = 0; conn->c_outgoing = (is_outgoing ? 1 : 0); conn->c_reconnect_jiffies = 0; INIT_DELAYED_WORK(&conn->c_send_w, rds_send_worker); INIT_DELAYED_WORK(&conn->c_recv_w, rds_recv_worker); INIT_DELAYED_WORK(&conn->c_conn_w, rds_connect_worker); INIT_WORK(&conn->c_down_w, rds_shutdown_worker); mutex_init(&conn->c_cm_lock); conn->c_flags = 0; rdsdebug("allocated conn %p for %pI4 -> %pI4 over %s %s\n", conn, &laddr, &faddr, trans->t_name ? trans->t_name : "[unknown]", is_outgoing ? "(outgoing)" : ""); /* * Since we ran without holding the conn lock, someone could * have created the same conn (either normal or passive) in the * interim. We check while holding the lock. If we won, we complete * init and return our conn. If we lost, we rollback and return the * other one. */ spin_lock_irqsave(&rds_conn_lock, flags); if (parent) { /* Creating passive conn */ if (parent->c_passive) { trans->conn_free(conn->c_transport_data); kmem_cache_free(rds_conn_slab, conn); conn = parent->c_passive; } else { parent->c_passive = conn; rds_cong_add_conn(conn); rds_conn_count++; } } else { /* Creating normal conn */ struct rds_connection *found; found = rds_conn_lookup(net, head, laddr, faddr, trans); if (found) { trans->conn_free(conn->c_transport_data); kmem_cache_free(rds_conn_slab, conn); conn = found; } else { hlist_add_head_rcu(&conn->c_hash_node, head); rds_cong_add_conn(conn); rds_conn_count++; } } spin_unlock_irqrestore(&rds_conn_lock, flags); out: return conn; }
166,572
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color) { int lastBorder; /* Seek left */ int leftLimit = -1, rightLimit; int i, restoreAlphaBlending = 0; if (border < 0) { /* Refuse to fill to a non-solid border */ return; } if (!im->trueColor) { if ((color > (im->colorsTotal - 1)) || (border > (im->colorsTotal - 1)) || (color < 0)) { return; } } restoreAlphaBlending = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (x >= im->sx) { x = im->sx - 1; } else if (x < 0) { x = 0; } if (y >= im->sy) { y = im->sy - 1; } else if (y < 0) { y = 0; } for (i = x; i >= 0; i--) { if (gdImageGetPixel(im, i, y) == border) { break; } gdImageSetPixel(im, i, y, color); leftLimit = i; } if (leftLimit == -1) { im->alphaBlendingFlag = restoreAlphaBlending; return; } /* Seek right */ rightLimit = x; for (i = (x + 1); i < im->sx; i++) { if (gdImageGetPixel(im, i, y) == border) { break; } gdImageSetPixel(im, i, y, color); rightLimit = i; } /* Look at lines above and below and start paints */ /* Above */ if (y > 0) { lastBorder = 1; for (i = leftLimit; i <= rightLimit; i++) { int c = gdImageGetPixel(im, i, y - 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder(im, i, y - 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } /* Below */ if (y < ((im->sy) - 1)) { lastBorder = 1; for (i = leftLimit; i <= rightLimit; i++) { int c = gdImageGetPixel(im, i, y + 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder(im, i, y + 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } im->alphaBlendingFlag = restoreAlphaBlending; } Commit Message: Fix #72696: imagefilltoborder stackoverflow on truecolor images We must not allow negative color values be passed to gdImageFillToBorder(), because that can lead to infinite recursion since the recursion termination condition will not necessarily be met. CWE ID: CWE-119
void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color) { int lastBorder; /* Seek left */ int leftLimit = -1, rightLimit; int i, restoreAlphaBlending = 0; if (border < 0 || color < 0) { /* Refuse to fill to a non-solid border */ return; } if (!im->trueColor) { if ((color > (im->colorsTotal - 1)) || (border > (im->colorsTotal - 1)) || (color < 0)) { return; } } restoreAlphaBlending = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (x >= im->sx) { x = im->sx - 1; } else if (x < 0) { x = 0; } if (y >= im->sy) { y = im->sy - 1; } else if (y < 0) { y = 0; } for (i = x; i >= 0; i--) { if (gdImageGetPixel(im, i, y) == border) { break; } gdImageSetPixel(im, i, y, color); leftLimit = i; } if (leftLimit == -1) { im->alphaBlendingFlag = restoreAlphaBlending; return; } /* Seek right */ rightLimit = x; for (i = (x + 1); i < im->sx; i++) { if (gdImageGetPixel(im, i, y) == border) { break; } gdImageSetPixel(im, i, y, color); rightLimit = i; } /* Look at lines above and below and start paints */ /* Above */ if (y > 0) { lastBorder = 1; for (i = leftLimit; i <= rightLimit; i++) { int c = gdImageGetPixel(im, i, y - 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder(im, i, y - 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } /* Below */ if (y < ((im->sy) - 1)) { lastBorder = 1; for (i = leftLimit; i <= rightLimit; i++) { int c = gdImageGetPixel(im, i, y + 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder(im, i, y + 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } im->alphaBlendingFlag = restoreAlphaBlending; }
168,671
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, NULL ) ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted CWE ID: CWE-200
int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, NULL, NULL, NULL ) ); } int mbedtls_ecdsa_sign_det_ext( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); ECDSA_VALIDATE_RET( f_rng_blind != NULL ); return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, f_rng_blind, p_rng_blind, NULL ) ); }
169,508
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromotingInstance::Init(uint32_t argc, const char* argn[], const char* argv[]) { CHECK(!initialized_); initialized_ = true; VLOG(1) << "Started ChromotingInstance::Init"; if (!media::IsMediaLibraryInitialized()) { LOG(ERROR) << "Media library not initialized."; return false; } net::EnableSSLServerSockets(); context_.Start(); scoped_refptr<FrameConsumerProxy> consumer_proxy = new FrameConsumerProxy(plugin_task_runner_); rectangle_decoder_ = new RectangleUpdateDecoder(context_.main_task_runner(), context_.decode_task_runner(), consumer_proxy); view_.reset(new PepperView(this, &context_, rectangle_decoder_.get())); consumer_proxy->Attach(view_->AsWeakPtr()); return true; } Commit Message: Restrict the Chromoting client plugin to use by extensions & apps. BUG=160456 Review URL: https://chromiumcodereview.appspot.com/11365276 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168289 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool ChromotingInstance::Init(uint32_t argc, const char* argn[], const char* argv[]) { CHECK(!initialized_); initialized_ = true; VLOG(1) << "Started ChromotingInstance::Init"; if (!media::IsMediaLibraryInitialized()) { LOG(ERROR) << "Media library not initialized."; return false; } // Check that the calling content is part of an app or extension. if (!IsCallerAppOrExtension()) { LOG(ERROR) << "Not an app or extension"; return false; } net::EnableSSLServerSockets(); context_.Start(); scoped_refptr<FrameConsumerProxy> consumer_proxy = new FrameConsumerProxy(plugin_task_runner_); rectangle_decoder_ = new RectangleUpdateDecoder(context_.main_task_runner(), context_.decode_task_runner(), consumer_proxy); view_.reset(new PepperView(this, &context_, rectangle_decoder_.get())); consumer_proxy->Attach(view_->AsWeakPtr()); return true; }
170,671
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: IW_IMPL(int) iw_get_i32le(const iw_byte *b) { return (iw_int32)(iw_uint32)(b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24)); } Commit Message: Trying to fix some invalid left shift operations Fixes issue #16 CWE ID: CWE-682
IW_IMPL(int) iw_get_i32le(const iw_byte *b) { return (iw_int32)(iw_uint32)((unsigned int)b[0] | ((unsigned int)b[1]<<8) | ((unsigned int)b[2]<<16) | ((unsigned int)b[3]<<24)); }
168,196
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int PreProcessingFx_ProcessReverse(effect_handle_t self, audio_buffer_t *inBuffer, audio_buffer_t *outBuffer) { preproc_effect_t * effect = (preproc_effect_t *)self; int status = 0; if (effect == NULL){ ALOGW("PreProcessingFx_ProcessReverse() ERROR effect == NULL"); return -EINVAL; } preproc_session_t * session = (preproc_session_t *)effect->session; if (inBuffer == NULL || inBuffer->raw == NULL){ ALOGW("PreProcessingFx_ProcessReverse() ERROR bad pointer"); return -EINVAL; } session->revProcessedMsk |= (1<<effect->procId); if ((session->revProcessedMsk & session->revEnabledMsk) == session->revEnabledMsk) { effect->session->revProcessedMsk = 0; if (session->revResampler != NULL) { size_t fr = session->frameCount - session->framesRev; if (inBuffer->frameCount < fr) { fr = inBuffer->frameCount; } if (session->revBufSize < session->framesRev + fr) { session->revBufSize = session->framesRev + fr; session->revBuf = (int16_t *)realloc(session->revBuf, session->revBufSize * session->inChannelCount * sizeof(int16_t)); } memcpy(session->revBuf + session->framesRev * session->inChannelCount, inBuffer->s16, fr * session->inChannelCount * sizeof(int16_t)); session->framesRev += fr; inBuffer->frameCount = fr; if (session->framesRev < session->frameCount) { return 0; } spx_uint32_t frIn = session->framesRev; spx_uint32_t frOut = session->apmFrameCount; if (session->inChannelCount == 1) { speex_resampler_process_int(session->revResampler, 0, session->revBuf, &frIn, session->revFrame->_payloadData, &frOut); } else { speex_resampler_process_interleaved_int(session->revResampler, session->revBuf, &frIn, session->revFrame->_payloadData, &frOut); } memcpy(session->revBuf, session->revBuf + frIn * session->inChannelCount, (session->framesRev - frIn) * session->inChannelCount * sizeof(int16_t)); session->framesRev -= frIn; } else { size_t fr = session->frameCount - session->framesRev; if (inBuffer->frameCount < fr) { fr = inBuffer->frameCount; } memcpy(session->revFrame->_payloadData + session->framesRev * session->inChannelCount, inBuffer->s16, fr * session->inChannelCount * sizeof(int16_t)); session->framesRev += fr; inBuffer->frameCount = fr; if (session->framesRev < session->frameCount) { return 0; } session->framesRev = 0; } session->revFrame->_payloadDataLengthInSamples = session->apmFrameCount * session->inChannelCount; effect->session->apm->AnalyzeReverseStream(session->revFrame); return 0; } else { return -ENODATA; } } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int PreProcessingFx_ProcessReverse(effect_handle_t self, audio_buffer_t *inBuffer, audio_buffer_t *outBuffer __unused) { preproc_effect_t * effect = (preproc_effect_t *)self; int status = 0; if (effect == NULL){ ALOGW("PreProcessingFx_ProcessReverse() ERROR effect == NULL"); return -EINVAL; } preproc_session_t * session = (preproc_session_t *)effect->session; if (inBuffer == NULL || inBuffer->raw == NULL){ ALOGW("PreProcessingFx_ProcessReverse() ERROR bad pointer"); return -EINVAL; } session->revProcessedMsk |= (1<<effect->procId); if ((session->revProcessedMsk & session->revEnabledMsk) == session->revEnabledMsk) { effect->session->revProcessedMsk = 0; if (session->revResampler != NULL) { size_t fr = session->frameCount - session->framesRev; if (inBuffer->frameCount < fr) { fr = inBuffer->frameCount; } if (session->revBufSize < session->framesRev + fr) { session->revBufSize = session->framesRev + fr; session->revBuf = (int16_t *)realloc(session->revBuf, session->revBufSize * session->inChannelCount * sizeof(int16_t)); } memcpy(session->revBuf + session->framesRev * session->inChannelCount, inBuffer->s16, fr * session->inChannelCount * sizeof(int16_t)); session->framesRev += fr; inBuffer->frameCount = fr; if (session->framesRev < session->frameCount) { return 0; } spx_uint32_t frIn = session->framesRev; spx_uint32_t frOut = session->apmFrameCount; if (session->inChannelCount == 1) { speex_resampler_process_int(session->revResampler, 0, session->revBuf, &frIn, session->revFrame->_payloadData, &frOut); } else { speex_resampler_process_interleaved_int(session->revResampler, session->revBuf, &frIn, session->revFrame->_payloadData, &frOut); } memcpy(session->revBuf, session->revBuf + frIn * session->inChannelCount, (session->framesRev - frIn) * session->inChannelCount * sizeof(int16_t)); session->framesRev -= frIn; } else { size_t fr = session->frameCount - session->framesRev; if (inBuffer->frameCount < fr) { fr = inBuffer->frameCount; } memcpy(session->revFrame->_payloadData + session->framesRev * session->inChannelCount, inBuffer->s16, fr * session->inChannelCount * sizeof(int16_t)); session->framesRev += fr; inBuffer->frameCount = fr; if (session->framesRev < session->frameCount) { return 0; } session->framesRev = 0; } session->revFrame->_payloadDataLengthInSamples = session->apmFrameCount * session->inChannelCount; effect->session->apm->AnalyzeReverseStream(session->revFrame); return 0; } else { return -ENODATA; } }
173,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Chapters::Atom::~Atom() { } 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
Chapters::Atom::~Atom() const char* SegmentInfo::GetMuxingAppAsUTF8() const { return m_pMuxingAppAsUTF8; }
174,454
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab) { jpc_streamlist_t *streams; uchar *dataptr; uint_fast32_t datacnt; uint_fast32_t tpcnt; jpc_ppxstabent_t *ent; int entno; jas_stream_t *stream; int n; if (!(streams = jpc_streamlist_create())) { goto error; } if (!tab->numents) { return streams; } entno = 0; ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; for (;;) { /* Get the length of the packet header data for the current tile-part. */ if (datacnt < 4) { goto error; } if (!(stream = jas_stream_memopen(0, 0))) { goto error; } if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams), stream)) { goto error; } tpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8) | dataptr[3]; datacnt -= 4; dataptr += 4; /* Get the packet header data for the current tile-part. */ while (tpcnt) { if (!datacnt) { if (++entno >= tab->numents) { goto error; } ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; } n = JAS_MIN(tpcnt, datacnt); if (jas_stream_write(stream, dataptr, n) != n) { goto error; } tpcnt -= n; dataptr += n; datacnt -= n; } jas_stream_rewind(stream); if (!datacnt) { if (++entno >= tab->numents) { break; } ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; } } return streams; error: if (streams) { jpc_streamlist_destroy(streams); } 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
jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab) { jpc_streamlist_t *streams; jas_uchar *dataptr; uint_fast32_t datacnt; uint_fast32_t tpcnt; jpc_ppxstabent_t *ent; int entno; jas_stream_t *stream; int n; if (!(streams = jpc_streamlist_create())) { goto error; } if (!tab->numents) { return streams; } entno = 0; ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; for (;;) { /* Get the length of the packet header data for the current tile-part. */ if (datacnt < 4) { goto error; } if (!(stream = jas_stream_memopen(0, 0))) { goto error; } if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams), stream)) { goto error; } tpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8) | dataptr[3]; datacnt -= 4; dataptr += 4; /* Get the packet header data for the current tile-part. */ while (tpcnt) { if (!datacnt) { if (++entno >= tab->numents) { goto error; } ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; } n = JAS_MIN(tpcnt, datacnt); if (jas_stream_write(stream, dataptr, n) != n) { goto error; } tpcnt -= n; dataptr += n; datacnt -= n; } jas_stream_rewind(stream); if (!datacnt) { if (++entno >= tab->numents) { break; } ent = tab->ents[entno]; dataptr = ent->data; datacnt = ent->len; } } return streams; error: if (streams) { jpc_streamlist_destroy(streams); } return 0; }
168,719
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserEventRouter::TabPinnedStateChanged(WebContents* contents, int index) { TabStripModel* tab_strip = NULL; int tab_index; if (ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index)) { DictionaryValue* changed_properties = new DictionaryValue(); changed_properties->SetBoolean(tab_keys::kPinnedKey, tab_strip->IsTabPinned(tab_index)); DispatchTabUpdatedEvent(contents, changed_properties); } } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void BrowserEventRouter::TabPinnedStateChanged(WebContents* contents, int index) { TabStripModel* tab_strip = NULL; int tab_index; if (ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index)) { scoped_ptr<DictionaryValue> changed_properties(new DictionaryValue()); changed_properties->SetBoolean(tab_keys::kPinnedKey, tab_strip->IsTabPinned(tab_index)); DispatchTabUpdatedEvent(contents, changed_properties.Pass()); } }
171,451
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Document::InitContentSecurityPolicy( ContentSecurityPolicy* csp, const ContentSecurityPolicy* policy_to_inherit) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); if (policy_to_inherit) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } else if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); policy_to_inherit = inherit_from->GetSecurityContext()->GetContentSecurityPolicy(); if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } } } if (policy_to_inherit && IsPluginDocument()) GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit); GetContentSecurityPolicy()->BindToExecutionContext(this); } Commit Message: Fixed bug where PlzNavigate CSP in a iframe did not get the inherited CSP When inheriting the CSP from a parent document to a local-scheme CSP, it does not always get propagated to the PlzNavigate CSP. This means that PlzNavigate CSP checks (like `frame-src`) would be ran against a blank policy instead of the proper inherited policy. Bug: 778658 Change-Id: I61bb0d432e1cea52f199e855624cb7b3078f56a9 Reviewed-on: https://chromium-review.googlesource.com/765969 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#518245} CWE ID: CWE-732
void Document::InitContentSecurityPolicy( ContentSecurityPolicy* csp, const ContentSecurityPolicy* policy_to_inherit) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); GetContentSecurityPolicy()->BindToExecutionContext(this); if (policy_to_inherit) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } else if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); policy_to_inherit = inherit_from->GetSecurityContext()->GetContentSecurityPolicy(); if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } } } if (policy_to_inherit && IsPluginDocument()) GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit); }
172,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int scsi_cmd_blk_ioctl(struct block_device *bd, fmode_t mode, unsigned int cmd, void __user *arg) { return scsi_cmd_ioctl(bd->bd_disk->queue, bd->bd_disk, mode, cmd, arg); } Commit Message: block: fail SCSI passthrough ioctls on partition devices Linux allows executing the SG_IO ioctl on a partition or LVM volume, and will pass the command to the underlying block device. This is well-known, but it is also a large security problem when (via Unix permissions, ACLs, SELinux or a combination thereof) a program or user needs to be granted access only to part of the disk. This patch lets partitions forward a small set of harmless ioctls; others are logged with printk so that we can see which ioctls are actually sent. In my tests only CDROM_GET_CAPABILITY actually occurred. Of course it was being sent to a (partition on a) hard disk, so it would have failed with ENOTTY and the patch isn't changing anything in practice. Still, I'm treating it specially to avoid spamming the logs. In principle, this restriction should include programs running with CAP_SYS_RAWIO. If for example I let a program access /dev/sda2 and /dev/sdb, it still should not be able to read/write outside the boundaries of /dev/sda2 independent of the capabilities. However, for now programs with CAP_SYS_RAWIO will still be allowed to send the ioctls. Their actions will still be logged. This patch does not affect the non-libata IDE driver. That driver however already tests for bd != bd->bd_contains before issuing some ioctl; it could be restricted further to forbid these ioctls even for programs running with CAP_SYS_ADMIN/CAP_SYS_RAWIO. Cc: [email protected] Cc: Jens Axboe <[email protected]> Cc: James Bottomley <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> [ Make it also print the command name when warning - Linus ] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
int scsi_cmd_blk_ioctl(struct block_device *bd, fmode_t mode, unsigned int cmd, void __user *arg) { int ret; ret = scsi_verify_blk_ioctl(bd, cmd); if (ret < 0) return ret; return scsi_cmd_ioctl(bd->bd_disk->queue, bd->bd_disk, mode, cmd, arg); }
169,889
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_get_uint_16(png_bytep buf) { png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) + (png_uint_16)(*(buf + 1))); return (i); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_uint_16(png_bytep buf) { png_uint_16 i = ((png_uint_16)((*(buf )) & 0xff) << 8) + ((png_uint_16)((*(buf + 1)) & 0xff) ); return (i); }
172,174
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int br_mdb_dump(struct sk_buff *skb, struct netlink_callback *cb) { struct net_device *dev; struct net *net = sock_net(skb->sk); struct nlmsghdr *nlh = NULL; int idx = 0, s_idx; s_idx = cb->args[0]; rcu_read_lock(); /* In theory this could be wrapped to 0... */ cb->seq = net->dev_base_seq + br_mdb_rehash_seq; for_each_netdev_rcu(net, dev) { if (dev->priv_flags & IFF_EBRIDGE) { struct br_port_msg *bpm; if (idx < s_idx) goto skip; nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, RTM_GETMDB, sizeof(*bpm), NLM_F_MULTI); if (nlh == NULL) break; bpm = nlmsg_data(nlh); bpm->ifindex = dev->ifindex; if (br_mdb_fill_info(skb, cb, dev) < 0) goto out; if (br_rports_fill_info(skb, cb, dev) < 0) goto out; cb->args[1] = 0; nlmsg_end(skb, nlh); skip: idx++; } } out: if (nlh) nlmsg_end(skb, nlh); rcu_read_unlock(); cb->args[0] = idx; return skb->len; } Commit Message: bridge: fix mdb info leaks The bridging code discloses heap and stack bytes via the RTM_GETMDB netlink interface and via the notify messages send to group RTNLGRP_MDB afer a successful add/del. Fix both cases by initializing all unset members/padding bytes with memset(0). Cc: Stephen Hemminger <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static int br_mdb_dump(struct sk_buff *skb, struct netlink_callback *cb) { struct net_device *dev; struct net *net = sock_net(skb->sk); struct nlmsghdr *nlh = NULL; int idx = 0, s_idx; s_idx = cb->args[0]; rcu_read_lock(); /* In theory this could be wrapped to 0... */ cb->seq = net->dev_base_seq + br_mdb_rehash_seq; for_each_netdev_rcu(net, dev) { if (dev->priv_flags & IFF_EBRIDGE) { struct br_port_msg *bpm; if (idx < s_idx) goto skip; nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, RTM_GETMDB, sizeof(*bpm), NLM_F_MULTI); if (nlh == NULL) break; bpm = nlmsg_data(nlh); memset(bpm, 0, sizeof(*bpm)); bpm->ifindex = dev->ifindex; if (br_mdb_fill_info(skb, cb, dev) < 0) goto out; if (br_rports_fill_info(skb, cb, dev) < 0) goto out; cb->args[1] = 0; nlmsg_end(skb, nlh); skip: idx++; } } out: if (nlh) nlmsg_end(skb, nlh); rcu_read_unlock(); cb->args[0] = idx; return skb->len; }
166,052
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void opl3_panning(int dev, int voice, int value) { devc->voc[voice].panning = value; } Commit Message: sound/oss/opl3: validate voice and channel indexes User-controllable indexes for voice and channel values may cause reading and writing beyond the bounds of their respective arrays, leading to potentially exploitable memory corruption. Validate these indexes. Signed-off-by: Dan Rosenberg <[email protected]> Cc: [email protected] Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-119
static void opl3_panning(int dev, int voice, int value) { if (voice < 0 || voice >= devc->nr_voice) return; devc->voc[voice].panning = value; }
165,890
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int CCITTFaxStream::lookChar() { int code1, code2, code3; int b1i, blackPixels, i, bits; GBool gotEOL; if (buf != EOF) { return buf; } if (outputBits == 0) { if (eof) { return EOF; } err = gFalse; if (nextLine2D) { for (i = 0; i < columns && codingLine[i] < columns; ++i) { refLine[i] = codingLine[i]; } refLine[i++] = columns; refLine[i] = columns; codingLine[0] = 0; a0i = 0; b1i = 0; while (codingLine[a0i] < columns && !err) { code1 = getTwoDimCode(); switch (code1) { case twoDimPass: if (likely(b1i + 1 < columns + 2)) { addPixels(refLine[b1i + 1], blackPixels); if (refLine[b1i + 1] < columns) { b1i += 2; } } break; case twoDimHoriz: code1 = code2 = 0; if (blackPixels) { do { code1 += code3 = getBlackCode(); } while (code3 >= 64); do { code2 += code3 = getWhiteCode(); } while (code3 >= 64); } else { do { code1 += code3 = getWhiteCode(); } while (code3 >= 64); do { code2 += code3 = getBlackCode(); } while (code3 >= 64); } addPixels(codingLine[a0i] + code1, blackPixels); if (codingLine[a0i] < columns) { addPixels(codingLine[a0i] + code2, blackPixels ^ 1); } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } break; case twoDimVertR3: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i] + 3, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertR2: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i] + 2, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertR1: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i] + 1, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVert0: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i], blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertL3: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixelsNeg(refLine[b1i] - 3, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { if (b1i > 0) { --b1i; } else { ++b1i; } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertL2: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixelsNeg(refLine[b1i] - 2, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { if (b1i > 0) { --b1i; } else { ++b1i; } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertL1: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixelsNeg(refLine[b1i] - 1, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { if (b1i > 0) { --b1i; } else { ++b1i; } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case EOF: addPixels(columns, 0); eof = gTrue; break; default: error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); addPixels(columns, 0); err = gTrue; break; } } } else { codingLine[0] = 0; a0i = 0; blackPixels = 0; while (codingLine[a0i] < columns) { code1 = 0; if (blackPixels) { do { code1 += code3 = getBlackCode(); } while (code3 >= 64); } else { do { code1 += code3 = getWhiteCode(); } while (code3 >= 64); } addPixels(codingLine[a0i] + code1, blackPixels); blackPixels ^= 1; } } gotEOL = gFalse; if (!endOfBlock && row == rows - 1) { eof = gTrue; } else if (endOfLine || !byteAlign) { code1 = lookBits(12); if (endOfLine) { while (code1 != EOF && code1 != 0x001) { eatBits(1); code1 = lookBits(12); } } else { while (code1 == 0) { eatBits(1); code1 = lookBits(12); } } if (code1 == 0x001) { eatBits(12); gotEOL = gTrue; } } if (byteAlign && !gotEOL) { inputBits &= ~7; } if (lookBits(1) == EOF) { eof = gTrue; } if (!eof && encoding > 0) { nextLine2D = !lookBits(1); eatBits(1); } if (endOfBlock && !endOfLine && byteAlign) { code1 = lookBits(24); if (code1 == 0x001001) { eatBits(12); gotEOL = gTrue; } } if (endOfBlock && gotEOL) { code1 = lookBits(12); if (code1 == 0x001) { eatBits(12); if (encoding > 0) { lookBits(1); eatBits(1); } if (encoding >= 0) { for (i = 0; i < 4; ++i) { code1 = lookBits(12); if (code1 != 0x001) { error(errSyntaxError, getPos(), "Bad RTC code in CCITTFax stream"); } eatBits(12); if (encoding > 0) { lookBits(1); eatBits(1); } } } eof = gTrue; } } else if (err && endOfLine) { while (1) { code1 = lookBits(13); if (code1 == EOF) { eof = gTrue; return EOF; } if ((code1 >> 1) == 0x001) { break; } eatBits(1); } eatBits(12); if (encoding > 0) { eatBits(1); nextLine2D = !(code1 & 1); } } if (codingLine[0] > 0) { outputBits = codingLine[a0i = 0]; } else { outputBits = codingLine[a0i = 1]; } ++row; } if (outputBits >= 8) { buf = (a0i & 1) ? 0x00 : 0xff; outputBits -= 8; if (outputBits == 0 && codingLine[a0i] < columns) { ++a0i; outputBits = codingLine[a0i] - codingLine[a0i - 1]; } } else { bits = 8; buf = 0; do { if (outputBits > bits) { buf <<= bits; if (!(a0i & 1)) { buf |= 0xff >> (8 - bits); } outputBits -= bits; bits = 0; } else { buf <<= outputBits; if (!(a0i & 1)) { buf |= 0xff >> (8 - outputBits); } bits -= outputBits; outputBits = 0; if (codingLine[a0i] < columns) { ++a0i; if (unlikely(a0i > columns)) { error(errSyntaxError, getPos(), "Bad bits {0:04x} in CCITTFax stream", bits); err = gTrue; break; } outputBits = codingLine[a0i] - codingLine[a0i - 1]; } else if (bits > 0) { buf <<= bits; bits = 0; } } } while (bits); } if (black) { buf ^= 0xff; } return buf; } Commit Message: CWE ID: CWE-119
int CCITTFaxStream::lookChar() { int code1, code2, code3; int b1i, blackPixels, i, bits; GBool gotEOL; if (buf != EOF) { return buf; } if (outputBits == 0) { if (eof) { return EOF; } err = gFalse; if (nextLine2D) { for (i = 0; i < columns && codingLine[i] < columns; ++i) { refLine[i] = codingLine[i]; } for (; i < columns + 2; ++i) { refLine[i] = columns; } codingLine[0] = 0; a0i = 0; b1i = 0; while (codingLine[a0i] < columns && !err) { code1 = getTwoDimCode(); switch (code1) { case twoDimPass: if (likely(b1i + 1 < columns + 2)) { addPixels(refLine[b1i + 1], blackPixels); if (refLine[b1i + 1] < columns) { b1i += 2; } } break; case twoDimHoriz: code1 = code2 = 0; if (blackPixels) { do { code1 += code3 = getBlackCode(); } while (code3 >= 64); do { code2 += code3 = getWhiteCode(); } while (code3 >= 64); } else { do { code1 += code3 = getWhiteCode(); } while (code3 >= 64); do { code2 += code3 = getBlackCode(); } while (code3 >= 64); } addPixels(codingLine[a0i] + code1, blackPixels); if (codingLine[a0i] < columns) { addPixels(codingLine[a0i] + code2, blackPixels ^ 1); } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } break; case twoDimVertR3: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i] + 3, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertR2: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i] + 2, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertR1: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i] + 1, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVert0: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i], blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertL3: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixelsNeg(refLine[b1i] - 3, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { if (b1i > 0) { --b1i; } else { ++b1i; } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertL2: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixelsNeg(refLine[b1i] - 2, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { if (b1i > 0) { --b1i; } else { ++b1i; } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertL1: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixelsNeg(refLine[b1i] - 1, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { if (b1i > 0) { --b1i; } else { ++b1i; } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case EOF: addPixels(columns, 0); eof = gTrue; break; default: error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); addPixels(columns, 0); err = gTrue; break; } } } else { codingLine[0] = 0; a0i = 0; blackPixels = 0; while (codingLine[a0i] < columns) { code1 = 0; if (blackPixels) { do { code1 += code3 = getBlackCode(); } while (code3 >= 64); } else { do { code1 += code3 = getWhiteCode(); } while (code3 >= 64); } addPixels(codingLine[a0i] + code1, blackPixels); blackPixels ^= 1; } } gotEOL = gFalse; if (!endOfBlock && row == rows - 1) { eof = gTrue; } else if (endOfLine || !byteAlign) { code1 = lookBits(12); if (endOfLine) { while (code1 != EOF && code1 != 0x001) { eatBits(1); code1 = lookBits(12); } } else { while (code1 == 0) { eatBits(1); code1 = lookBits(12); } } if (code1 == 0x001) { eatBits(12); gotEOL = gTrue; } } if (byteAlign && !gotEOL) { inputBits &= ~7; } if (lookBits(1) == EOF) { eof = gTrue; } if (!eof && encoding > 0) { nextLine2D = !lookBits(1); eatBits(1); } if (endOfBlock && !endOfLine && byteAlign) { code1 = lookBits(24); if (code1 == 0x001001) { eatBits(12); gotEOL = gTrue; } } if (endOfBlock && gotEOL) { code1 = lookBits(12); if (code1 == 0x001) { eatBits(12); if (encoding > 0) { lookBits(1); eatBits(1); } if (encoding >= 0) { for (i = 0; i < 4; ++i) { code1 = lookBits(12); if (code1 != 0x001) { error(errSyntaxError, getPos(), "Bad RTC code in CCITTFax stream"); } eatBits(12); if (encoding > 0) { lookBits(1); eatBits(1); } } } eof = gTrue; } } else if (err && endOfLine) { while (1) { code1 = lookBits(13); if (code1 == EOF) { eof = gTrue; return EOF; } if ((code1 >> 1) == 0x001) { break; } eatBits(1); } eatBits(12); if (encoding > 0) { eatBits(1); nextLine2D = !(code1 & 1); } } if (codingLine[0] > 0) { outputBits = codingLine[a0i = 0]; } else { outputBits = codingLine[a0i = 1]; } ++row; } if (outputBits >= 8) { buf = (a0i & 1) ? 0x00 : 0xff; outputBits -= 8; if (outputBits == 0 && codingLine[a0i] < columns) { ++a0i; outputBits = codingLine[a0i] - codingLine[a0i - 1]; } } else { bits = 8; buf = 0; do { if (outputBits > bits) { buf <<= bits; if (!(a0i & 1)) { buf |= 0xff >> (8 - bits); } outputBits -= bits; bits = 0; } else { buf <<= outputBits; if (!(a0i & 1)) { buf |= 0xff >> (8 - outputBits); } bits -= outputBits; outputBits = 0; if (codingLine[a0i] < columns) { ++a0i; if (unlikely(a0i > columns)) { error(errSyntaxError, getPos(), "Bad bits {0:04x} in CCITTFax stream", bits); err = gTrue; break; } outputBits = codingLine[a0i] - codingLine[a0i - 1]; } else if (bits > 0) { buf <<= bits; bits = 0; } } } while (bits); } if (black) { buf ^= 0xff; } return buf; }
164,730
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void add_bytes_c(uint8_t *dst, uint8_t *src, int w){ long i; for(i=0; i<=w-sizeof(long); i+=sizeof(long)){ long a = *(long*)(src+i); long b = *(long*)(dst+i); *(long*)(dst+i) = ((a&pb_7f) + (b&pb_7f)) ^ ((a^b)&pb_80); } for(; i<w; i++) dst[i+0] += src[i+0]; } Commit Message: avcodec/dsputil: fix signedness in sizeof() comparissions Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-189
static void add_bytes_c(uint8_t *dst, uint8_t *src, int w){ long i; for(i=0; i<=w-(int)sizeof(long); i+=sizeof(long)){ long a = *(long*)(src+i); long b = *(long*)(dst+i); *(long*)(dst+i) = ((a&pb_7f) + (b&pb_7f)) ^ ((a^b)&pb_80); } for(; i<w; i++) dst[i+0] += src[i+0]; }
165,929
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { size_t ofs = CDF_GETUINT32(p, (i << 1) + 1); q = (const uint8_t *)(const void *) ((const char *)(const void *)p + ofs - 2 * sizeof(uint32_t)); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); if (nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == 0\n")); goto out; } o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; } Commit Message: Add missing check offset test (Francisco Alonso, Jan Kaluza at RedHat) CWE ID: CWE-20
cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { size_t tail = (i << 1) + 1; if (cdf_check_stream_offset(sst, h, p, tail * sizeof(uint32_t), __LINE__) == -1) goto out; size_t ofs = CDF_GETUINT32(p, tail); q = (const uint8_t *)(const void *) ((const char *)(const void *)p + ofs - 2 * sizeof(uint32_t)); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); if (nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == 0\n")); goto out; } o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; }
166,364
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: nm_ip4_config_commit (const NMIP4Config *config, int ifindex, guint32 default_route_metric) { NMIP4ConfigPrivate *priv = NM_IP4_CONFIG_GET_PRIVATE (config); guint32 mtu = nm_ip4_config_get_mtu (config); int i; g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (config != NULL, FALSE); /* Addresses */ nm_platform_ip4_address_sync (ifindex, priv->addresses, default_route_metric); /* Routes */ { int count = nm_ip4_config_get_num_routes (config); GArray *routes = g_array_sized_new (FALSE, FALSE, sizeof (NMPlatformIP4Route), count); const NMPlatformIP4Route *route; gboolean success; for (i = 0; i < count; i++) { route = nm_ip4_config_get_route (config, i); /* Don't add the route if it's more specific than one of the subnets * the device already has an IP address on. */ if ( route->gateway == 0 && nm_ip4_config_destination_is_direct (config, route->network, route->plen)) continue; g_array_append_vals (routes, route, 1); } success = nm_route_manager_ip4_route_sync (nm_route_manager_get (), ifindex, routes); g_array_unref (routes); return FALSE; } /* MTU */ if (mtu && mtu != nm_platform_link_get_mtu (ifindex)) nm_platform_link_set_mtu (ifindex, mtu); return TRUE; } Commit Message: CWE ID: CWE-20
nm_ip4_config_commit (const NMIP4Config *config, int ifindex, guint32 default_route_metric) { NMIP4ConfigPrivate *priv = NM_IP4_CONFIG_GET_PRIVATE (config); int i; g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (config != NULL, FALSE); /* Addresses */ nm_platform_ip4_address_sync (ifindex, priv->addresses, default_route_metric); /* Routes */ { int count = nm_ip4_config_get_num_routes (config); GArray *routes = g_array_sized_new (FALSE, FALSE, sizeof (NMPlatformIP4Route), count); const NMPlatformIP4Route *route; gboolean success; for (i = 0; i < count; i++) { route = nm_ip4_config_get_route (config, i); /* Don't add the route if it's more specific than one of the subnets * the device already has an IP address on. */ if ( route->gateway == 0 && nm_ip4_config_destination_is_direct (config, route->network, route->plen)) continue; g_array_append_vals (routes, route, 1); } success = nm_route_manager_ip4_route_sync (nm_route_manager_get (), ifindex, routes); g_array_unref (routes); return FALSE; } return TRUE; }
164,815
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_file_splice_write( struct pipe_inode_info *pipe, struct file *outfilp, loff_t *ppos, size_t count, unsigned int flags) { struct inode *inode = outfilp->f_mapping->host; struct xfs_inode *ip = XFS_I(inode); int ioflags = 0; ssize_t ret; XFS_STATS_INC(xs_write_calls); if (outfilp->f_mode & FMODE_NOCMTIME) ioflags |= IO_INVIS; if (XFS_FORCED_SHUTDOWN(ip->i_mount)) return -EIO; xfs_ilock(ip, XFS_IOLOCK_EXCL); trace_xfs_file_splice_write(ip, count, *ppos, ioflags); ret = generic_file_splice_write(pipe, outfilp, ppos, count, flags); if (ret > 0) XFS_STATS_ADD(xs_write_bytes, ret); xfs_iunlock(ip, XFS_IOLOCK_EXCL); return ret; } Commit Message: ->splice_write() via ->write_iter() iter_file_splice_write() - a ->splice_write() instance that gathers the pipe buffers, builds a bio_vec-based iov_iter covering those and feeds it to ->write_iter(). A bunch of simple cases coverted to that... [AV: fixed the braino spotted by Cyrill] Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-264
xfs_file_splice_write(
166,810
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_get_asm_flags (png_structp png_ptr) { /* Obsolete, to be removed from libpng-1.4.0 */ return (png_ptr? 0L: 0L); } 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_get_asm_flags (png_structp png_ptr) { /* Obsolete, to be removed from libpng-1.4.0 */ PNG_UNUSED(png_ptr) return 0L; }
172,165
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PSIR_FileWriter::ParseFileResources ( XMP_IO* fileRef, XMP_Uns32 length ) { static const size_t kMinPSIRSize = 12; // 4+2+1+1+4 this->DeleteExistingInfo(); this->fileParsed = true; if ( length == 0 ) return; XMP_Int64 psirOrigin = fileRef->Offset(); // Need this to determine the resource data offsets. XMP_Int64 fileEnd = psirOrigin + length; char nameBuffer [260]; // The name is a PString, at 1+255+1 including length and pad. while ( fileRef->Offset() < fileEnd ) { if ( ! XIO::CheckFileSpace ( fileRef, kMinPSIRSize ) ) break; // Bad image resource. XMP_Int64 thisRsrcPos = fileRef->Offset(); XMP_Uns32 type = XIO::ReadUns32_BE ( fileRef ); XMP_Uns16 id = XIO::ReadUns16_BE ( fileRef ); XMP_Uns8 nameLen = XIO::ReadUns8 ( fileRef ); // ! The length for the Pascal string. XMP_Uns16 paddedLen = (nameLen + 2) & 0xFFFE; // ! Round up to an even total. Yes, +2! if ( ! XIO::CheckFileSpace ( fileRef, paddedLen+4 ) ) break; // Bad image resource. nameBuffer[0] = nameLen; fileRef->ReadAll ( &nameBuffer[1], paddedLen-1 ); // Include the pad byte, present for zero nameLen. XMP_Uns32 dataLen = XIO::ReadUns32_BE ( fileRef ); XMP_Uns32 dataTotal = ((dataLen + 1) & 0xFFFFFFFEUL); // Round up to an even total. if ( ! XIO::CheckFileSpace ( fileRef, dataTotal ) ) break; // Bad image resource. XMP_Int64 thisDataPos = fileRef->Offset(); continue; } InternalRsrcInfo newInfo ( id, dataLen, kIsFileBased ); InternalRsrcMap::iterator rsrcPos = this->imgRsrcs.find ( id ); if ( rsrcPos == this->imgRsrcs.end() ) { rsrcPos = this->imgRsrcs.insert ( rsrcPos, InternalRsrcMap::value_type ( id, newInfo ) ); } else if ( (rsrcPos->second.dataLen == 0) && (newInfo.dataLen != 0) ) { rsrcPos->second = newInfo; } else { fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart ); continue; } InternalRsrcInfo* rsrcPtr = &rsrcPos->second; rsrcPtr->origOffset = (XMP_Uns32)thisDataPos; if ( nameLen > 0 ) { rsrcPtr->rsrcName = (XMP_Uns8*) malloc ( paddedLen ); if ( rsrcPtr->rsrcName == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory ); memcpy ( (void*)rsrcPtr->rsrcName, nameBuffer, paddedLen ); // AUDIT: Safe, allocated enough bytes above. } if ( ! IsMetadataImgRsrc ( id ) ) { fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart ); continue; } rsrcPtr->dataPtr = malloc ( dataTotal ); // ! Allocate after the IsMetadataImgRsrc check. if ( rsrcPtr->dataPtr == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory ); fileRef->ReadAll ( (void*)rsrcPtr->dataPtr, dataTotal ); } Commit Message: CWE ID: CWE-125
void PSIR_FileWriter::ParseFileResources ( XMP_IO* fileRef, XMP_Uns32 length ) { static const size_t kMinPSIRSize = 12; // 4+2+1+1+4 this->DeleteExistingInfo(); this->fileParsed = true; if ( length == 0 ) return; XMP_Int64 psirOrigin = fileRef->Offset(); // Need this to determine the resource data offsets. XMP_Int64 fileEnd = psirOrigin + length; char nameBuffer [260]; // The name is a PString, at 1+255+1 including length and pad. while ( fileRef->Offset() < fileEnd ) { if ( ! XIO::CheckFileSpace ( fileRef, kMinPSIRSize ) ) break; // Bad image resource. XMP_Int64 thisRsrcPos = fileRef->Offset(); XMP_Uns32 type = XIO::ReadUns32_BE ( fileRef ); XMP_Uns16 id = XIO::ReadUns16_BE ( fileRef ); XMP_Uns8 nameLen = XIO::ReadUns8 ( fileRef ); // ! The length for the Pascal string. XMP_Uns16 paddedLen = (nameLen + 2) & 0xFFFE; // ! Round up to an even total. Yes, +2! if ( ! XIO::CheckFileSpace ( fileRef, paddedLen+4 ) ) break; // Bad image resource. nameBuffer[0] = nameLen; fileRef->ReadAll ( &nameBuffer[1], paddedLen-1 ); // Include the pad byte, present for zero nameLen. XMP_Uns32 dataLen = XIO::ReadUns32_BE ( fileRef ); XMP_Uns32 dataTotal = ((dataLen + 1) & 0xFFFFFFFEUL); // Round up to an even total. // See bug https://bugs.freedesktop.org/show_bug.cgi?id=105204 // If dataLen is 0xffffffff, then dataTotal might be 0 // and therefor make the CheckFileSpace test pass. if (dataTotal < dataLen) { break; } if ( ! XIO::CheckFileSpace ( fileRef, dataTotal ) ) break; // Bad image resource. XMP_Int64 thisDataPos = fileRef->Offset(); continue; } InternalRsrcInfo newInfo ( id, dataLen, kIsFileBased ); InternalRsrcMap::iterator rsrcPos = this->imgRsrcs.find ( id ); if ( rsrcPos == this->imgRsrcs.end() ) { rsrcPos = this->imgRsrcs.insert ( rsrcPos, InternalRsrcMap::value_type ( id, newInfo ) ); } else if ( (rsrcPos->second.dataLen == 0) && (newInfo.dataLen != 0) ) { rsrcPos->second = newInfo; } else { fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart ); continue; } InternalRsrcInfo* rsrcPtr = &rsrcPos->second; rsrcPtr->origOffset = (XMP_Uns32)thisDataPos; if ( nameLen > 0 ) { rsrcPtr->rsrcName = (XMP_Uns8*) malloc ( paddedLen ); if ( rsrcPtr->rsrcName == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory ); memcpy ( (void*)rsrcPtr->rsrcName, nameBuffer, paddedLen ); // AUDIT: Safe, allocated enough bytes above. } if ( ! IsMetadataImgRsrc ( id ) ) { fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart ); continue; } rsrcPtr->dataPtr = malloc ( dataTotal ); // ! Allocate after the IsMetadataImgRsrc check. if ( rsrcPtr->dataPtr == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory ); fileRef->ReadAll ( (void*)rsrcPtr->dataPtr, dataTotal ); }
164,994
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: mainloop_destroy_trigger(crm_trigger_t * source) { source->trigger = FALSE; if (source->id > 0) { g_source_remove(source->id); } return TRUE; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
mainloop_destroy_trigger(crm_trigger_t * source) { source->trigger = FALSE; if (source->id > 0) { g_source_remove(source->id); source->id = 0; } return TRUE; }
166,157
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_async_throw_error (MyObject *obj, DBusGMethodInvocation *context) { IncrementData *data = g_new0(IncrementData, 1); data->context = context; g_idle_add ((GSourceFunc)do_async_error, data); } Commit Message: CWE ID: CWE-264
my_object_async_throw_error (MyObject *obj, DBusGMethodInvocation *context)
165,089
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ { if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } } ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { WORD32 buf_size; pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; /* If dynamic bitstream buffer is not allocated and * header decode is done, then allocate dynamic bitstream buffer */ if((NULL == ps_dec->pu1_bits_buf_dynamic) && (ps_dec->i4_header_decoded & 1)) { WORD32 size; void *pv_buf; void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); RETURN_IF((NULL == pv_buf), IV_FAIL); ps_dec->pu1_bits_buf_dynamic = pv_buf; ps_dec->u4_dynamic_bits_buf_size = size; } if(ps_dec->pu1_bits_buf_dynamic) { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; buf_size = ps_dec->u4_dynamic_bits_buf_size; } else { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; buf_size = ps_dec->u4_static_bits_buf_size; } u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ buflen = MIN(buflen, buf_size); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); /* Decoder may read extra 8 bytes near end of the frame */ if((buflen + 8) < buf_size) { memset(pu1_bitstrm_buf + buflen, 0, 8); } u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && (ret != IVD_MEM_ALLOC_FAILED) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T)) { return IV_FAIL; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); if(ret != 0) { return IV_FAIL; } } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Commit Message: Decoder: Initialize first_pb_nal_in_pic for error slices first_pb_nal_in_pic was uninitialized for error clips Bug: 29023649 Change-Id: Ie4e0a94059c5f675bf619e31534846e2c2ca58ae CWE ID: CWE-172
WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ { if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } } ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { WORD32 buf_size; pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; /* If dynamic bitstream buffer is not allocated and * header decode is done, then allocate dynamic bitstream buffer */ if((NULL == ps_dec->pu1_bits_buf_dynamic) && (ps_dec->i4_header_decoded & 1)) { WORD32 size; void *pv_buf; void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); RETURN_IF((NULL == pv_buf), IV_FAIL); ps_dec->pu1_bits_buf_dynamic = pv_buf; ps_dec->u4_dynamic_bits_buf_size = size; } if(ps_dec->pu1_bits_buf_dynamic) { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; buf_size = ps_dec->u4_dynamic_bits_buf_size; } else { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; buf_size = ps_dec->u4_static_bits_buf_size; } u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ buflen = MIN(buflen, buf_size); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); /* Decoder may read extra 8 bytes near end of the frame */ if((buflen + 8) < buf_size) { memset(pu1_bitstrm_buf + buflen, 0, 8); } u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && (ret != IVD_MEM_ALLOC_FAILED) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T)) { return IV_FAIL; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); if(ret != 0) { return IV_FAIL; } } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; }
173,514
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int hsr_dev_finalize(struct net_device *hsr_dev, struct net_device *slave[2], unsigned char multicast_spec, u8 protocol_version) { struct hsr_priv *hsr; struct hsr_port *port; int res; hsr = netdev_priv(hsr_dev); INIT_LIST_HEAD(&hsr->ports); INIT_LIST_HEAD(&hsr->node_db); INIT_LIST_HEAD(&hsr->self_node_db); ether_addr_copy(hsr_dev->dev_addr, slave[0]->dev_addr); /* Make sure we recognize frames from ourselves in hsr_rcv() */ res = hsr_create_self_node(&hsr->self_node_db, hsr_dev->dev_addr, slave[1]->dev_addr); if (res < 0) return res; spin_lock_init(&hsr->seqnr_lock); /* Overflow soon to find bugs easier: */ hsr->sequence_nr = HSR_SEQNR_START; hsr->sup_sequence_nr = HSR_SUP_SEQNR_START; timer_setup(&hsr->announce_timer, hsr_announce, 0); timer_setup(&hsr->prune_timer, hsr_prune_nodes, 0); ether_addr_copy(hsr->sup_multicast_addr, def_multicast_addr); hsr->sup_multicast_addr[ETH_ALEN - 1] = multicast_spec; hsr->protVersion = protocol_version; /* FIXME: should I modify the value of these? * * - hsr_dev->flags - i.e. * IFF_MASTER/SLAVE? * - hsr_dev->priv_flags - i.e. * IFF_EBRIDGE? * IFF_TX_SKB_SHARING? * IFF_HSR_MASTER/SLAVE? */ /* Make sure the 1st call to netif_carrier_on() gets through */ netif_carrier_off(hsr_dev); res = hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER); if (res) return res; res = register_netdevice(hsr_dev); if (res) goto fail; res = hsr_add_port(hsr, slave[0], HSR_PT_SLAVE_A); if (res) goto fail; res = hsr_add_port(hsr, slave[1], HSR_PT_SLAVE_B); if (res) goto fail; mod_timer(&hsr->prune_timer, jiffies + msecs_to_jiffies(PRUNE_PERIOD)); return 0; fail: hsr_for_each_port(hsr, port) hsr_del_port(port); return res; } Commit Message: net: hsr: fix memory leak in hsr_dev_finalize() If hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER) failed to add port, it directly returns res and forgets to free the node that allocated in hsr_create_self_node(), and forgets to delete the node->mac_list linked in hsr->self_node_db. BUG: memory leak unreferenced object 0xffff8881cfa0c780 (size 64): comm "syz-executor.0", pid 2077, jiffies 4294717969 (age 2415.377s) hex dump (first 32 bytes): e0 c7 a0 cf 81 88 ff ff 00 02 00 00 00 00 ad de ................ 00 e6 49 cd 81 88 ff ff c0 9b 87 d0 81 88 ff ff ..I............. backtrace: [<00000000e2ff5070>] hsr_dev_finalize+0x736/0x960 [hsr] [<000000003ed2e597>] hsr_newlink+0x2b2/0x3e0 [hsr] [<000000003fa8c6b6>] __rtnl_newlink+0xf1f/0x1600 net/core/rtnetlink.c:3182 [<000000001247a7ad>] rtnl_newlink+0x66/0x90 net/core/rtnetlink.c:3240 [<00000000e7d1b61d>] rtnetlink_rcv_msg+0x54e/0xb90 net/core/rtnetlink.c:5130 [<000000005556bd3a>] netlink_rcv_skb+0x129/0x340 net/netlink/af_netlink.c:2477 [<00000000741d5ee6>] netlink_unicast_kernel net/netlink/af_netlink.c:1310 [inline] [<00000000741d5ee6>] netlink_unicast+0x49a/0x650 net/netlink/af_netlink.c:1336 [<000000009d56f9b7>] netlink_sendmsg+0x88b/0xdf0 net/netlink/af_netlink.c:1917 [<0000000046b35c59>] sock_sendmsg_nosec net/socket.c:621 [inline] [<0000000046b35c59>] sock_sendmsg+0xc3/0x100 net/socket.c:631 [<00000000d208adc9>] __sys_sendto+0x33e/0x560 net/socket.c:1786 [<00000000b582837a>] __do_sys_sendto net/socket.c:1798 [inline] [<00000000b582837a>] __se_sys_sendto net/socket.c:1794 [inline] [<00000000b582837a>] __x64_sys_sendto+0xdd/0x1b0 net/socket.c:1794 [<00000000c866801d>] do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 [<00000000fea382d9>] entry_SYSCALL_64_after_hwframe+0x49/0xbe [<00000000e01dacb3>] 0xffffffffffffffff Fixes: c5a759117210 ("net/hsr: Use list_head (and rcu) instead of array for slave devices.") Reported-by: Hulk Robot <[email protected]> Signed-off-by: Mao Wenan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-772
int hsr_dev_finalize(struct net_device *hsr_dev, struct net_device *slave[2], unsigned char multicast_spec, u8 protocol_version) { struct hsr_priv *hsr; struct hsr_port *port; int res; hsr = netdev_priv(hsr_dev); INIT_LIST_HEAD(&hsr->ports); INIT_LIST_HEAD(&hsr->node_db); INIT_LIST_HEAD(&hsr->self_node_db); ether_addr_copy(hsr_dev->dev_addr, slave[0]->dev_addr); /* Make sure we recognize frames from ourselves in hsr_rcv() */ res = hsr_create_self_node(&hsr->self_node_db, hsr_dev->dev_addr, slave[1]->dev_addr); if (res < 0) return res; spin_lock_init(&hsr->seqnr_lock); /* Overflow soon to find bugs easier: */ hsr->sequence_nr = HSR_SEQNR_START; hsr->sup_sequence_nr = HSR_SUP_SEQNR_START; timer_setup(&hsr->announce_timer, hsr_announce, 0); timer_setup(&hsr->prune_timer, hsr_prune_nodes, 0); ether_addr_copy(hsr->sup_multicast_addr, def_multicast_addr); hsr->sup_multicast_addr[ETH_ALEN - 1] = multicast_spec; hsr->protVersion = protocol_version; /* FIXME: should I modify the value of these? * * - hsr_dev->flags - i.e. * IFF_MASTER/SLAVE? * - hsr_dev->priv_flags - i.e. * IFF_EBRIDGE? * IFF_TX_SKB_SHARING? * IFF_HSR_MASTER/SLAVE? */ /* Make sure the 1st call to netif_carrier_on() gets through */ netif_carrier_off(hsr_dev); res = hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER); if (res) goto err_add_port; res = register_netdevice(hsr_dev); if (res) goto fail; res = hsr_add_port(hsr, slave[0], HSR_PT_SLAVE_A); if (res) goto fail; res = hsr_add_port(hsr, slave[1], HSR_PT_SLAVE_B); if (res) goto fail; mod_timer(&hsr->prune_timer, jiffies + msecs_to_jiffies(PRUNE_PERIOD)); return 0; fail: hsr_for_each_port(hsr, port) hsr_del_port(port); err_add_port: hsr_del_node(&hsr->self_node_db); return res; }
169,502
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltRegisterExtModuleElement(const xmlChar * name, const xmlChar * URI, xsltPreComputeFunction precomp, xsltTransformFunction transform) { int ret; xsltExtElementPtr ext; if ((name == NULL) || (URI == NULL) || (transform == NULL)) return (-1); if (xsltElementsHash == NULL) xsltElementsHash = xmlHashCreate(10); if (xsltElementsHash == NULL) return (-1); xmlMutexLock(xsltExtMutex); ext = xsltNewExtElement(precomp, transform); if (ext == NULL) { ret = -1; goto done; } xmlHashUpdateEntry2(xsltElementsHash, name, URI, (void *) ext, (xmlHashDeallocator) xsltFreeExtElement); done: xmlMutexUnlock(xsltExtMutex); return (0); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltRegisterExtModuleElement(const xmlChar * name, const xmlChar * URI, xsltPreComputeFunction precomp, xsltTransformFunction transform) { int ret = 0; xsltExtElementPtr ext; if ((name == NULL) || (URI == NULL) || (transform == NULL)) return (-1); if (xsltElementsHash == NULL) xsltElementsHash = xmlHashCreate(10); if (xsltElementsHash == NULL) return (-1); xmlMutexLock(xsltExtMutex); ext = xsltNewExtElement(precomp, transform); if (ext == NULL) { ret = -1; goto done; } xmlHashUpdateEntry2(xsltElementsHash, name, URI, (void *) ext, (xmlHashDeallocator) xsltFreeExtElement); done: xmlMutexUnlock(xsltExtMutex); return (ret); }
173,300
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: zsetdevice(i_ctx_t *i_ctx_p) { gx_device *dev = gs_currentdevice(igs); os_ptr op = osp; int code = 0; check_write_type(*op, t_device); if (dev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != dev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; } Commit Message: CWE ID:
zsetdevice(i_ctx_t *i_ctx_p) { gx_device *odev = NULL, *dev = gs_currentdevice(igs); os_ptr op = osp; int code = dev_proc(dev, dev_spec_op)(dev, gxdso_current_output_device, (void *)&odev, 0); if (code < 0) return code; check_write_type(*op, t_device); if (odev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != odev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; }
164,638
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ShellWindow::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSION_UNLOADED: { const extensions::Extension* unloaded_extension = content::Details<extensions::UnloadedExtensionInfo>( details)->extension; if (extension_ == unloaded_extension) Close(); break; } case content::NOTIFICATION_APP_TERMINATING: Close(); break; default: NOTREACHED() << "Received unexpected notification"; } } Commit Message: Make chrome.appWindow.create() provide access to the child window at a predictable time. When you first create a window with chrome.appWindow.create(), it won't have loaded any resources. So, at create time, you are guaranteed that: child_window.location.href == 'about:blank' child_window.document.documentElement.outerHTML == '<html><head></head><body></body></html>' This is in line with the behaviour of window.open(). BUG=131735 TEST=browser_tests:PlatformAppBrowserTest.WindowsApi Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=144072 Review URL: https://chromiumcodereview.appspot.com/10644006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@144356 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ShellWindow::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED: { // TODO(jeremya): once http://crbug.com/123007 is fixed, we'll no longer // need to suspend resource requests here (the call in the constructor // should be enough). content::Details<std::pair<RenderViewHost*, RenderViewHost*> > host_details(details); if (host_details->first) SuspendRenderViewHost(host_details->second); break; } case chrome::NOTIFICATION_EXTENSION_UNLOADED: { const extensions::Extension* unloaded_extension = content::Details<extensions::UnloadedExtensionInfo>( details)->extension; if (extension_ == unloaded_extension) Close(); break; } case content::NOTIFICATION_APP_TERMINATING: Close(); break; default: NOTREACHED() << "Received unexpected notification"; } }
170,813
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PaymentRequest::PaymentRequest( content::RenderFrameHost* render_frame_host, content::WebContents* web_contents, std::unique_ptr<ContentPaymentRequestDelegate> delegate, PaymentRequestWebContentsManager* manager, PaymentRequestDisplayManager* display_manager, mojo::InterfaceRequest<mojom::PaymentRequest> request, ObserverForTest* observer_for_testing) : web_contents_(web_contents), delegate_(std::move(delegate)), manager_(manager), display_manager_(display_manager), display_handle_(nullptr), binding_(this, std::move(request)), top_level_origin_(url_formatter::FormatUrlForSecurityDisplay( web_contents_->GetLastCommittedURL())), frame_origin_(url_formatter::FormatUrlForSecurityDisplay( render_frame_host->GetLastCommittedURL())), observer_for_testing_(observer_for_testing), journey_logger_(delegate_->IsIncognito(), ukm::GetSourceIdForWebContentsDocument(web_contents)), weak_ptr_factory_(this) { binding_.set_connection_error_handler(base::BindOnce( &PaymentRequest::OnConnectionTerminated, weak_ptr_factory_.GetWeakPtr())); } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} CWE ID: CWE-189
PaymentRequest::PaymentRequest( content::RenderFrameHost* render_frame_host, content::WebContents* web_contents, std::unique_ptr<ContentPaymentRequestDelegate> delegate, PaymentRequestWebContentsManager* manager, PaymentRequestDisplayManager* display_manager, mojo::InterfaceRequest<mojom::PaymentRequest> request, ObserverForTest* observer_for_testing) : web_contents_(web_contents), log_(web_contents_), delegate_(std::move(delegate)), manager_(manager), display_manager_(display_manager), display_handle_(nullptr), binding_(this, std::move(request)), top_level_origin_(url_formatter::FormatUrlForSecurityDisplay( web_contents_->GetLastCommittedURL())), frame_origin_(url_formatter::FormatUrlForSecurityDisplay( render_frame_host->GetLastCommittedURL())), observer_for_testing_(observer_for_testing), journey_logger_(delegate_->IsIncognito(), ukm::GetSourceIdForWebContentsDocument(web_contents)), weak_ptr_factory_(this) { binding_.set_connection_error_handler(base::BindOnce( &PaymentRequest::OnConnectionTerminated, weak_ptr_factory_.GetWeakPtr())); }
173,084
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC) { php_stream *tmpstream = NULL; databuf_t *data = NULL; char *ptr; int ch, lastch; size_t size, rcvd; size_t lines; char **ret = NULL; char **entry; char *text; if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory."); return NULL; } if (!ftp_type(ftp, FTPTYPE_ASCII)) { goto bail; } if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) { goto bail; } ftp->data = data; if (!ftp_putcmd(ftp, cmd, path)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) { goto bail; } /* some servers don't open a ftp-data connection if the directory is empty */ if (ftp->resp == 226) { ftp->data = data_close(ftp, data); php_stream_close(tmpstream); return ecalloc(1, sizeof(char*)); } /* pull data buffer into tmpfile */ if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) { goto bail; } size = 0; lines = 0; lastch = 0; while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) { if (rcvd == -1 || rcvd > ((size_t)(-1))-size) { goto bail; } php_stream_write(tmpstream, data->buf, rcvd); size += rcvd; for (ptr = data->buf; rcvd; rcvd--, ptr++) { if (*ptr == '\n' && lastch == '\r') { lines++; } else { size++; } lastch = *ptr; } lastch = *ptr; } } Commit Message: CWE ID: CWE-119
ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC) { php_stream *tmpstream = NULL; databuf_t *data = NULL; char *ptr; int ch, lastch; size_t size, rcvd; size_t lines; char **ret = NULL; char **entry; char *text; if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory."); return NULL; } if (!ftp_type(ftp, FTPTYPE_ASCII)) { goto bail; } if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) { goto bail; } ftp->data = data; if (!ftp_putcmd(ftp, cmd, path)) { goto bail; } if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) { goto bail; } /* some servers don't open a ftp-data connection if the directory is empty */ if (ftp->resp == 226) { ftp->data = data_close(ftp, data); php_stream_close(tmpstream); return ecalloc(1, sizeof(char*)); } /* pull data buffer into tmpfile */ if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) { goto bail; } size = 0; lines = 0; lastch = 0; while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) { if (rcvd == -1 || rcvd > ((size_t)(-1))-size) { goto bail; } php_stream_write(tmpstream, data->buf, rcvd); size += rcvd; for (ptr = data->buf; rcvd; rcvd--, ptr++) { if (*ptr == '\n' && lastch == '\r') { lines++; } lastch = *ptr; } lastch = *ptr; } }
165,301
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct inode *isofs_iget(struct super_block *sb, unsigned long block, unsigned long offset) { unsigned long hashval; struct inode *inode; struct isofs_iget5_callback_data data; long ret; if (offset >= 1ul << sb->s_blocksize_bits) return ERR_PTR(-EINVAL); data.block = block; data.offset = offset; hashval = (block << sb->s_blocksize_bits) | offset; inode = iget5_locked(sb, hashval, &isofs_iget5_test, &isofs_iget5_set, &data); if (!inode) return ERR_PTR(-ENOMEM); if (inode->i_state & I_NEW) { ret = isofs_read_inode(inode); if (ret < 0) { iget_failed(inode); inode = ERR_PTR(ret); } else { unlock_new_inode(inode); } } return inode; } Commit Message: isofs: Fix unbounded recursion when processing relocated directories We did not check relocated directory in any way when processing Rock Ridge 'CL' tag. Thus a corrupted isofs image can possibly have a CL entry pointing to another CL entry leading to possibly unbounded recursion in kernel code and thus stack overflow or deadlocks (if there is a loop created from CL entries). Fix the problem by not allowing CL entry to point to a directory entry with CL entry (such use makes no good sense anyway) and by checking whether CL entry doesn't point to itself. CC: [email protected] Reported-by: Chris Evans <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-20
struct inode *isofs_iget(struct super_block *sb, struct inode *__isofs_iget(struct super_block *sb, unsigned long block, unsigned long offset, int relocated) { unsigned long hashval; struct inode *inode; struct isofs_iget5_callback_data data; long ret; if (offset >= 1ul << sb->s_blocksize_bits) return ERR_PTR(-EINVAL); data.block = block; data.offset = offset; hashval = (block << sb->s_blocksize_bits) | offset; inode = iget5_locked(sb, hashval, &isofs_iget5_test, &isofs_iget5_set, &data); if (!inode) return ERR_PTR(-ENOMEM); if (inode->i_state & I_NEW) { ret = isofs_read_inode(inode, relocated); if (ret < 0) { iget_failed(inode); inode = ERR_PTR(ret); } else { unlock_new_inode(inode); } } return inode; }
166,268
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gplotAddPlot(GPLOT *gplot, NUMA *nax, NUMA *nay, l_int32 plotstyle, const char *plottitle) { char buf[L_BUF_SIZE]; char emptystring[] = ""; char *datastr, *title; l_int32 n, i; l_float32 valx, valy, startx, delx; SARRAY *sa; PROCNAME("gplotAddPlot"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); if (!nay) return ERROR_INT("nay not defined", procName, 1); if (plotstyle < 0 || plotstyle >= NUM_GPLOT_STYLES) return ERROR_INT("invalid plotstyle", procName, 1); if ((n = numaGetCount(nay)) == 0) return ERROR_INT("no points to plot", procName, 1); if (nax && (n != numaGetCount(nax))) return ERROR_INT("nax and nay sizes differ", procName, 1); if (n == 1 && plotstyle == GPLOT_LINES) { L_INFO("only 1 pt; changing style to points\n", procName); plotstyle = GPLOT_POINTS; } /* Save plotstyle and plottitle */ numaGetParameters(nay, &startx, &delx); numaAddNumber(gplot->plotstyles, plotstyle); if (plottitle) { title = stringNew(plottitle); sarrayAddString(gplot->plottitles, title, L_INSERT); } else { sarrayAddString(gplot->plottitles, emptystring, L_COPY); } /* Generate and save data filename */ gplot->nplots++; snprintf(buf, L_BUF_SIZE, "%s.data.%d", gplot->rootname, gplot->nplots); sarrayAddString(gplot->datanames, buf, L_COPY); /* Generate data and save as a string */ sa = sarrayCreate(n); for (i = 0; i < n; i++) { if (nax) numaGetFValue(nax, i, &valx); else valx = startx + i * delx; numaGetFValue(nay, i, &valy); snprintf(buf, L_BUF_SIZE, "%f %f\n", valx, valy); sarrayAddString(sa, buf, L_COPY); } datastr = sarrayToString(sa, 0); sarrayAddString(gplot->plotdata, datastr, L_INSERT); sarrayDestroy(&sa); return 0; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
gplotAddPlot(GPLOT *gplot, NUMA *nax, NUMA *nay, l_int32 plotstyle, const char *plottitle) { char buf[L_BUFSIZE]; char emptystring[] = ""; char *datastr, *title; l_int32 n, i; l_float32 valx, valy, startx, delx; SARRAY *sa; PROCNAME("gplotAddPlot"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); if (!nay) return ERROR_INT("nay not defined", procName, 1); if (plotstyle < 0 || plotstyle >= NUM_GPLOT_STYLES) return ERROR_INT("invalid plotstyle", procName, 1); if ((n = numaGetCount(nay)) == 0) return ERROR_INT("no points to plot", procName, 1); if (nax && (n != numaGetCount(nax))) return ERROR_INT("nax and nay sizes differ", procName, 1); if (n == 1 && plotstyle == GPLOT_LINES) { L_INFO("only 1 pt; changing style to points\n", procName); plotstyle = GPLOT_POINTS; } /* Save plotstyle and plottitle */ numaGetParameters(nay, &startx, &delx); numaAddNumber(gplot->plotstyles, plotstyle); if (plottitle) { title = stringNew(plottitle); sarrayAddString(gplot->plottitles, title, L_INSERT); } else { sarrayAddString(gplot->plottitles, emptystring, L_COPY); } /* Generate and save data filename */ gplot->nplots++; snprintf(buf, L_BUFSIZE, "%s.data.%d", gplot->rootname, gplot->nplots); sarrayAddString(gplot->datanames, buf, L_COPY); /* Generate data and save as a string */ sa = sarrayCreate(n); for (i = 0; i < n; i++) { if (nax) numaGetFValue(nax, i, &valx); else valx = startx + i * delx; numaGetFValue(nay, i, &valy); snprintf(buf, L_BUFSIZE, "%f %f\n", valx, valy); sarrayAddString(sa, buf, L_COPY); } datastr = sarrayToString(sa, 0); sarrayAddString(gplot->plotdata, datastr, L_INSERT); sarrayDestroy(&sa); return 0; }
169,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int lz4_uncompress(const char *source, char *dest, int osize) { const BYTE *ip = (const BYTE *) source; const BYTE *ref; BYTE *op = (BYTE *) dest; BYTE * const oend = op + osize; BYTE *cpy; unsigned token; size_t length; size_t dec32table[] = {0, 3, 2, 3, 0, 0, 0, 0}; #if LZ4_ARCH64 size_t dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3}; #endif while (1) { /* get runlength */ token = *ip++; length = (token >> ML_BITS); if (length == RUN_MASK) { size_t len; len = *ip++; for (; len == 255; length += 255) len = *ip++; length += len; } /* copy literals */ cpy = op + length; if (unlikely(cpy > oend - COPYLENGTH)) { /* * Error: not enough place for another match * (min 4) + 5 literals */ if (cpy != oend) goto _output_error; memcpy(op, ip, length); ip += length; break; /* EOF */ } LZ4_WILDCOPY(ip, op, cpy); ip -= (op - cpy); op = cpy; /* get offset */ LZ4_READ_LITTLEENDIAN_16(ref, cpy, ip); ip += 2; /* Error: offset create reference outside destination buffer */ if (unlikely(ref < (BYTE *const) dest)) goto _output_error; /* get matchlength */ length = token & ML_MASK; if (length == ML_MASK) { for (; *ip == 255; length += 255) ip++; length += *ip++; } /* copy repeated sequence */ if (unlikely((op - ref) < STEPSIZE)) { #if LZ4_ARCH64 size_t dec64 = dec64table[op - ref]; #else const int dec64 = 0; #endif op[0] = ref[0]; op[1] = ref[1]; op[2] = ref[2]; op[3] = ref[3]; op += 4; ref += 4; ref -= dec32table[op-ref]; PUT4(ref, op); op += STEPSIZE - 4; ref -= dec64; } else { LZ4_COPYSTEP(ref, op); } cpy = op + length - (STEPSIZE - 4); if (cpy > (oend - COPYLENGTH)) { /* Error: request to write beyond destination buffer */ if (cpy > oend) goto _output_error; LZ4_SECURECOPY(ref, op, (oend - COPYLENGTH)); while (op < cpy) *op++ = *ref++; op = cpy; /* * Check EOF (should never happen, since last 5 bytes * are supposed to be literals) */ if (op == oend) goto _output_error; continue; } LZ4_SECURECOPY(ref, op, cpy); op = cpy; /* correction */ } /* end of decoding */ return (int) (((char *)ip) - source); /* write overflow error detected */ _output_error: return (int) (-(((char *)ip) - source)); } Commit Message: lz4: ensure length does not wrap Given some pathologically compressed data, lz4 could possibly decide to wrap a few internal variables, causing unknown things to happen. Catch this before the wrapping happens and abort the decompression. Reported-by: "Don A. Bailey" <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-20
static int lz4_uncompress(const char *source, char *dest, int osize) { const BYTE *ip = (const BYTE *) source; const BYTE *ref; BYTE *op = (BYTE *) dest; BYTE * const oend = op + osize; BYTE *cpy; unsigned token; size_t length; size_t dec32table[] = {0, 3, 2, 3, 0, 0, 0, 0}; #if LZ4_ARCH64 size_t dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3}; #endif while (1) { /* get runlength */ token = *ip++; length = (token >> ML_BITS); if (length == RUN_MASK) { size_t len; len = *ip++; for (; len == 255; length += 255) len = *ip++; if (unlikely(length > (size_t)(length + len))) goto _output_error; length += len; } /* copy literals */ cpy = op + length; if (unlikely(cpy > oend - COPYLENGTH)) { /* * Error: not enough place for another match * (min 4) + 5 literals */ if (cpy != oend) goto _output_error; memcpy(op, ip, length); ip += length; break; /* EOF */ } LZ4_WILDCOPY(ip, op, cpy); ip -= (op - cpy); op = cpy; /* get offset */ LZ4_READ_LITTLEENDIAN_16(ref, cpy, ip); ip += 2; /* Error: offset create reference outside destination buffer */ if (unlikely(ref < (BYTE *const) dest)) goto _output_error; /* get matchlength */ length = token & ML_MASK; if (length == ML_MASK) { for (; *ip == 255; length += 255) ip++; length += *ip++; } /* copy repeated sequence */ if (unlikely((op - ref) < STEPSIZE)) { #if LZ4_ARCH64 size_t dec64 = dec64table[op - ref]; #else const int dec64 = 0; #endif op[0] = ref[0]; op[1] = ref[1]; op[2] = ref[2]; op[3] = ref[3]; op += 4; ref += 4; ref -= dec32table[op-ref]; PUT4(ref, op); op += STEPSIZE - 4; ref -= dec64; } else { LZ4_COPYSTEP(ref, op); } cpy = op + length - (STEPSIZE - 4); if (cpy > (oend - COPYLENGTH)) { /* Error: request to write beyond destination buffer */ if (cpy > oend) goto _output_error; LZ4_SECURECOPY(ref, op, (oend - COPYLENGTH)); while (op < cpy) *op++ = *ref++; op = cpy; /* * Check EOF (should never happen, since last 5 bytes * are supposed to be literals) */ if (op == oend) goto _output_error; continue; } LZ4_SECURECOPY(ref, op, cpy); op = cpy; /* correction */ } /* end of decoding */ return (int) (((char *)ip) - source); /* write overflow error detected */ _output_error: return (int) (-(((char *)ip) - source)); }
166,301
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: chunk_type_valid(png_uint_32 c) /* Bit whacking approach to chunk name validation that is intended to avoid * branches. The cost is that it uses a lot of 32-bit constants, which might * be bad on some architectures. */ { png_uint_32 t; /* Remove bit 5 from all but the reserved byte; this means every * 8-bit unit must be in the range 65-90 to be valid. So bit 5 * must be zero, bit 6 must be set and bit 7 zero. */ c &= ~PNG_U32(32,32,0,32); t = (c & ~0x1f1f1f1f) ^ 0x40404040; /* Subtract 65 for each 8 bit quantity, this must not overflow * and each byte must then be in the range 0-25. */ c -= PNG_U32(65,65,65,65); t |=c ; /* Subtract 26, handling the overflow which should set the top * three bits of each byte. */ c -= PNG_U32(25,25,25,26); t |= ~c; return (t & 0xe0e0e0e0) == 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
chunk_type_valid(png_uint_32 c) /* Bit whacking approach to chunk name validation that is intended to avoid * branches. The cost is that it uses a lot of 32-bit constants, which might * be bad on some architectures. */ { png_uint_32 t; /* Remove bit 5 from all but the reserved byte; this means every * 8-bit unit must be in the range 65-90 to be valid. So bit 5 * must be zero, bit 6 must be set and bit 7 zero. */ c &= ~PNG_U32(32,32,0,32); t = (c & ~0x1f1f1f1f) ^ 0x40404040; /* Subtract 65 for each 8-bit quantity, this must not overflow * and each byte must then be in the range 0-25. */ c -= PNG_U32(65,65,65,65); t |=c ; /* Subtract 26, handling the overflow which should set the top * three bits of each byte. */ c -= PNG_U32(25,25,25,26); t |= ~c; return (t & 0xe0e0e0e0) == 0; }
173,730
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothOptionsHandler::GenerateFakePairing( const std::string& name, const std::string& address, const std::string& icon, const std::string& pairing) { DictionaryValue device; device.SetString("name", name); device.SetString("address", address); device.SetString("icon", icon); device.SetBoolean("paired", false); device.SetBoolean("connected", false); DictionaryValue op; op.SetString("pairing", pairing); if (pairing.compare("bluetoothEnterPasskey") != 0) op.SetInteger("passkey", 12345); if (pairing.compare("bluetoothRemotePasskey") == 0) op.SetInteger("entered", 2); web_ui_->CallJavascriptFunction( "options.SystemOptions.connectBluetoothDevice", device, op); } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void BluetoothOptionsHandler::GenerateFakePairing( bool connected, const std::string& pairing) { DictionaryValue properties; properties.SetString(bluetooth_device::kNameProperty, name); properties.SetString(bluetooth_device::kAddressProperty, address); properties.SetString(bluetooth_device::kIconProperty, icon); properties.SetBoolean(bluetooth_device::kPairedProperty, paired); properties.SetBoolean(bluetooth_device::kConnectedProperty, connected); properties.SetInteger(bluetooth_device::kClassProperty, 0); chromeos::BluetoothDevice* device = chromeos::BluetoothDevice::Create(properties); DeviceFound("FakeAdapter", device); if (pairing.compare("bluetoothRemotePasskey") == 0) { DisplayPasskey(device, 12345, 2); } else if (pairing.compare("bluetoothConfirmPasskey") == 0) { RequestConfirmation(device, 12345); } else if (pairing.compare("bluetoothEnterPasskey") == 0) { RequestPasskey(device); } delete device; }
170,970
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp) { ns->shm_tot -= (shp->shm_segsz + PAGE_SIZE - 1) >> PAGE_SHIFT; shm_rmid(ns, shp); shm_unlock(shp); if (!is_file_hugepages(shp->shm_file)) shmem_lock(shp->shm_file, 0, shp->mlock_user); else if (shp->mlock_user) user_shm_unlock(file_inode(shp->shm_file)->i_size, shp->mlock_user); fput (shp->shm_file); ipc_rcu_putref(shp, shm_rcu_free); } Commit Message: ipc,shm: fix shm_file deletion races When IPC_RMID races with other shm operations there's potential for use-after-free of the shm object's associated file (shm_file). Here's the race before this patch: TASK 1 TASK 2 ------ ------ shm_rmid() ipc_lock_object() shmctl() shp = shm_obtain_object_check() shm_destroy() shum_unlock() fput(shp->shm_file) ipc_lock_object() shmem_lock(shp->shm_file) <OOPS> The oops is caused because shm_destroy() calls fput() after dropping the ipc_lock. fput() clears the file's f_inode, f_path.dentry, and f_path.mnt, which causes various NULL pointer references in task 2. I reliably see the oops in task 2 if with shmlock, shmu This patch fixes the races by: 1) set shm_file=NULL in shm_destroy() while holding ipc_object_lock(). 2) modify at risk operations to check shm_file while holding ipc_object_lock(). Example workloads, which each trigger oops... Workload 1: while true; do id=$(shmget 1 4096) shm_rmid $id & shmlock $id & wait done The oops stack shows accessing NULL f_inode due to racing fput: _raw_spin_lock shmem_lock SyS_shmctl Workload 2: while true; do id=$(shmget 1 4096) shmat $id 4096 & shm_rmid $id & wait done The oops stack is similar to workload 1 due to NULL f_inode: touch_atime shmem_mmap shm_mmap mmap_region do_mmap_pgoff do_shmat SyS_shmat Workload 3: while true; do id=$(shmget 1 4096) shmlock $id shm_rmid $id & shmunlock $id & wait done The oops stack shows second fput tripping on an NULL f_inode. The first fput() completed via from shm_destroy(), but a racing thread did a get_file() and queued this fput(): locks_remove_flock __fput ____fput task_work_run do_notify_resume int_signal Fixes: c2c737a0461e ("ipc,shm: shorten critical region for shmat") Fixes: 2caacaa82a51 ("ipc,shm: shorten critical region for shmctl") Signed-off-by: Greg Thelen <[email protected]> Cc: Davidlohr Bueso <[email protected]> Cc: Rik van Riel <[email protected]> Cc: Manfred Spraul <[email protected]> Cc: <[email protected]> # 3.10.17+ 3.11.6+ Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
static void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp) { struct file *shm_file; shm_file = shp->shm_file; shp->shm_file = NULL; ns->shm_tot -= (shp->shm_segsz + PAGE_SIZE - 1) >> PAGE_SHIFT; shm_rmid(ns, shp); shm_unlock(shp); if (!is_file_hugepages(shm_file)) shmem_lock(shm_file, 0, shp->mlock_user); else if (shp->mlock_user) user_shm_unlock(file_inode(shm_file)->i_size, shp->mlock_user); fput(shm_file); ipc_rcu_putref(shp, shm_rcu_free); }
165,912
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: l2tp_result_code_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr))); ptr++; /* Result Code */ if (length > 2) { /* Error Code (opt) */ ND_PRINT((ndo, "/%u", EXTRACT_16BITS(ptr))); ptr++; } if (length > 4) { /* Error Message (opt) */ ND_PRINT((ndo, " ")); print_string(ndo, (const u_char *)ptr, length - 4); } } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_result_code_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; /* Result Code */ if (length < 2) { ND_PRINT((ndo, "AVP too short")); return; } ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr))); ptr++; length -= 2; /* Error Code (opt) */ if (length == 0) return; if (length < 2) { ND_PRINT((ndo, " AVP too short")); return; } ND_PRINT((ndo, "/%u", EXTRACT_16BITS(ptr))); ptr++; length -= 2; /* Error Message (opt) */ if (length == 0) return; ND_PRINT((ndo, " ")); print_string(ndo, (const u_char *)ptr, length); }
167,902
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_asntime_into_isotime (unsigned char const **buf, size_t *len, ksba_isotime_t isotime) { struct tag_info ti; gpg_error_t err; err = _ksba_ber_parse_tl (buf, len, &ti); if (err) ; else if ( !(ti.class == CLASS_UNIVERSAL && (ti.tag == TYPE_UTC_TIME || ti.tag == TYPE_GENERALIZED_TIME) && !ti.is_constructed) ) err = gpg_error (GPG_ERR_INV_OBJ); else if (!(err = _ksba_asntime_to_iso (*buf, ti.length, ti.tag == TYPE_UTC_TIME, isotime))) parse_skip (buf, len, &ti); } Commit Message: CWE ID: CWE-20
parse_asntime_into_isotime (unsigned char const **buf, size_t *len, ksba_isotime_t isotime) { struct tag_info ti; gpg_error_t err; err = _ksba_ber_parse_tl (buf, len, &ti); if (err) ; else if ( !(ti.class == CLASS_UNIVERSAL && (ti.tag == TYPE_UTC_TIME || ti.tag == TYPE_GENERALIZED_TIME) && !ti.is_constructed) ) err = gpg_error (GPG_ERR_INV_OBJ); else if (ti.length > *len) err = gpg_error (GPG_ERR_INV_BER); else if (!(err = _ksba_asntime_to_iso (*buf, ti.length, ti.tag == TYPE_UTC_TIME, isotime))) parse_skip (buf, len, &ti); }
165,030
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Initialize() { Initialize(kDefaultChannelLayout, kDefaultSampleBits); } Commit Message: Protect AudioRendererAlgorithm from invalid step sizes. BUG=165430 TEST=unittests and asan pass. Review URL: https://codereview.chromium.org/11573023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void Initialize() { Initialize(kDefaultChannelLayout, kDefaultSampleBits, kSamplesPerSecond); }
171,533
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Effect_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData){ EffectContext * pContext = (EffectContext *) self; int retsize; if(pContext->EffectType == LVM_BASS_BOOST){ } if(pContext->EffectType == LVM_VIRTUALIZER){ } if(pContext->EffectType == LVM_EQUALIZER){ } if(pContext->EffectType == LVM_VOLUME){ } if (pContext == NULL){ ALOGV("\tLVM_ERROR : Effect_command ERROR pContext == NULL"); return -EINVAL; } switch (cmdCode){ case EFFECT_CMD_INIT: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR, EFFECT_CMD_INIT: ERROR for effect type %d", pContext->EffectType); return -EINVAL; } *(int *) pReplyData = 0; if(pContext->EffectType == LVM_BASS_BOOST){ android::BassSetStrength(pContext, 0); } if(pContext->EffectType == LVM_VIRTUALIZER){ android::VirtualizerSetStrength(pContext, 0); } if(pContext->EffectType == LVM_EQUALIZER){ android::EqualizerSetPreset(pContext, 0); } if(pContext->EffectType == LVM_VOLUME){ *(int *) pReplyData = android::VolumeSetVolumeLevel(pContext, 0); } break; case EFFECT_CMD_SET_CONFIG: if (pCmdData == NULL|| cmdSize != sizeof(effect_config_t)|| pReplyData == NULL|| *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: " "EFFECT_CMD_SET_CONFIG: ERROR"); return -EINVAL; } *(int *) pReplyData = android::Effect_setConfig(pContext, (effect_config_t *) pCmdData); break; case EFFECT_CMD_GET_CONFIG: if (pReplyData == NULL || *replySize != sizeof(effect_config_t)) { ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: " "EFFECT_CMD_GET_CONFIG: ERROR"); return -EINVAL; } android::Effect_getConfig(pContext, (effect_config_t *)pReplyData); break; case EFFECT_CMD_RESET: android::Effect_setConfig(pContext, &pContext->config); break; case EFFECT_CMD_GET_PARAM:{ if(pContext->EffectType == LVM_BASS_BOOST){ if (pCmdData == NULL || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) || pReplyData == NULL || *replySize < (sizeof(effect_param_t) + sizeof(int32_t))){ ALOGV("\tLVM_ERROR : BassBoost_command cmdCode Case: " "EFFECT_CMD_GET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *)pCmdData; memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); p->status = android::BassBoost_getParameter(pContext, p->data, &p->vsize, p->data + voffset); *replySize = sizeof(effect_param_t) + voffset + p->vsize; } if(pContext->EffectType == LVM_VIRTUALIZER){ if (pCmdData == NULL || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) || pReplyData == NULL || *replySize < (sizeof(effect_param_t) + sizeof(int32_t))){ ALOGV("\tLVM_ERROR : Virtualizer_command cmdCode Case: " "EFFECT_CMD_GET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *)pCmdData; memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); p->status = android::Virtualizer_getParameter(pContext, (void *)p->data, &p->vsize, p->data + voffset); *replySize = sizeof(effect_param_t) + voffset + p->vsize; } if(pContext->EffectType == LVM_EQUALIZER){ if (pCmdData == NULL || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) || pReplyData == NULL || *replySize < (int) (sizeof(effect_param_t) + sizeof(int32_t))) { ALOGV("\tLVM_ERROR : Equalizer_command cmdCode Case: " "EFFECT_CMD_GET_PARAM"); return -EINVAL; } effect_param_t *p = (effect_param_t *)pCmdData; memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); p->status = android::Equalizer_getParameter(pContext, p->data, &p->vsize, p->data + voffset); *replySize = sizeof(effect_param_t) + voffset + p->vsize; } if(pContext->EffectType == LVM_VOLUME){ if (pCmdData == NULL || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) || pReplyData == NULL || *replySize < (int) (sizeof(effect_param_t) + sizeof(int32_t))){ ALOGV("\tLVM_ERROR : Volume_command cmdCode Case: " "EFFECT_CMD_GET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *)pCmdData; memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); p->status = android::Volume_getParameter(pContext, (void *)p->data, &p->vsize, p->data + voffset); *replySize = sizeof(effect_param_t) + voffset + p->vsize; } } break; case EFFECT_CMD_SET_PARAM:{ if(pContext->EffectType == LVM_BASS_BOOST){ if (pCmdData == NULL|| cmdSize != (sizeof(effect_param_t) + sizeof(int32_t) +sizeof(int16_t))|| pReplyData == NULL|| *replySize != sizeof(int32_t)){ ALOGV("\tLVM_ERROR : BassBoost_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; if (p->psize != sizeof(int32_t)){ ALOGV("\tLVM_ERROR : BassBoost_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)"); return -EINVAL; } *(int *)pReplyData = android::BassBoost_setParameter(pContext, (void *)p->data, p->data + p->psize); } if(pContext->EffectType == LVM_VIRTUALIZER){ if (pCmdData == NULL || cmdSize > (sizeof(effect_param_t) + sizeof(int32_t) +sizeof(int32_t)) || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t) +sizeof(int16_t)) || pReplyData == NULL || *replySize != sizeof(int32_t)){ ALOGV("\tLVM_ERROR : Virtualizer_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; if (p->psize != sizeof(int32_t)){ ALOGV("\tLVM_ERROR : Virtualizer_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)"); return -EINVAL; } *(int *)pReplyData = android::Virtualizer_setParameter(pContext, (void *)p->data, p->data + p->psize); } if(pContext->EffectType == LVM_EQUALIZER){ if (pCmdData == NULL || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) || pReplyData == NULL || *replySize != sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Equalizer_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; *(int *)pReplyData = android::Equalizer_setParameter(pContext, (void *)p->data, p->data + p->psize); } if(pContext->EffectType == LVM_VOLUME){ if ( pCmdData == NULL|| cmdSize < (sizeof(effect_param_t) + sizeof(int32_t))|| pReplyData == NULL|| *replySize != sizeof(int32_t)){ ALOGV("\tLVM_ERROR : Volume_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; *(int *)pReplyData = android::Volume_setParameter(pContext, (void *)p->data, p->data + p->psize); } } break; case EFFECT_CMD_ENABLE: ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_ENABLE start"); if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: EFFECT_CMD_ENABLE: ERROR"); return -EINVAL; } *(int *)pReplyData = android::Effect_setEnabled(pContext, LVM_TRUE); break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: EFFECT_CMD_DISABLE: ERROR"); return -EINVAL; } *(int *)pReplyData = android::Effect_setEnabled(pContext, LVM_FALSE); break; case EFFECT_CMD_SET_DEVICE: { ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_DEVICE start"); uint32_t device = *(uint32_t *)pCmdData; pContext->pBundledContext->nOutputDevice = (audio_devices_t) device; if (pContext->EffectType == LVM_BASS_BOOST) { if((device == AUDIO_DEVICE_OUT_SPEAKER) || (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) || (device == AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER)){ ALOGV("\tEFFECT_CMD_SET_DEVICE device is invalid for LVM_BASS_BOOST %d", *(int32_t *)pCmdData); ALOGV("\tEFFECT_CMD_SET_DEVICE temporary disable LVM_BAS_BOOST"); if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) { ALOGV("\tEFFECT_CMD_SET_DEVICE disable LVM_BASS_BOOST %d", *(int32_t *)pCmdData); android::LvmEffect_disable(pContext); } pContext->pBundledContext->bBassTempDisabled = LVM_TRUE; } else { ALOGV("\tEFFECT_CMD_SET_DEVICE device is valid for LVM_BASS_BOOST %d", *(int32_t *)pCmdData); if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) { ALOGV("\tEFFECT_CMD_SET_DEVICE re-enable LVM_BASS_BOOST %d", *(int32_t *)pCmdData); android::LvmEffect_enable(pContext); } pContext->pBundledContext->bBassTempDisabled = LVM_FALSE; } } if (pContext->EffectType == LVM_VIRTUALIZER) { if (pContext->pBundledContext->nVirtualizerForcedDevice == AUDIO_DEVICE_NONE) { if (android::VirtualizerIsDeviceSupported(device) != 0) { ALOGV("\tEFFECT_CMD_SET_DEVICE device is invalid for LVM_VIRTUALIZER %d", *(int32_t *)pCmdData); ALOGV("\tEFFECT_CMD_SET_DEVICE temporary disable LVM_VIRTUALIZER"); if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) { ALOGV("\tEFFECT_CMD_SET_DEVICE disable LVM_VIRTUALIZER %d", *(int32_t *)pCmdData); android::LvmEffect_disable(pContext); } pContext->pBundledContext->bVirtualizerTempDisabled = LVM_TRUE; } else { ALOGV("\tEFFECT_CMD_SET_DEVICE device is valid for LVM_VIRTUALIZER %d", *(int32_t *)pCmdData); if(pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE){ ALOGV("\tEFFECT_CMD_SET_DEVICE re-enable LVM_VIRTUALIZER %d", *(int32_t *)pCmdData); android::LvmEffect_enable(pContext); } pContext->pBundledContext->bVirtualizerTempDisabled = LVM_FALSE; } } // else virtualization mode is forced to a certain device, nothing to do } ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_DEVICE end"); break; } case EFFECT_CMD_SET_VOLUME: { uint32_t leftVolume, rightVolume; int16_t leftdB, rightdB; int16_t maxdB, pandB; int32_t vol_ret[2] = {1<<24,1<<24}; // Apply no volume int status = 0; LVM_ControlParams_t ActiveParams; /* Current control Parameters */ LVM_ReturnStatus_en LvmStatus=LVM_SUCCESS; /* Function call status */ if(pReplyData == LVM_NULL){ break; } if (pCmdData == NULL || cmdSize != 2 * sizeof(uint32_t)) { ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: " "EFFECT_CMD_SET_VOLUME: ERROR"); return -EINVAL; } leftVolume = ((*(uint32_t *)pCmdData)); rightVolume = ((*((uint32_t *)pCmdData + 1))); if(leftVolume == 0x1000000){ leftVolume -= 1; } if(rightVolume == 0x1000000){ rightVolume -= 1; } leftdB = android::LVC_Convert_VolToDb(leftVolume); rightdB = android::LVC_Convert_VolToDb(rightVolume); pandB = rightdB - leftdB; maxdB = leftdB; if(rightdB > maxdB){ maxdB = rightdB; } memcpy(pReplyData, vol_ret, sizeof(int32_t)*2); android::VolumeSetVolumeLevel(pContext, (int16_t)(maxdB*100)); /* Get the current settings */ LvmStatus =LVM_GetControlParameters(pContext->pBundledContext->hInstance,&ActiveParams); LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeSetStereoPosition") if(LvmStatus != LVM_SUCCESS) return -EINVAL; /* Volume parameters */ ActiveParams.VC_Balance = pandB; ALOGV("\t\tVolumeSetStereoPosition() (-96dB -> +96dB)-> %d\n", ActiveParams.VC_Balance ); /* Activate the initial settings */ LvmStatus =LVM_SetControlParameters(pContext->pBundledContext->hInstance,&ActiveParams); LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "VolumeSetStereoPosition") if(LvmStatus != LVM_SUCCESS) return -EINVAL; break; } case EFFECT_CMD_SET_AUDIO_MODE: break; default: return -EINVAL; } return 0; } /* end Effect_command */ Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int Effect_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData){ EffectContext * pContext = (EffectContext *) self; int retsize; if(pContext->EffectType == LVM_BASS_BOOST){ } if(pContext->EffectType == LVM_VIRTUALIZER){ } if(pContext->EffectType == LVM_EQUALIZER){ } if(pContext->EffectType == LVM_VOLUME){ } if (pContext == NULL){ ALOGV("\tLVM_ERROR : Effect_command ERROR pContext == NULL"); return -EINVAL; } switch (cmdCode){ case EFFECT_CMD_INIT: if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR, EFFECT_CMD_INIT: ERROR for effect type %d", pContext->EffectType); return -EINVAL; } *(int *) pReplyData = 0; if(pContext->EffectType == LVM_BASS_BOOST){ android::BassSetStrength(pContext, 0); } if(pContext->EffectType == LVM_VIRTUALIZER){ android::VirtualizerSetStrength(pContext, 0); } if(pContext->EffectType == LVM_EQUALIZER){ android::EqualizerSetPreset(pContext, 0); } if(pContext->EffectType == LVM_VOLUME){ *(int *) pReplyData = android::VolumeSetVolumeLevel(pContext, 0); } break; case EFFECT_CMD_SET_CONFIG: if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) { ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: " "EFFECT_CMD_SET_CONFIG: ERROR"); return -EINVAL; } *(int *) pReplyData = android::Effect_setConfig(pContext, (effect_config_t *) pCmdData); break; case EFFECT_CMD_GET_CONFIG: if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) { ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: " "EFFECT_CMD_GET_CONFIG: ERROR"); return -EINVAL; } android::Effect_getConfig(pContext, (effect_config_t *)pReplyData); break; case EFFECT_CMD_RESET: android::Effect_setConfig(pContext, &pContext->config); break; case EFFECT_CMD_GET_PARAM:{ effect_param_t *p = (effect_param_t *)pCmdData; if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) || cmdSize < (sizeof(effect_param_t) + p->psize) || pReplyData == NULL || replySize == NULL || *replySize < (sizeof(effect_param_t) + p->psize)) { ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: ERROR"); return -EINVAL; } memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); if(pContext->EffectType == LVM_BASS_BOOST){ p->status = android::BassBoost_getParameter(pContext, p->data, &p->vsize, p->data + voffset); } if(pContext->EffectType == LVM_VIRTUALIZER){ p->status = android::Virtualizer_getParameter(pContext, (void *)p->data, &p->vsize, p->data + voffset); } if(pContext->EffectType == LVM_EQUALIZER){ p->status = android::Equalizer_getParameter(pContext, p->data, &p->vsize, p->data + voffset); } if(pContext->EffectType == LVM_VOLUME){ p->status = android::Volume_getParameter(pContext, (void *)p->data, &p->vsize, p->data + voffset); } *replySize = sizeof(effect_param_t) + voffset + p->vsize; } break; case EFFECT_CMD_SET_PARAM:{ if(pContext->EffectType == LVM_BASS_BOOST){ if (pCmdData == NULL || cmdSize != (sizeof(effect_param_t) + sizeof(int32_t) +sizeof(int16_t)) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) { ALOGV("\tLVM_ERROR : BassBoost_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; if (p->psize != sizeof(int32_t)){ ALOGV("\tLVM_ERROR : BassBoost_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)"); return -EINVAL; } *(int *)pReplyData = android::BassBoost_setParameter(pContext, (void *)p->data, p->data + p->psize); } if(pContext->EffectType == LVM_VIRTUALIZER){ if (pCmdData == NULL || // legal parameters are int16_t or int32_t cmdSize > (sizeof(effect_param_t) + sizeof(int32_t) +sizeof(int32_t)) || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t) +sizeof(int16_t)) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Virtualizer_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; if (p->psize != sizeof(int32_t)){ ALOGV("\tLVM_ERROR : Virtualizer_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)"); return -EINVAL; } *(int *)pReplyData = android::Virtualizer_setParameter(pContext, (void *)p->data, p->data + p->psize); } if(pContext->EffectType == LVM_EQUALIZER){ if (pCmdData == NULL || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Equalizer_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; *(int *)pReplyData = android::Equalizer_setParameter(pContext, (void *)p->data, p->data + p->psize); } if(pContext->EffectType == LVM_VOLUME){ if (pCmdData == NULL || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Volume_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; *(int *)pReplyData = android::Volume_setParameter(pContext, (void *)p->data, p->data + p->psize); } } break; case EFFECT_CMD_ENABLE: ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_ENABLE start"); if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) { ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: EFFECT_CMD_ENABLE: ERROR"); return -EINVAL; } *(int *)pReplyData = android::Effect_setEnabled(pContext, LVM_TRUE); break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) { ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: EFFECT_CMD_DISABLE: ERROR"); return -EINVAL; } *(int *)pReplyData = android::Effect_setEnabled(pContext, LVM_FALSE); break; case EFFECT_CMD_SET_DEVICE: { ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_DEVICE start"); if (pCmdData == NULL){ ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: EFFECT_CMD_SET_DEVICE: ERROR"); return -EINVAL; } uint32_t device = *(uint32_t *)pCmdData; pContext->pBundledContext->nOutputDevice = (audio_devices_t) device; if (pContext->EffectType == LVM_BASS_BOOST) { if((device == AUDIO_DEVICE_OUT_SPEAKER) || (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) || (device == AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER)){ ALOGV("\tEFFECT_CMD_SET_DEVICE device is invalid for LVM_BASS_BOOST %d", *(int32_t *)pCmdData); ALOGV("\tEFFECT_CMD_SET_DEVICE temporary disable LVM_BAS_BOOST"); if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) { ALOGV("\tEFFECT_CMD_SET_DEVICE disable LVM_BASS_BOOST %d", *(int32_t *)pCmdData); android::LvmEffect_disable(pContext); } pContext->pBundledContext->bBassTempDisabled = LVM_TRUE; } else { ALOGV("\tEFFECT_CMD_SET_DEVICE device is valid for LVM_BASS_BOOST %d", *(int32_t *)pCmdData); if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) { ALOGV("\tEFFECT_CMD_SET_DEVICE re-enable LVM_BASS_BOOST %d", *(int32_t *)pCmdData); android::LvmEffect_enable(pContext); } pContext->pBundledContext->bBassTempDisabled = LVM_FALSE; } } if (pContext->EffectType == LVM_VIRTUALIZER) { if (pContext->pBundledContext->nVirtualizerForcedDevice == AUDIO_DEVICE_NONE) { if (android::VirtualizerIsDeviceSupported(device) != 0) { ALOGV("\tEFFECT_CMD_SET_DEVICE device is invalid for LVM_VIRTUALIZER %d", *(int32_t *)pCmdData); ALOGV("\tEFFECT_CMD_SET_DEVICE temporary disable LVM_VIRTUALIZER"); if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) { ALOGV("\tEFFECT_CMD_SET_DEVICE disable LVM_VIRTUALIZER %d", *(int32_t *)pCmdData); android::LvmEffect_disable(pContext); } pContext->pBundledContext->bVirtualizerTempDisabled = LVM_TRUE; } else { ALOGV("\tEFFECT_CMD_SET_DEVICE device is valid for LVM_VIRTUALIZER %d", *(int32_t *)pCmdData); if(pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE){ ALOGV("\tEFFECT_CMD_SET_DEVICE re-enable LVM_VIRTUALIZER %d", *(int32_t *)pCmdData); android::LvmEffect_enable(pContext); } pContext->pBundledContext->bVirtualizerTempDisabled = LVM_FALSE; } } // else virtualization mode is forced to a certain device, nothing to do } ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_DEVICE end"); break; } case EFFECT_CMD_SET_VOLUME: { uint32_t leftVolume, rightVolume; int16_t leftdB, rightdB; int16_t maxdB, pandB; int32_t vol_ret[2] = {1<<24,1<<24}; // Apply no volume int status = 0; LVM_ControlParams_t ActiveParams; /* Current control Parameters */ LVM_ReturnStatus_en LvmStatus=LVM_SUCCESS; /* Function call status */ if(pReplyData == LVM_NULL){ break; } if (pCmdData == NULL || cmdSize != 2 * sizeof(uint32_t) || pReplyData == NULL || replySize == NULL || *replySize < 2*sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: " "EFFECT_CMD_SET_VOLUME: ERROR"); return -EINVAL; } leftVolume = ((*(uint32_t *)pCmdData)); rightVolume = ((*((uint32_t *)pCmdData + 1))); if(leftVolume == 0x1000000){ leftVolume -= 1; } if(rightVolume == 0x1000000){ rightVolume -= 1; } leftdB = android::LVC_Convert_VolToDb(leftVolume); rightdB = android::LVC_Convert_VolToDb(rightVolume); pandB = rightdB - leftdB; maxdB = leftdB; if(rightdB > maxdB){ maxdB = rightdB; } memcpy(pReplyData, vol_ret, sizeof(int32_t)*2); android::VolumeSetVolumeLevel(pContext, (int16_t)(maxdB*100)); /* Get the current settings */ LvmStatus =LVM_GetControlParameters(pContext->pBundledContext->hInstance,&ActiveParams); LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeSetStereoPosition") if(LvmStatus != LVM_SUCCESS) return -EINVAL; /* Volume parameters */ ActiveParams.VC_Balance = pandB; ALOGV("\t\tVolumeSetStereoPosition() (-96dB -> +96dB)-> %d\n", ActiveParams.VC_Balance ); /* Activate the initial settings */ LvmStatus =LVM_SetControlParameters(pContext->pBundledContext->hInstance,&ActiveParams); LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "VolumeSetStereoPosition") if(LvmStatus != LVM_SUCCESS) return -EINVAL; break; } case EFFECT_CMD_SET_AUDIO_MODE: break; default: return -EINVAL; } return 0; } /* end Effect_command */
173,348
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int btpan_tap_send(int tap_fd, const BD_ADDR src, const BD_ADDR dst, UINT16 proto, const char* buf, UINT16 len, BOOLEAN ext, BOOLEAN forward) { UNUSED(ext); UNUSED(forward); if (tap_fd != INVALID_FD) { tETH_HDR eth_hdr; memcpy(&eth_hdr.h_dest, dst, ETH_ADDR_LEN); memcpy(&eth_hdr.h_src, src, ETH_ADDR_LEN); eth_hdr.h_proto = htons(proto); char packet[TAP_MAX_PKT_WRITE_LEN + sizeof(tETH_HDR)]; memcpy(packet, &eth_hdr, sizeof(tETH_HDR)); if (len > TAP_MAX_PKT_WRITE_LEN) { LOG_ERROR("btpan_tap_send eth packet size:%d is exceeded limit!", len); return -1; } memcpy(packet + sizeof(tETH_HDR), buf, len); /* Send data to network interface */ int ret = write(tap_fd, packet, len + sizeof(tETH_HDR)); BTIF_TRACE_DEBUG("ret:%d", ret); return ret; } return -1; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
int btpan_tap_send(int tap_fd, const BD_ADDR src, const BD_ADDR dst, UINT16 proto, const char* buf, UINT16 len, BOOLEAN ext, BOOLEAN forward) { UNUSED(ext); UNUSED(forward); if (tap_fd != INVALID_FD) { tETH_HDR eth_hdr; memcpy(&eth_hdr.h_dest, dst, ETH_ADDR_LEN); memcpy(&eth_hdr.h_src, src, ETH_ADDR_LEN); eth_hdr.h_proto = htons(proto); char packet[TAP_MAX_PKT_WRITE_LEN + sizeof(tETH_HDR)]; memcpy(packet, &eth_hdr, sizeof(tETH_HDR)); if (len > TAP_MAX_PKT_WRITE_LEN) { LOG_ERROR("btpan_tap_send eth packet size:%d is exceeded limit!", len); return -1; } memcpy(packet + sizeof(tETH_HDR), buf, len); /* Send data to network interface */ int ret = TEMP_FAILURE_RETRY(write(tap_fd, packet, len + sizeof(tETH_HDR))); BTIF_TRACE_DEBUG("ret:%d", ret); return ret; } return -1; }
173,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ui::ModalType ExtensionInstallDialogView::GetModalType() const { return ui::MODAL_TYPE_WINDOW; } Commit Message: Make the webstore inline install dialog be tab-modal Also clean up a few minor lint errors while I'm in here. BUG=550047 Review URL: https://codereview.chromium.org/1496033003 Cr-Commit-Position: refs/heads/master@{#363925} CWE ID: CWE-17
ui::ModalType ExtensionInstallDialogView::GetModalType() const { return prompt_->ShouldUseTabModalDialog() ? ui::MODAL_TYPE_CHILD : ui::MODAL_TYPE_WINDOW; }
172,206
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PlatformFontSkia::InitDefaultFont() { if (g_default_font.Get()) return true; bool success = false; std::string family = kFallbackFontFamilyName; int size_pixels = 12; int style = Font::NORMAL; Font::Weight weight = Font::Weight::NORMAL; FontRenderParams params; const SkiaFontDelegate* delegate = SkiaFontDelegate::instance(); if (delegate) { delegate->GetDefaultFontDescription(&family, &size_pixels, &style, &weight, &params); } else if (default_font_description_) { #if defined(OS_CHROMEOS) FontRenderParamsQuery query; CHECK(FontList::ParseDescription(*default_font_description_, &query.families, &query.style, &query.pixel_size, &query.weight)) << "Failed to parse font description " << *default_font_description_; params = gfx::GetFontRenderParams(query, &family); size_pixels = query.pixel_size; style = query.style; weight = query.weight; #else NOTREACHED(); #endif } sk_sp<SkTypeface> typeface = CreateSkTypeface(style & Font::ITALIC, weight, &family, &success); if (!success) return false; g_default_font.Get() = new PlatformFontSkia( std::move(typeface), family, size_pixels, style, weight, params); return true; } Commit Message: Take default system font size from PlatformFont The default font returned by Skia should take the initial size from the default value kDefaultBaseFontSize specified in PlatformFont. [email protected], [email protected] [email protected] Bug: 944227 Change-Id: I6b230b80c349abbe5968edb3cebdd6e89db4c4a6 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1642738 Reviewed-by: Robert Liao <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Commit-Queue: Etienne Bergeron <[email protected]> Cr-Commit-Position: refs/heads/master@{#666299} CWE ID: CWE-862
bool PlatformFontSkia::InitDefaultFont() { if (g_default_font.Get()) return true; bool success = false; std::string family = kFallbackFontFamilyName; int size_pixels = PlatformFont::kDefaultBaseFontSize; int style = Font::NORMAL; Font::Weight weight = Font::Weight::NORMAL; FontRenderParams params; const SkiaFontDelegate* delegate = SkiaFontDelegate::instance(); if (delegate) { delegate->GetDefaultFontDescription(&family, &size_pixels, &style, &weight, &params); } else if (default_font_description_) { #if defined(OS_CHROMEOS) FontRenderParamsQuery query; CHECK(FontList::ParseDescription(*default_font_description_, &query.families, &query.style, &query.pixel_size, &query.weight)) << "Failed to parse font description " << *default_font_description_; params = gfx::GetFontRenderParams(query, &family); size_pixels = query.pixel_size; style = query.style; weight = query.weight; #else NOTREACHED(); #endif } sk_sp<SkTypeface> typeface = CreateSkTypeface(style & Font::ITALIC, weight, &family, &success); if (!success) return false; g_default_font.Get() = new PlatformFontSkia( std::move(typeface), family, size_pixels, style, weight, params); return true; }
173,209
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssl_do_connect (server * serv) { char buf[128]; g_sess = serv->server_session; if (SSL_connect (serv->ssl) <= 0) { char err_buf[128]; int err; g_sess = NULL; if ((err = ERR_get_error ()) > 0) { ERR_error_string (err, err_buf); snprintf (buf, sizeof (buf), "(%d) %s", err, err_buf); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); if (ERR_GET_REASON (err) == SSL_R_WRONG_VERSION_NUMBER) PrintText (serv->server_session, _("Are you sure this is a SSL capable server and port?\n")); server_cleanup (serv); if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } } g_sess = NULL; if (SSL_is_init_finished (serv->ssl)) { struct cert_info cert_info; struct chiper_info *chiper_info; int verify_error; int i; if (!_SSL_get_cert_info (&cert_info, serv->ssl)) { snprintf (buf, sizeof (buf), "* Certification info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Subject:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.subject_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.subject_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Issuer:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.issuer_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.issuer_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Public key algorithm: %s (%d bits)", cert_info.algorithm, cert_info.algorithm_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); /*if (cert_info.rsa_tmp_bits) { snprintf (buf, sizeof (buf), " Public key algorithm uses ephemeral key with %d bits", cert_info.rsa_tmp_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); }*/ snprintf (buf, sizeof (buf), " Sign algorithm %s", cert_info.sign_algorithm/*, cert_info.sign_algorithm_bits*/); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Valid since %s to %s", cert_info.notbefore, cert_info.notafter); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } else { snprintf (buf, sizeof (buf), " * No Certificate"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } chiper_info = _SSL_get_cipher_info (serv->ssl); /* static buffer */ snprintf (buf, sizeof (buf), "* Cipher info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Version: %s, cipher %s (%u bits)", chiper_info->version, chiper_info->chiper, chiper_info->chiper_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); verify_error = SSL_get_verify_result (serv->ssl); switch (verify_error) { case X509_V_OK: /* snprintf (buf, sizeof (buf), "* Verify OK (?)"); */ /* EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); */ break; case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: case X509_V_ERR_CERT_HAS_EXPIRED: if (serv->accept_invalid_cert) { snprintf (buf, sizeof (buf), "* Verify E: %s.? (%d) -- Ignored", X509_verify_cert_error_string (verify_error), verify_error); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); break; } default: snprintf (buf, sizeof (buf), "%s.? (%d)", X509_verify_cert_error_string (verify_error), verify_error); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); return (0); } server_stopconnecting (serv); /* activate gtk poll */ server_connected (serv); return (0); /* remove it (0) */ } else { if (serv->ssl->session && serv->ssl->session->time + SSLTMOUT < time (NULL)) { snprintf (buf, sizeof (buf), "SSL handshake timed out"); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); /* ->connecting = FALSE */ if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } return (1); /* call it more (1) */ } } Commit Message: ssl: Validate hostnames Closes #524 CWE ID: CWE-310
ssl_do_connect (server * serv) { char buf[128]; g_sess = serv->server_session; if (SSL_connect (serv->ssl) <= 0) { char err_buf[128]; int err; g_sess = NULL; if ((err = ERR_get_error ()) > 0) { ERR_error_string (err, err_buf); snprintf (buf, sizeof (buf), "(%d) %s", err, err_buf); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); if (ERR_GET_REASON (err) == SSL_R_WRONG_VERSION_NUMBER) PrintText (serv->server_session, _("Are you sure this is a SSL capable server and port?\n")); server_cleanup (serv); if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } } g_sess = NULL; if (SSL_is_init_finished (serv->ssl)) { struct cert_info cert_info; struct chiper_info *chiper_info; int verify_error; int i; if (!_SSL_get_cert_info (&cert_info, serv->ssl)) { snprintf (buf, sizeof (buf), "* Certification info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Subject:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.subject_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.subject_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Issuer:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.issuer_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.issuer_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Public key algorithm: %s (%d bits)", cert_info.algorithm, cert_info.algorithm_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); /*if (cert_info.rsa_tmp_bits) { snprintf (buf, sizeof (buf), " Public key algorithm uses ephemeral key with %d bits", cert_info.rsa_tmp_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); }*/ snprintf (buf, sizeof (buf), " Sign algorithm %s", cert_info.sign_algorithm/*, cert_info.sign_algorithm_bits*/); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Valid since %s to %s", cert_info.notbefore, cert_info.notafter); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } else { snprintf (buf, sizeof (buf), " * No Certificate"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } chiper_info = _SSL_get_cipher_info (serv->ssl); /* static buffer */ snprintf (buf, sizeof (buf), "* Cipher info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Version: %s, cipher %s (%u bits)", chiper_info->version, chiper_info->chiper, chiper_info->chiper_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); verify_error = SSL_get_verify_result (serv->ssl); switch (verify_error) { case X509_V_OK: { X509 *cert = SSL_get_peer_certificate (serv->ssl); int hostname_err; if ((hostname_err = _SSL_check_hostname(cert, serv->hostname)) != 0) { snprintf (buf, sizeof (buf), "* Verify E: Failed to validate hostname? (%d)%s", hostname_err, serv->accept_invalid_cert ? " -- Ignored" : ""); if (serv->accept_invalid_cert) EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); else goto conn_fail; } break; } /* snprintf (buf, sizeof (buf), "* Verify OK (?)"); */ /* EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); */ case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: case X509_V_ERR_CERT_HAS_EXPIRED: if (serv->accept_invalid_cert) { snprintf (buf, sizeof (buf), "* Verify E: %s.? (%d) -- Ignored", X509_verify_cert_error_string (verify_error), verify_error); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); break; } default: snprintf (buf, sizeof (buf), "%s.? (%d)", X509_verify_cert_error_string (verify_error), verify_error); conn_fail: EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); return (0); } server_stopconnecting (serv); /* activate gtk poll */ server_connected (serv); return (0); /* remove it (0) */ } else { if (serv->ssl->session && serv->ssl->session->time + SSLTMOUT < time (NULL)) { snprintf (buf, sizeof (buf), "SSL handshake timed out"); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); /* ->connecting = FALSE */ if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } return (1); /* call it more (1) */ } }
167,593
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DatabaseMessageFilter::OnDatabaseOpened(const string16& origin_identifier, const string16& database_name, const string16& description, int64 estimated_size) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); int64 database_size = 0; db_tracker_->DatabaseOpened(origin_identifier, database_name, description, estimated_size, &database_size); database_connections_.AddConnection(origin_identifier, database_name); Send(new DatabaseMsg_UpdateSize(origin_identifier, database_name, database_size)); } Commit Message: WebDatabase: check path traversal in origin_identifier BUG=172264 Review URL: https://chromiumcodereview.appspot.com/12212091 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@183141 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-22
void DatabaseMessageFilter::OnDatabaseOpened(const string16& origin_identifier, const string16& database_name, const string16& description, int64 estimated_size) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!DatabaseUtil::IsValidOriginIdentifier(origin_identifier)) { RecordAction(UserMetricsAction("BadMessageTerminate_DBMF")); BadMessageReceived(); return; } int64 database_size = 0; db_tracker_->DatabaseOpened(origin_identifier, database_name, description, estimated_size, &database_size); database_connections_.AddConnection(origin_identifier, database_name); Send(new DatabaseMsg_UpdateSize(origin_identifier, database_name, database_size)); }
171,477
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gfx::Rect ShellWindowFrameView::GetBoundsForClientView() const { if (frame_->IsFullscreen()) return bounds(); return gfx::Rect(0, kCaptionHeight, width(), std::max(0, 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::GetBoundsForClientView() const { if (is_frameless_ || frame_->IsFullscreen()) return bounds(); return gfx::Rect(0, kCaptionHeight, width(), std::max(0, height() - kCaptionHeight)); }
170,711
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: yyparse (void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env) { /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, yyscanner, lex_env); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 106 "hex_grammar.y" /* yacc.c:1646 */ { RE_AST* re_ast = yyget_extra(yyscanner); re_ast->root_node = (yyvsp[-1].re_node); } #line 1330 "hex_grammar.c" /* yacc.c:1646 */ break; case 3: #line 115 "hex_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = (yyvsp[0].re_node); } #line 1338 "hex_grammar.c" /* yacc.c:1646 */ break; case 4: #line 119 "hex_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1351 "hex_grammar.c" /* yacc.c:1646 */ break; case 5: #line 128 "hex_grammar.y" /* yacc.c:1646 */ { RE_NODE* new_concat; RE_NODE* leftmost_concat = NULL; RE_NODE* leftmost_node = (yyvsp[-1].re_node); (yyval.re_node) = NULL; /* Some portions of the code (i.e: yr_re_split_at_chaining_point) expect a left-unbalanced tree where the right child of a concat node can't be another concat node. A concat node must be always the left child of its parent if the parent is also a concat. For this reason the can't simply create two new concat nodes arranged like this: concat / \ / \ token's \ subtree concat / \ / \ / \ token_sequence's token's subtree subtree Instead we must insert the subtree for the first token as the leftmost node of the token_sequence subtree. */ while (leftmost_node->type == RE_NODE_CONCAT) { leftmost_concat = leftmost_node; leftmost_node = leftmost_node->left; } new_concat = yr_re_node_create( RE_NODE_CONCAT, (yyvsp[-2].re_node), leftmost_node); if (new_concat != NULL) { if (leftmost_concat != NULL) { leftmost_concat->left = new_concat; (yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node)); } else { (yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, new_concat, (yyvsp[0].re_node)); } } DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1413 "hex_grammar.c" /* yacc.c:1646 */ break; case 6: #line 190 "hex_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = (yyvsp[0].re_node); } #line 1421 "hex_grammar.c" /* yacc.c:1646 */ break; case 7: #line 194 "hex_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1434 "hex_grammar.c" /* yacc.c:1646 */ break; case 8: #line 207 "hex_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = (yyvsp[0].re_node); } #line 1442 "hex_grammar.c" /* yacc.c:1646 */ break; case 9: #line 211 "hex_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = (yyvsp[0].re_node); (yyval.re_node)->greedy = FALSE; } #line 1451 "hex_grammar.c" /* yacc.c:1646 */ break; case 10: #line 220 "hex_grammar.y" /* yacc.c:1646 */ { lex_env->token_count++; if (lex_env->token_count > MAX_HEX_STRING_TOKENS) { yr_re_node_destroy((yyvsp[0].re_node)); yyerror(yyscanner, lex_env, "string too long"); YYABORT; } (yyval.re_node) = (yyvsp[0].re_node); } #line 1468 "hex_grammar.c" /* yacc.c:1646 */ break; case 11: #line 233 "hex_grammar.y" /* yacc.c:1646 */ { lex_env->inside_or++; } #line 1476 "hex_grammar.c" /* yacc.c:1646 */ break; case 12: #line 237 "hex_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = (yyvsp[-1].re_node); lex_env->inside_or--; } #line 1485 "hex_grammar.c" /* yacc.c:1646 */ break; case 13: #line 246 "hex_grammar.y" /* yacc.c:1646 */ { if ((yyvsp[-1].integer) <= 0) { yyerror(yyscanner, lex_env, "invalid jump length"); YYABORT; } if (lex_env->inside_or && (yyvsp[-1].integer) > STRING_CHAINING_THRESHOLD) { yyerror(yyscanner, lex_env, "jumps over " STR(STRING_CHAINING_THRESHOLD) " now allowed inside alternation (|)"); YYABORT; } (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = (int) (yyvsp[-1].integer); (yyval.re_node)->end = (int) (yyvsp[-1].integer); } #line 1512 "hex_grammar.c" /* yacc.c:1646 */ break; case 14: #line 269 "hex_grammar.y" /* yacc.c:1646 */ { if (lex_env->inside_or && ((yyvsp[-3].integer) > STRING_CHAINING_THRESHOLD || (yyvsp[-1].integer) > STRING_CHAINING_THRESHOLD) ) { yyerror(yyscanner, lex_env, "jumps over " STR(STRING_CHAINING_THRESHOLD) " now allowed inside alternation (|)"); YYABORT; } if ((yyvsp[-3].integer) < 0 || (yyvsp[-1].integer) < 0) { yyerror(yyscanner, lex_env, "invalid negative jump length"); YYABORT; } if ((yyvsp[-3].integer) > (yyvsp[-1].integer)) { yyerror(yyscanner, lex_env, "invalid jump range"); YYABORT; } (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = (int) (yyvsp[-3].integer); (yyval.re_node)->end = (int) (yyvsp[-1].integer); } #line 1548 "hex_grammar.c" /* yacc.c:1646 */ break; case 15: #line 301 "hex_grammar.y" /* yacc.c:1646 */ { if (lex_env->inside_or) { yyerror(yyscanner, lex_env, "unbounded jumps not allowed inside alternation (|)"); YYABORT; } if ((yyvsp[-2].integer) < 0) { yyerror(yyscanner, lex_env, "invalid negative jump length"); YYABORT; } (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = (int) (yyvsp[-2].integer); (yyval.re_node)->end = INT_MAX; } #line 1574 "hex_grammar.c" /* yacc.c:1646 */ break; case 16: #line 323 "hex_grammar.y" /* yacc.c:1646 */ { if (lex_env->inside_or) { yyerror(yyscanner, lex_env, "unbounded jumps not allowed inside alternation (|)"); YYABORT; } (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = 0; (yyval.re_node)->end = INT_MAX; } #line 1594 "hex_grammar.c" /* yacc.c:1646 */ break; case 17: #line 343 "hex_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = (yyvsp[0].re_node); } #line 1602 "hex_grammar.c" /* yacc.c:1646 */ break; case 18: #line 347 "hex_grammar.y" /* yacc.c:1646 */ { mark_as_not_fast_regexp(); (yyval.re_node) = yr_re_node_create(RE_NODE_ALT, (yyvsp[-2].re_node), (yyvsp[0].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1617 "hex_grammar.c" /* yacc.c:1646 */ break; case 19: #line 361 "hex_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_LITERAL, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->value = (int) (yyvsp[0].integer); } #line 1629 "hex_grammar.c" /* yacc.c:1646 */ break; case 20: #line 369 "hex_grammar.y" /* yacc.c:1646 */ { uint8_t mask = (uint8_t) ((yyvsp[0].integer) >> 8); if (mask == 0x00) { (yyval.re_node) = yr_re_node_create(RE_NODE_ANY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } else { (yyval.re_node) = yr_re_node_create(RE_NODE_MASKED_LITERAL, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->value = (yyvsp[0].integer) & 0xFF; (yyval.re_node)->mask = mask; } } #line 1653 "hex_grammar.c" /* yacc.c:1646 */ break; #line 1657 "hex_grammar.c" /* yacc.c:1646 */ default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (yyscanner, lex_env, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (yyscanner, lex_env, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, yyscanner, lex_env); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp, yyscanner, lex_env); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (yyscanner, lex_env, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, yyscanner, lex_env); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yyscanner, lex_env); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } Commit Message: Fix issue #674 for hex strings. CWE ID: CWE-674
yyparse (void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env) { /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, yyscanner, lex_env); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 113 "hex_grammar.y" /* yacc.c:1661 */ { RE_AST* re_ast = yyget_extra(yyscanner); re_ast->root_node = (yyvsp[-1].re_node); } #line 1337 "hex_grammar.c" /* yacc.c:1661 */ break; case 3: #line 122 "hex_grammar.y" /* yacc.c:1661 */ { (yyval.re_node) = (yyvsp[0].re_node); } #line 1345 "hex_grammar.c" /* yacc.c:1661 */ break; case 4: #line 126 "hex_grammar.y" /* yacc.c:1661 */ { incr_ast_levels(); (yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1360 "hex_grammar.c" /* yacc.c:1661 */ break; case 5: #line 137 "hex_grammar.y" /* yacc.c:1661 */ { RE_NODE* new_concat; RE_NODE* leftmost_concat = NULL; RE_NODE* leftmost_node = (yyvsp[-1].re_node); incr_ast_levels(); (yyval.re_node) = NULL; /* Some portions of the code (i.e: yr_re_split_at_chaining_point) expect a left-unbalanced tree where the right child of a concat node can't be another concat node. A concat node must be always the left child of its parent if the parent is also a concat. For this reason the can't simply create two new concat nodes arranged like this: concat / \ / \ token's \ subtree concat / \ / \ / \ token_sequence's token's subtree subtree Instead we must insert the subtree for the first token as the leftmost node of the token_sequence subtree. */ while (leftmost_node->type == RE_NODE_CONCAT) { leftmost_concat = leftmost_node; leftmost_node = leftmost_node->left; } new_concat = yr_re_node_create( RE_NODE_CONCAT, (yyvsp[-2].re_node), leftmost_node); if (new_concat != NULL) { if (leftmost_concat != NULL) { leftmost_concat->left = new_concat; (yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node)); } else { (yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, new_concat, (yyvsp[0].re_node)); } } DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1424 "hex_grammar.c" /* yacc.c:1661 */ break; case 6: #line 201 "hex_grammar.y" /* yacc.c:1661 */ { (yyval.re_node) = (yyvsp[0].re_node); } #line 1432 "hex_grammar.c" /* yacc.c:1661 */ break; case 7: #line 205 "hex_grammar.y" /* yacc.c:1661 */ { incr_ast_levels(); (yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1447 "hex_grammar.c" /* yacc.c:1661 */ break; case 8: #line 220 "hex_grammar.y" /* yacc.c:1661 */ { (yyval.re_node) = (yyvsp[0].re_node); } #line 1455 "hex_grammar.c" /* yacc.c:1661 */ break; case 9: #line 224 "hex_grammar.y" /* yacc.c:1661 */ { (yyval.re_node) = (yyvsp[0].re_node); (yyval.re_node)->greedy = FALSE; } #line 1464 "hex_grammar.c" /* yacc.c:1661 */ break; case 10: #line 233 "hex_grammar.y" /* yacc.c:1661 */ { lex_env->token_count++; if (lex_env->token_count > MAX_HEX_STRING_TOKENS) { yr_re_node_destroy((yyvsp[0].re_node)); yyerror(yyscanner, lex_env, "string too long"); YYABORT; } (yyval.re_node) = (yyvsp[0].re_node); } #line 1481 "hex_grammar.c" /* yacc.c:1661 */ break; case 11: #line 246 "hex_grammar.y" /* yacc.c:1661 */ { lex_env->inside_or++; } #line 1489 "hex_grammar.c" /* yacc.c:1661 */ break; case 12: #line 250 "hex_grammar.y" /* yacc.c:1661 */ { (yyval.re_node) = (yyvsp[-1].re_node); lex_env->inside_or--; } #line 1498 "hex_grammar.c" /* yacc.c:1661 */ break; case 13: #line 259 "hex_grammar.y" /* yacc.c:1661 */ { if ((yyvsp[-1].integer) <= 0) { yyerror(yyscanner, lex_env, "invalid jump length"); YYABORT; } if (lex_env->inside_or && (yyvsp[-1].integer) > STRING_CHAINING_THRESHOLD) { yyerror(yyscanner, lex_env, "jumps over " STR(STRING_CHAINING_THRESHOLD) " now allowed inside alternation (|)"); YYABORT; } (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = (int) (yyvsp[-1].integer); (yyval.re_node)->end = (int) (yyvsp[-1].integer); } #line 1525 "hex_grammar.c" /* yacc.c:1661 */ break; case 14: #line 282 "hex_grammar.y" /* yacc.c:1661 */ { if (lex_env->inside_or && ((yyvsp[-3].integer) > STRING_CHAINING_THRESHOLD || (yyvsp[-1].integer) > STRING_CHAINING_THRESHOLD) ) { yyerror(yyscanner, lex_env, "jumps over " STR(STRING_CHAINING_THRESHOLD) " now allowed inside alternation (|)"); YYABORT; } if ((yyvsp[-3].integer) < 0 || (yyvsp[-1].integer) < 0) { yyerror(yyscanner, lex_env, "invalid negative jump length"); YYABORT; } if ((yyvsp[-3].integer) > (yyvsp[-1].integer)) { yyerror(yyscanner, lex_env, "invalid jump range"); YYABORT; } (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = (int) (yyvsp[-3].integer); (yyval.re_node)->end = (int) (yyvsp[-1].integer); } #line 1561 "hex_grammar.c" /* yacc.c:1661 */ break; case 15: #line 314 "hex_grammar.y" /* yacc.c:1661 */ { if (lex_env->inside_or) { yyerror(yyscanner, lex_env, "unbounded jumps not allowed inside alternation (|)"); YYABORT; } if ((yyvsp[-2].integer) < 0) { yyerror(yyscanner, lex_env, "invalid negative jump length"); YYABORT; } (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = (int) (yyvsp[-2].integer); (yyval.re_node)->end = INT_MAX; } #line 1587 "hex_grammar.c" /* yacc.c:1661 */ break; case 16: #line 336 "hex_grammar.y" /* yacc.c:1661 */ { if (lex_env->inside_or) { yyerror(yyscanner, lex_env, "unbounded jumps not allowed inside alternation (|)"); YYABORT; } (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = 0; (yyval.re_node)->end = INT_MAX; } #line 1607 "hex_grammar.c" /* yacc.c:1661 */ break; case 17: #line 356 "hex_grammar.y" /* yacc.c:1661 */ { (yyval.re_node) = (yyvsp[0].re_node); } #line 1615 "hex_grammar.c" /* yacc.c:1661 */ break; case 18: #line 360 "hex_grammar.y" /* yacc.c:1661 */ { mark_as_not_fast_regexp(); incr_ast_levels(); (yyval.re_node) = yr_re_node_create(RE_NODE_ALT, (yyvsp[-2].re_node), (yyvsp[0].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1631 "hex_grammar.c" /* yacc.c:1661 */ break; case 19: #line 375 "hex_grammar.y" /* yacc.c:1661 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_LITERAL, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->value = (int) (yyvsp[0].integer); } #line 1643 "hex_grammar.c" /* yacc.c:1661 */ break; case 20: #line 383 "hex_grammar.y" /* yacc.c:1661 */ { uint8_t mask = (uint8_t) ((yyvsp[0].integer) >> 8); if (mask == 0x00) { (yyval.re_node) = yr_re_node_create(RE_NODE_ANY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } else { (yyval.re_node) = yr_re_node_create(RE_NODE_MASKED_LITERAL, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->value = (yyvsp[0].integer) & 0xFF; (yyval.re_node)->mask = mask; } } #line 1667 "hex_grammar.c" /* yacc.c:1661 */ break; #line 1671 "hex_grammar.c" /* yacc.c:1661 */ default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (yyscanner, lex_env, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (yyscanner, lex_env, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, yyscanner, lex_env); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp, yyscanner, lex_env); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (yyscanner, lex_env, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, yyscanner, lex_env); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yyscanner, lex_env); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; }
168,101
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int cg_mkdir(const char *path, mode_t mode) { struct fuse_context *fc = fuse_get_context(); char *fpath = NULL, *path1, *cgdir = NULL, *controller; const char *cgroup; int ret; if (!fc) return -EIO; controller = pick_controller_from_path(fc, path); if (!controller) return -EINVAL; cgroup = find_cgroup_in_path(path); if (!cgroup) return -EINVAL; get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) path1 = "/"; else path1 = cgdir; if (!fc_may_access(fc, controller, path1, NULL, O_RDWR)) { ret = -EACCES; goto out; } if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) { ret = -EACCES; goto out; } ret = cgfs_create(controller, cgroup, fc->uid, fc->gid); printf("cgfs_create returned %d for %s %s\n", ret, controller, cgroup); out: free(cgdir); return ret; } Commit Message: Fix checking of parent directories Taken from the justification in the launchpad bug: To a task in freezer cgroup /a/b/c/d, it should appear that there are no cgroups other than its descendents. Since this is a filesystem, we must have the parent directories, but each parent cgroup should only contain the child which the task can see. So, when this task looks at /a/b, it should see only directory 'c' and no files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x exists or not. Opening /a/b/tasks should result in -ENOENT. The caller_may_see_dir checks specifically whether a task may see a cgroup directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing opendir('/a/b/c/d'). caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at /a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only) directory which he can see in the path - 'c'. Beyond this, regular DAC permissions should apply, with the root-in-user-namespace privilege over its mapped uids being respected. The fc_may_access check does this check for both directories and files. This is CVE-2015-1342 (LP: #1508481) Signed-off-by: Serge Hallyn <[email protected]> CWE ID: CWE-264
int cg_mkdir(const char *path, mode_t mode) { struct fuse_context *fc = fuse_get_context(); char *fpath = NULL, *path1, *cgdir = NULL, *controller, *next = NULL; const char *cgroup; int ret; if (!fc) return -EIO; controller = pick_controller_from_path(fc, path); if (!controller) return -EINVAL; cgroup = find_cgroup_in_path(path); if (!cgroup) return -EINVAL; get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) path1 = "/"; else path1 = cgdir; if (!caller_is_in_ancestor(fc->pid, controller, path1, &next)) { if (fpath && strcmp(next, fpath) == 0) ret = -EEXIST; else ret = -ENOENT; goto out; } if (!fc_may_access(fc, controller, path1, NULL, O_RDWR)) { ret = -EACCES; goto out; } if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) { ret = -EACCES; goto out; } ret = cgfs_create(controller, cgroup, fc->uid, fc->gid); printf("cgfs_create returned %d for %s %s\n", ret, controller, cgroup); out: free(cgdir); free(next); return ret; }
166,705
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ~InputMethodStatusConnection() { } bool IBusConnectionsAreAlive() { return ibus_ && ibus_bus_is_connected(ibus_) && ibus_config_; } void MaybeRestoreConnections() { if (IBusConnectionsAreAlive()) { return; } MaybeCreateIBus(); MaybeRestoreIBusConfig(); if (IBusConnectionsAreAlive()) { ConnectPanelServiceSignals(); if (connection_change_handler_) { LOG(INFO) << "Notifying Chrome that IBus is ready."; connection_change_handler_(language_library_, true); } } } void MaybeCreateIBus() { if (ibus_) { return; } ibus_init(); ibus_ = ibus_bus_new(); if (!ibus_) { LOG(ERROR) << "ibus_bus_new() failed"; return; } ConnectIBusSignals(); ibus_bus_set_watch_dbus_signal(ibus_, TRUE); ibus_bus_set_watch_ibus_signal(ibus_, TRUE); if (ibus_bus_is_connected(ibus_)) { LOG(INFO) << "IBus connection is ready."; } } void MaybeRestoreIBusConfig() { if (!ibus_) { return; } MaybeDestroyIBusConfig(); if (!ibus_config_) { GDBusConnection* ibus_connection = ibus_bus_get_connection(ibus_); if (!ibus_connection) { LOG(INFO) << "Couldn't create an ibus config object since " << "IBus connection is not ready."; return; } const gboolean disconnected = g_dbus_connection_is_closed(ibus_connection); if (disconnected) { LOG(ERROR) << "Couldn't create an ibus config object since " << "IBus connection is closed."; return; } ibus_config_ = ibus_config_new(ibus_connection, NULL /* do not cancel the operation */, NULL /* do not get error information */); if (!ibus_config_) { LOG(ERROR) << "ibus_config_new() failed. ibus-memconf is not ready?"; return; } g_object_ref(ibus_config_); LOG(INFO) << "ibus_config_ is ready."; } } void MaybeDestroyIBusConfig() { if (!ibus_) { LOG(ERROR) << "MaybeDestroyIBusConfig: ibus_ is NULL"; return; } if (ibus_config_ && !ibus_bus_is_connected(ibus_)) { g_object_unref(ibus_config_); ibus_config_ = NULL; } } void FocusIn(const char* input_context_path) { if (!input_context_path) { LOG(ERROR) << "NULL context passed"; } else { DLOG(INFO) << "FocusIn: " << input_context_path; } input_context_path_ = Or(input_context_path, ""); } void RegisterProperties(IBusPropList* ibus_prop_list) { DLOG(INFO) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)"); ImePropertyList prop_list; // our representation. if (ibus_prop_list) { if (!FlattenPropertyList(ibus_prop_list, &prop_list)) { RegisterProperties(NULL); return; } } register_ime_properties_(language_library_, prop_list); } void UpdateProperty(IBusProperty* ibus_prop) { DLOG(INFO) << "UpdateProperty"; DCHECK(ibus_prop); ImePropertyList prop_list; // our representation. if (!FlattenProperty(ibus_prop, &prop_list)) { LOG(ERROR) << "Malformed properties are detected"; return; } if (!prop_list.empty()) { update_ime_property_(language_library_, prop_list); } } void UpdateUI(const char* current_global_engine_id) { DCHECK(current_global_engine_id); const IBusEngineInfo* engine_info = NULL; for (size_t i = 0; i < arraysize(kIBusEngines); ++i) { if (kIBusEngines[i].name == std::string(current_global_engine_id)) { engine_info = &kIBusEngines[i]; break; } } if (!engine_info) { LOG(ERROR) << current_global_engine_id << " is not found in the input method white-list."; return; } InputMethodDescriptor current_input_method = CreateInputMethodDescriptor(engine_info->name, engine_info->longname, engine_info->layout, engine_info->language); DLOG(INFO) << "Updating the UI. ID:" << current_input_method.id << ", keyboard_layout:" << current_input_method.keyboard_layout; current_input_method_changed_(language_library_, current_input_method); } void ConnectIBusSignals() { if (!ibus_) { return; } g_signal_connect_after(ibus_, "connected", G_CALLBACK(IBusBusConnectedCallback), this); g_signal_connect(ibus_, "disconnected", G_CALLBACK(IBusBusDisconnectedCallback), this); g_signal_connect(ibus_, "global-engine-changed", G_CALLBACK(IBusBusGlobalEngineChangedCallback), this); g_signal_connect(ibus_, "name-owner-changed", G_CALLBACK(IBusBusNameOwnerChangedCallback), this); } void ConnectPanelServiceSignals() { if (!ibus_) { return; } IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE( g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey)); if (!ibus_panel_service) { LOG(ERROR) << "IBusPanelService is NOT available."; return; } g_signal_connect(ibus_panel_service, "focus-in", G_CALLBACK(FocusInCallback), this); g_signal_connect(ibus_panel_service, "register-properties", G_CALLBACK(RegisterPropertiesCallback), this); g_signal_connect(ibus_panel_service, "update-property", G_CALLBACK(UpdatePropertyCallback), this); } static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << "IBus connection is recovered."; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } static void IBusBusDisconnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << "IBus connection is terminated."; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeDestroyIBusConfig(); if (self->connection_change_handler_) { LOG(INFO) << "Notifying Chrome that IBus is terminated."; self->connection_change_handler_(self->language_library_, false); } } static void IBusBusGlobalEngineChangedCallback( IBusBus* bus, const gchar* engine_name, gpointer user_data) { DCHECK(engine_name); DLOG(INFO) << "Global engine is changed to " << engine_name; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->UpdateUI(engine_name); } static void IBusBusNameOwnerChangedCallback( IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name, gpointer user_data) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); DLOG(INFO) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; return; } LOG(INFO) << "IBus config daemon is started. Recovering ibus_config_"; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } static void FocusInCallback(IBusPanelService* panel, const gchar* path, gpointer user_data) { g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->FocusIn(path); } static void RegisterPropertiesCallback(IBusPanelService* panel, IBusPropList* prop_list, gpointer user_data) { g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->RegisterProperties(prop_list); } static void UpdatePropertyCallback(IBusPanelService* panel, IBusProperty* ibus_prop, gpointer user_data) { g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->UpdateProperty(ibus_prop); } static void SetImeConfigCallback(GObject* source_object, GAsyncResult* res, gpointer user_data) { IBusConfig* config = IBUS_CONFIG(user_data); g_return_if_fail(config); GError* error = NULL; const gboolean result = ibus_config_set_value_async_finish(config, res, &error); if (!result) { std::string message = "(unknown error)"; if (error && error->message) { message = error->message; } LOG(ERROR) << "ibus_config_set_value_async failed: " << message; } if (error) { g_error_free(error); } g_object_unref(config); } LanguageCurrentInputMethodMonitorFunction current_input_method_changed_; LanguageRegisterImePropertiesFunction register_ime_properties_; LanguageUpdateImePropertyFunction update_ime_property_; LanguageConnectionChangeMonitorFunction connection_change_handler_; void* language_library_; IBusBus* ibus_; IBusConfig* ibus_config_; std::string input_context_path_; }; 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
~InputMethodStatusConnection() { ~IBusControllerImpl() { } bool IBusConnectionsAreAlive() { return ibus_ && ibus_bus_is_connected(ibus_) && ibus_config_; } void MaybeRestoreConnections() { if (IBusConnectionsAreAlive()) { return; } MaybeCreateIBus(); MaybeRestoreIBusConfig(); if (IBusConnectionsAreAlive()) { ConnectPanelServiceSignals(); VLOG(1) << "Notifying Chrome that IBus is ready."; FOR_EACH_OBSERVER(Observer, observers_, OnConnectionChange(true)); } } void MaybeCreateIBus() { if (ibus_) { return; } ibus_init(); ibus_ = ibus_bus_new(); if (!ibus_) { LOG(ERROR) << "ibus_bus_new() failed"; return; } ConnectIBusSignals(); ibus_bus_set_watch_dbus_signal(ibus_, TRUE); ibus_bus_set_watch_ibus_signal(ibus_, TRUE); if (ibus_bus_is_connected(ibus_)) { VLOG(1) << "IBus connection is ready."; } } void MaybeRestoreIBusConfig() { if (!ibus_) { return; } MaybeDestroyIBusConfig(); if (!ibus_config_) { GDBusConnection* ibus_connection = ibus_bus_get_connection(ibus_); if (!ibus_connection) { VLOG(1) << "Couldn't create an ibus config object since " << "IBus connection is not ready."; return; } const gboolean disconnected = g_dbus_connection_is_closed(ibus_connection); if (disconnected) { LOG(ERROR) << "Couldn't create an ibus config object since " << "IBus connection is closed."; return; } ibus_config_ = ibus_config_new(ibus_connection, NULL /* do not cancel the operation */, NULL /* do not get error information */); if (!ibus_config_) { LOG(ERROR) << "ibus_config_new() failed. ibus-memconf is not ready?"; return; } g_object_ref(ibus_config_); VLOG(1) << "ibus_config_ is ready."; } } void MaybeDestroyIBusConfig() { if (!ibus_) { LOG(ERROR) << "MaybeDestroyIBusConfig: ibus_ is NULL"; return; } if (ibus_config_ && !ibus_bus_is_connected(ibus_)) { g_object_unref(ibus_config_); ibus_config_ = NULL; } } void DoRegisterProperties(IBusPropList* ibus_prop_list) { VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)"); ImePropertyList prop_list; // our representation. if (ibus_prop_list) { if (!FlattenPropertyList(ibus_prop_list, &prop_list)) { DoRegisterProperties(NULL); return; } } VLOG(1) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)"); FOR_EACH_OBSERVER(Observer, observers_, OnRegisterImeProperties(prop_list)); } void UpdateUI(const char* current_global_engine_id) { DCHECK(current_global_engine_id); const IBusEngineInfo* engine_info = NULL; for (size_t i = 0; i < arraysize(kIBusEngines); ++i) { if (kIBusEngines[i].name == std::string(current_global_engine_id)) { engine_info = &kIBusEngines[i]; break; } } if (!engine_info) { LOG(ERROR) << current_global_engine_id << " is not found in the input method white-list."; return; } InputMethodDescriptor current_input_method = CreateInputMethodDescriptor(engine_info->name, engine_info->longname, engine_info->layout, engine_info->language); VLOG(1) << "Updating the UI. ID:" << current_input_method.id << ", keyboard_layout:" << current_input_method.keyboard_layout; FOR_EACH_OBSERVER(Observer, observers_, OnCurrentInputMethodChanged(current_input_method)); } void ConnectIBusSignals() { if (!ibus_) { return; } g_signal_connect_after(ibus_, "connected", G_CALLBACK(IBusBusConnectedThunk), this); g_signal_connect(ibus_, "disconnected", G_CALLBACK(IBusBusDisconnectedThunk), this); g_signal_connect(ibus_, "global-engine-changed", G_CALLBACK(IBusBusGlobalEngineChangedThunk), this); g_signal_connect(ibus_, "name-owner-changed", G_CALLBACK(IBusBusNameOwnerChangedThunk), this); } void ConnectPanelServiceSignals() { if (!ibus_) { return; } IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE( g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey)); if (!ibus_panel_service) { LOG(ERROR) << "IBusPanelService is NOT available."; return; } g_signal_connect(ibus_panel_service, "focus-in", G_CALLBACK(FocusInThunk), this); g_signal_connect(ibus_panel_service, "register-properties", G_CALLBACK(RegisterPropertiesThunk), this); g_signal_connect(ibus_panel_service, "update-property", G_CALLBACK(UpdatePropertyThunk), this); } void IBusBusConnected(IBusBus* bus) { LOG(WARNING) << "IBus connection is recovered."; MaybeRestoreConnections(); } void IBusBusDisconnected(IBusBus* bus) { LOG(WARNING) << "IBus connection is terminated."; MaybeDestroyIBusConfig(); VLOG(1) << "Notifying Chrome that IBus is terminated."; FOR_EACH_OBSERVER(Observer, observers_, OnConnectionChange(false)); } void IBusBusGlobalEngineChanged(IBusBus* bus, const gchar* engine_name) { DCHECK(engine_name); VLOG(1) << "Global engine is changed to " << engine_name; UpdateUI(engine_name); } void IBusBusNameOwnerChanged(IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); VLOG(1) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; // |OnConnectionChange| with false here to allow Chrome to return; } VLOG(1) << "IBus config daemon is started. Recovering ibus_config_"; // successfully created, |OnConnectionChange| will be called to MaybeRestoreConnections(); } void FocusIn(IBusPanelService* panel, const gchar* input_context_path) { if (!input_context_path) { LOG(ERROR) << "NULL context passed"; } else { VLOG(1) << "FocusIn: " << input_context_path; } // Remember the current ic path. input_context_path_ = Or(input_context_path, ""); } void RegisterProperties(IBusPanelService* panel, IBusPropList* prop_list) { DoRegisterProperties(prop_list); } void UpdateProperty(IBusPanelService* panel, IBusProperty* ibus_prop) { VLOG(1) << "UpdateProperty"; DCHECK(ibus_prop); // You can call // LOG(INFO) << "\n" << PrintProp(ibus_prop, 0); // here to dump |ibus_prop|. ImePropertyList prop_list; // our representation. if (!FlattenProperty(ibus_prop, &prop_list)) { // Don't update the UI on errors. LOG(ERROR) << "Malformed properties are detected"; return; } // Notify the change. if (!prop_list.empty()) { FOR_EACH_OBSERVER(Observer, observers_, OnUpdateImeProperty(prop_list)); } } static void SetImeConfigCallback(GObject* source_object, GAsyncResult* res, gpointer user_data) { IBusConfig* config = IBUS_CONFIG(user_data); g_return_if_fail(config); GError* error = NULL; const gboolean result = ibus_config_set_value_async_finish(config, res, &error); if (!result) { std::string message = "(unknown error)"; if (error && error->message) { message = error->message; } LOG(ERROR) << "ibus_config_set_value_async failed: " << message; } if (error) { g_error_free(error); } g_object_unref(config); } IBusBus* ibus_; IBusConfig* ibus_config_; std::string input_context_path_; ObserverList<Observer> observers_; };
170,553
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->64 */ coerce_reg_to_32(dst_reg); coerce_reg_to_32(&src_reg); } smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } if (src_known) dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; if (src_known) dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } Commit Message: bpf: fix incorrect tracking of register size truncation Properly handle register truncation to a smaller size. The old code first mirrors the clearing of the high 32 bits in the bitwise tristate representation, which is correct. But then, it computes the new arithmetic bounds as the intersection between the old arithmetic bounds and the bounds resulting from the bitwise tristate representation. Therefore, when coerce_reg_to_32() is called on a number with bounds [0xffff'fff8, 0x1'0000'0007], the verifier computes [0xffff'fff8, 0xffff'ffff] as bounds of the truncated number. This is incorrect: The truncated number could also be in the range [0, 7], and no meaningful arithmetic bounds can be computed in that case apart from the obvious [0, 0xffff'ffff]. Starting with v4.14, this is exploitable by unprivileged users as long as the unprivileged_bpf_disabled sysctl isn't set. Debian assigned CVE-2017-16996 for this issue. v2: - flip the mask during arithmetic bounds calculation (Ben Hutchings) v3: - add CVE number (Ben Hutchings) Fixes: b03c9f9fdc37 ("bpf/verifier: track signed and unsigned min/max values") Signed-off-by: Jann Horn <[email protected]> Acked-by: Edward Cree <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-119
static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->64 */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } if (src_known) dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; if (src_known) dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; }
167,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsImageGray(next_image) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/350 CWE ID: CWE-787
static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsImageGray(next_image) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); }
168,406
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ikev2_parent_inR1outI2_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct dh_continuation *dh = (struct dh_continuation *)pcrc; struct msg_digest *md = dh->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inR1outI2: calculating g^{xy}, sending I2")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (dh->md) release_md(dh->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == dh->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inR1outI2_tail(pcrc, r); if (dh->md != NULL) { complete_v2_state_transition(&dh->md, e); if (dh->md) release_md(dh->md); } reset_globals(); passert(GLOBALS_ARE_RESET()); } Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload CWE ID: CWE-20
static void ikev2_parent_inR1outI2_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct dh_continuation *dh = (struct dh_continuation *)pcrc; struct msg_digest *md = dh->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inR1outI2: calculating g^{xy}, sending I2")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (dh->md) release_md(dh->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == dh->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inR1outI2_tail(pcrc, r); if (dh->md != NULL) { complete_v2_state_transition(&dh->md, e); if (dh->md) release_md(dh->md); } reset_globals(); }
166,472
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy(RTCPeerConnectionHandlerClient* client) : m_client(client) { ASSERT_UNUSED(m_client, m_client); } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy(RTCPeerConnectionHandlerClient* client) : m_client(client) { ASSERT(m_client); }
170,346
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BaseRenderingContext2D::drawImage(ScriptState* script_state, CanvasImageSource* image_source, double sx, double sy, double sw, double sh, double dx, double dy, double dw, double dh, ExceptionState& exception_state) { if (!DrawingCanvas()) return; double start_time = 0; Optional<CustomCountHistogram> timer; if (!IsPaint2D()) { start_time = WTF::MonotonicallyIncreasingTime(); if (GetImageBuffer() && GetImageBuffer()->IsAccelerated()) { if (image_source->IsVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_video_gpu, ("Blink.Canvas.DrawImage.Video.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_video_gpu); } else if (image_source->IsCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_canvas_gpu, ("Blink.Canvas.DrawImage.Canvas.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_canvas_gpu); } else if (image_source->IsSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_svggpu, ("Blink.Canvas.DrawImage.SVG.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_svggpu); } else if (image_source->IsImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_image_bitmap_gpu, ("Blink.Canvas.DrawImage.ImageBitmap.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_image_bitmap_gpu); } else if (image_source->IsOffscreenCanvas()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_offscreencanvas_gpu, ("Blink.Canvas.DrawImage.OffscreenCanvas.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_offscreencanvas_gpu); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_others_gpu, ("Blink.Canvas.DrawImage.Others.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_others_gpu); } } else { if (image_source->IsVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_video_cpu, ("Blink.Canvas.DrawImage.Video.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_video_cpu); } else if (image_source->IsCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_canvas_cpu, ("Blink.Canvas.DrawImage.Canvas.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_canvas_cpu); } else if (image_source->IsSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_svgcpu, ("Blink.Canvas.DrawImage.SVG.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_svgcpu); } else if (image_source->IsImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_image_bitmap_cpu, ("Blink.Canvas.DrawImage.ImageBitmap.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_image_bitmap_cpu); } else if (image_source->IsOffscreenCanvas()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_offscreencanvas_cpu, ("Blink.Canvas.DrawImage.OffscreenCanvas.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_offscreencanvas_cpu); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_others_cpu, ("Blink.Canvas.DrawImage.Others.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_others_cpu); } } } scoped_refptr<Image> image; FloatSize default_object_size(Width(), Height()); SourceImageStatus source_image_status = kInvalidSourceImageStatus; if (!image_source->IsVideoElement()) { AccelerationHint hint = (HasImageBuffer() && GetImageBuffer()->IsAccelerated()) ? kPreferAcceleration : kPreferNoAcceleration; image = image_source->GetSourceImageForCanvas(&source_image_status, hint, kSnapshotReasonDrawImage, default_object_size); if (source_image_status == kUndecodableSourceImageStatus) { exception_state.ThrowDOMException( kInvalidStateError, "The HTMLImageElement provided is in the 'broken' state."); } if (!image || !image->width() || !image->height()) return; } else { if (!static_cast<HTMLVideoElement*>(image_source)->HasAvailableVideoFrame()) return; } if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dw) || !std::isfinite(dh) || !std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh) || !dw || !dh || !sw || !sh) return; FloatRect src_rect = NormalizeRect(FloatRect(sx, sy, sw, sh)); FloatRect dst_rect = NormalizeRect(FloatRect(dx, dy, dw, dh)); FloatSize image_size = image_source->ElementSize(default_object_size); ClipRectsToImageRect(FloatRect(FloatPoint(), image_size), &src_rect, &dst_rect); image_source->AdjustDrawRects(&src_rect, &dst_rect); if (src_rect.IsEmpty()) return; DisableDeferralReason reason = kDisableDeferralReasonUnknown; if (ShouldDisableDeferral(image_source, &reason)) DisableDeferral(reason); else if (image->IsTextureBacked()) DisableDeferral(kDisableDeferralDrawImageWithTextureBackedSourceImage); ValidateStateStack(); WillDrawImage(image_source); ValidateStateStack(); ImageBuffer* buffer = GetImageBuffer(); if (buffer && buffer->IsAccelerated() && !image_source->IsAccelerated()) { float src_area = src_rect.Width() * src_rect.Height(); if (src_area > CanvasHeuristicParameters::kDrawImageTextureUploadHardSizeLimit) { this->DisableAcceleration(); } else if (src_area > CanvasHeuristicParameters:: kDrawImageTextureUploadSoftSizeLimit) { SkRect bounds = dst_rect; SkMatrix ctm = DrawingCanvas()->getTotalMatrix(); ctm.mapRect(&bounds); float dst_area = dst_rect.Width() * dst_rect.Height(); if (src_area > dst_area * CanvasHeuristicParameters:: kDrawImageTextureUploadSoftSizeLimitScaleThreshold) { this->DisableAcceleration(); } } } ValidateStateStack(); if (OriginClean() && WouldTaintOrigin(image_source, ExecutionContext::From(script_state))) { SetOriginTainted(); ClearResolvedFilters(); } Draw( [this, &image_source, &image, &src_rect, dst_rect]( PaintCanvas* c, const PaintFlags* flags) // draw lambda { DrawImageInternal(c, image_source, image.get(), src_rect, dst_rect, flags); }, [this, &dst_rect](const SkIRect& clip_bounds) // overdraw test lambda { return RectContainsTransformedRect(dst_rect, clip_bounds); }, dst_rect, CanvasRenderingContext2DState::kImagePaintType, image_source->IsOpaque() ? CanvasRenderingContext2DState::kOpaqueImage : CanvasRenderingContext2DState::kNonOpaqueImage); ValidateStateStack(); if (!IsPaint2D()) { DCHECK(start_time); timer->Count((WTF::MonotonicallyIncreasingTime() - start_time) * WTF::Time::kMicrosecondsPerSecond); } } Commit Message: [PE] Distinguish between tainting due to canvas content and filter. A filter on a canvas can itself lead to origin tainting, for reasons other than that the canvas contents are tainted. This CL changes to distinguish these two causes, so that we recompute filters on content-tainting change. Bug: 778506 Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6 Reviewed-on: https://chromium-review.googlesource.com/811767 Reviewed-by: Fredrik Söderquist <[email protected]> Commit-Queue: Chris Harrelson <[email protected]> Cr-Commit-Position: refs/heads/master@{#522274} CWE ID: CWE-200
void BaseRenderingContext2D::drawImage(ScriptState* script_state, CanvasImageSource* image_source, double sx, double sy, double sw, double sh, double dx, double dy, double dw, double dh, ExceptionState& exception_state) { if (!DrawingCanvas()) return; double start_time = 0; Optional<CustomCountHistogram> timer; if (!IsPaint2D()) { start_time = WTF::MonotonicallyIncreasingTime(); if (GetImageBuffer() && GetImageBuffer()->IsAccelerated()) { if (image_source->IsVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_video_gpu, ("Blink.Canvas.DrawImage.Video.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_video_gpu); } else if (image_source->IsCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_canvas_gpu, ("Blink.Canvas.DrawImage.Canvas.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_canvas_gpu); } else if (image_source->IsSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_svggpu, ("Blink.Canvas.DrawImage.SVG.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_svggpu); } else if (image_source->IsImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_image_bitmap_gpu, ("Blink.Canvas.DrawImage.ImageBitmap.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_image_bitmap_gpu); } else if (image_source->IsOffscreenCanvas()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_offscreencanvas_gpu, ("Blink.Canvas.DrawImage.OffscreenCanvas.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_offscreencanvas_gpu); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_others_gpu, ("Blink.Canvas.DrawImage.Others.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_others_gpu); } } else { if (image_source->IsVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_video_cpu, ("Blink.Canvas.DrawImage.Video.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_video_cpu); } else if (image_source->IsCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_canvas_cpu, ("Blink.Canvas.DrawImage.Canvas.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_canvas_cpu); } else if (image_source->IsSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_svgcpu, ("Blink.Canvas.DrawImage.SVG.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_svgcpu); } else if (image_source->IsImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_image_bitmap_cpu, ("Blink.Canvas.DrawImage.ImageBitmap.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_image_bitmap_cpu); } else if (image_source->IsOffscreenCanvas()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_offscreencanvas_cpu, ("Blink.Canvas.DrawImage.OffscreenCanvas.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_offscreencanvas_cpu); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_others_cpu, ("Blink.Canvas.DrawImage.Others.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_others_cpu); } } } scoped_refptr<Image> image; FloatSize default_object_size(Width(), Height()); SourceImageStatus source_image_status = kInvalidSourceImageStatus; if (!image_source->IsVideoElement()) { AccelerationHint hint = (HasImageBuffer() && GetImageBuffer()->IsAccelerated()) ? kPreferAcceleration : kPreferNoAcceleration; image = image_source->GetSourceImageForCanvas(&source_image_status, hint, kSnapshotReasonDrawImage, default_object_size); if (source_image_status == kUndecodableSourceImageStatus) { exception_state.ThrowDOMException( kInvalidStateError, "The HTMLImageElement provided is in the 'broken' state."); } if (!image || !image->width() || !image->height()) return; } else { if (!static_cast<HTMLVideoElement*>(image_source)->HasAvailableVideoFrame()) return; } if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dw) || !std::isfinite(dh) || !std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh) || !dw || !dh || !sw || !sh) return; FloatRect src_rect = NormalizeRect(FloatRect(sx, sy, sw, sh)); FloatRect dst_rect = NormalizeRect(FloatRect(dx, dy, dw, dh)); FloatSize image_size = image_source->ElementSize(default_object_size); ClipRectsToImageRect(FloatRect(FloatPoint(), image_size), &src_rect, &dst_rect); image_source->AdjustDrawRects(&src_rect, &dst_rect); if (src_rect.IsEmpty()) return; DisableDeferralReason reason = kDisableDeferralReasonUnknown; if (ShouldDisableDeferral(image_source, &reason)) DisableDeferral(reason); else if (image->IsTextureBacked()) DisableDeferral(kDisableDeferralDrawImageWithTextureBackedSourceImage); ValidateStateStack(); WillDrawImage(image_source); ValidateStateStack(); ImageBuffer* buffer = GetImageBuffer(); if (buffer && buffer->IsAccelerated() && !image_source->IsAccelerated()) { float src_area = src_rect.Width() * src_rect.Height(); if (src_area > CanvasHeuristicParameters::kDrawImageTextureUploadHardSizeLimit) { this->DisableAcceleration(); } else if (src_area > CanvasHeuristicParameters:: kDrawImageTextureUploadSoftSizeLimit) { SkRect bounds = dst_rect; SkMatrix ctm = DrawingCanvas()->getTotalMatrix(); ctm.mapRect(&bounds); float dst_area = dst_rect.Width() * dst_rect.Height(); if (src_area > dst_area * CanvasHeuristicParameters:: kDrawImageTextureUploadSoftSizeLimitScaleThreshold) { this->DisableAcceleration(); } } } ValidateStateStack(); if (!origin_tainted_by_content_ && WouldTaintOrigin(image_source, ExecutionContext::From(script_state))) SetOriginTaintedByContent(); Draw( [this, &image_source, &image, &src_rect, dst_rect]( PaintCanvas* c, const PaintFlags* flags) // draw lambda { DrawImageInternal(c, image_source, image.get(), src_rect, dst_rect, flags); }, [this, &dst_rect](const SkIRect& clip_bounds) // overdraw test lambda { return RectContainsTransformedRect(dst_rect, clip_bounds); }, dst_rect, CanvasRenderingContext2DState::kImagePaintType, image_source->IsOpaque() ? CanvasRenderingContext2DState::kOpaqueImage : CanvasRenderingContext2DState::kNonOpaqueImage); ValidateStateStack(); if (!IsPaint2D()) { DCHECK(start_time); timer->Count((WTF::MonotonicallyIncreasingTime() - start_time) * WTF::Time::kMicrosecondsPerSecond); } }
172,907
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Init() { DCHECK(!initialized_successfully_) << "Already initialized"; if (!CrosLibrary::Get()->EnsureLoaded()) return false; input_method_status_connection_ = chromeos::MonitorInputMethodStatus( this, &InputMethodChangedHandler, &RegisterPropertiesHandler, &UpdatePropertyHandler, &ConnectionChangeHandler); if (!input_method_status_connection_) return false; initialized_successfully_ = true; return true; } 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
bool Init() { DCHECK(!initialized_successfully_) << "Already initialized"; ibus_controller_ = input_method::IBusController::Create(); // The observer should be added before Connect() so we can capture the // initial connection change. ibus_controller_->AddObserver(this); ibus_controller_->Connect(); initialized_successfully_ = true; return true; }
170,494
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), #if defined(OS_WIN) accessible_parent_(NULL), #endif frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), is_loading_(false), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), displayed_insecure_content_(false), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), is_being_destroyed_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), render_view_message_source_(NULL), render_frame_message_source_(NULL), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), virtual_keyboard_requested_(false), page_scale_factor_is_one_(true), loading_weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); wake_lock_service_context_.reset(new WakeLockServiceContext(this)); } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID:
WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), #if defined(OS_WIN) accessible_parent_(NULL), #endif frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), is_loading_(false), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), displayed_insecure_content_(false), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), is_being_destroyed_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), render_view_message_source_(NULL), render_frame_message_source_(NULL), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), virtual_keyboard_requested_(false), page_scale_factor_is_one_(true), loading_weak_factory_(this), weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); wake_lock_service_context_.reset(new WakeLockServiceContext(this)); }
172,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) { AHCICmdHdr *cmd = ad->cur_cmd; uint32_t opts = le32_to_cpu(cmd->opts); int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN; dma_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG)); dma_addr_t real_prdt_len = prdt_len; uint8_t *prdt; uint8_t *prdt; int i; int r = 0; int sum = 0; int off_idx = -1; int off_pos = -1; int tbl_entry_size; IDEBus *bus = &ad->port; BusState *qbus = BUS(bus); if (!sglist_alloc_hint) { DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts); return -1; if (prdt_len < real_prdt_len) { DPRINTF(ad->port_no, "mapped less than expected\n"); r = -1; goto out; } /* Get entries in the PRDT, init a qemu sglist accordingly */ if (sglist_alloc_hint > 0) { AHCI_SG *tbl = (AHCI_SG *)prdt; sum = 0; for (i = 0; i < sglist_alloc_hint; i++) { /* flags_size is zero-based */ tbl_entry_size = prdt_tbl_entry_size(&tbl[i]); if (offset <= (sum + tbl_entry_size)) { off_idx = i; off_pos = offset - sum; break; } sum += tbl_entry_size; } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %d\n", __func__, off_idx, off_pos); r = -1; goto out; } } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %d\n", __func__, off_idx, off_pos); r = -1; goto out; qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); } } out: dma_memory_unmap(ad->hba->as, prdt, prdt_len, DMA_DIRECTION_TO_DEVICE, prdt_len); /* flags_size is zero-based */ qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); } Commit Message: CWE ID: CWE-399
static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int32_t offset) { AHCICmdHdr *cmd = ad->cur_cmd; uint32_t opts = le32_to_cpu(cmd->opts); int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN; dma_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG)); dma_addr_t real_prdt_len = prdt_len; uint8_t *prdt; uint8_t *prdt; int i; int r = 0; uint64_t sum = 0; int off_idx = -1; int64_t off_pos = -1; int tbl_entry_size; IDEBus *bus = &ad->port; BusState *qbus = BUS(bus); /* * Note: AHCI PRDT can describe up to 256GiB. SATA/ATA only support * transactions of up to 32MiB as of ATA8-ACS3 rev 1b, assuming a * 512 byte sector size. We limit the PRDT in this implementation to * a reasonably large 2GiB, which can accommodate the maximum transfer * request for sector sizes up to 32K. */ if (!sglist_alloc_hint) { DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts); return -1; if (prdt_len < real_prdt_len) { DPRINTF(ad->port_no, "mapped less than expected\n"); r = -1; goto out; } /* Get entries in the PRDT, init a qemu sglist accordingly */ if (sglist_alloc_hint > 0) { AHCI_SG *tbl = (AHCI_SG *)prdt; sum = 0; for (i = 0; i < sglist_alloc_hint; i++) { /* flags_size is zero-based */ tbl_entry_size = prdt_tbl_entry_size(&tbl[i]); if (offset <= (sum + tbl_entry_size)) { off_idx = i; off_pos = offset - sum; break; } sum += tbl_entry_size; } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %d\n", __func__, off_idx, off_pos); r = -1; goto out; } } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %"PRId64"\n", __func__, off_idx, off_pos); r = -1; goto out; qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); } } out: dma_memory_unmap(ad->hba->as, prdt, prdt_len, DMA_DIRECTION_TO_DEVICE, prdt_len); /* flags_size is zero-based */ qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); if (sglist->size > INT32_MAX) { error_report("AHCI Physical Region Descriptor Table describes " "more than 2 GiB.\n"); qemu_sglist_destroy(sglist); r = -1; goto out; } }
164,838
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: asmlinkage void bad_mode(struct pt_regs *regs, int reason, unsigned int esr) { console_verbose(); pr_crit("Bad mode in %s handler detected, code 0x%08x\n", handler[reason], esr); die("Oops - bad mode", regs, 0); local_irq_disable(); panic("bad mode"); } Commit Message: arm64: don't kill the kernel on a bad esr from el0 Rather than completely killing the kernel if we receive an esr value we can't deal with in the el0 handlers, send the process a SIGILL and log the esr value in the hope that we can debug it. If we receive a bad esr from el1, we'll die() as before. Signed-off-by: Mark Rutland <[email protected]> Signed-off-by: Catalin Marinas <[email protected]> Cc: [email protected] CWE ID:
asmlinkage void bad_mode(struct pt_regs *regs, int reason, unsigned int esr) { siginfo_t info; void __user *pc = (void __user *)instruction_pointer(regs); console_verbose(); pr_crit("Bad mode in %s handler detected, code 0x%08x\n", handler[reason], esr); __show_regs(regs); info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_ILLOPC; info.si_addr = pc; arm64_notify_die("Oops - bad mode", regs, &info, 0); }
166,012
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool NavigationControllerImpl::RendererDidNavigate( RenderFrameHostImpl* rfh, const FrameHostMsg_DidCommitProvisionalLoad_Params& params, LoadCommittedDetails* details, bool is_navigation_within_page, NavigationHandleImpl* navigation_handle) { is_initial_navigation_ = false; bool overriding_user_agent_changed = false; if (GetLastCommittedEntry()) { details->previous_url = GetLastCommittedEntry()->GetURL(); details->previous_entry_index = GetLastCommittedEntryIndex(); if (pending_entry_ && pending_entry_->GetIsOverridingUserAgent() != GetLastCommittedEntry()->GetIsOverridingUserAgent()) overriding_user_agent_changed = true; } else { details->previous_url = GURL(); details->previous_entry_index = -1; } bool was_restored = false; DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() || pending_entry_->restore_type() != RestoreType::NONE); if (pending_entry_ && pending_entry_->restore_type() != RestoreType::NONE) { pending_entry_->set_restore_type(RestoreType::NONE); was_restored = true; } details->did_replace_entry = params.should_replace_current_entry; details->type = ClassifyNavigation(rfh, params); details->is_same_document = is_navigation_within_page; if (PendingEntryMatchesHandle(navigation_handle)) { if (pending_entry_->reload_type() != ReloadType::NONE) { last_committed_reload_type_ = pending_entry_->reload_type(); last_committed_reload_time_ = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); } else if (!pending_entry_->is_renderer_initiated() || params.gesture == NavigationGestureUser) { last_committed_reload_type_ = ReloadType::NONE; last_committed_reload_time_ = base::Time(); } } switch (details->type) { case NAVIGATION_TYPE_NEW_PAGE: RendererDidNavigateToNewPage(rfh, params, details->is_same_document, details->did_replace_entry, navigation_handle); break; case NAVIGATION_TYPE_EXISTING_PAGE: details->did_replace_entry = details->is_same_document; RendererDidNavigateToExistingPage(rfh, params, details->is_same_document, was_restored, navigation_handle); break; case NAVIGATION_TYPE_SAME_PAGE: RendererDidNavigateToSamePage(rfh, params, navigation_handle); break; case NAVIGATION_TYPE_NEW_SUBFRAME: RendererDidNavigateNewSubframe(rfh, params, details->is_same_document, details->did_replace_entry); break; case NAVIGATION_TYPE_AUTO_SUBFRAME: if (!RendererDidNavigateAutoSubframe(rfh, params)) { NotifyEntryChanged(GetLastCommittedEntry()); return false; } break; case NAVIGATION_TYPE_NAV_IGNORE: if (pending_entry_) { DiscardNonCommittedEntries(); delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL); } return false; default: NOTREACHED(); } base::Time timestamp = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); DVLOG(1) << "Navigation finished at (smoothed) timestamp " << timestamp.ToInternalValue(); DiscardNonCommittedEntriesInternal(); DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState."; NavigationEntryImpl* active_entry = GetLastCommittedEntry(); active_entry->SetTimestamp(timestamp); active_entry->SetHttpStatusCode(params.http_status_code); FrameNavigationEntry* frame_entry = active_entry->GetFrameEntry(rfh->frame_tree_node()); if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance()) frame_entry = nullptr; if (frame_entry) { DCHECK(params.page_state == frame_entry->page_state()); } if (!rfh->GetParent() && IsBlockedNavigation(navigation_handle->GetNetErrorCode())) { DCHECK(params.url_is_unreachable); active_entry->SetURL(GURL(url::kAboutBlankURL)); active_entry->SetVirtualURL(params.url); if (frame_entry) { frame_entry->SetPageState( PageState::CreateFromURL(active_entry->GetURL())); } } size_t redirect_chain_size = 0; for (size_t i = 0; i < params.redirects.size(); ++i) { redirect_chain_size += params.redirects[i].spec().length(); } UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size); active_entry->ResetForCommit(frame_entry); if (!rfh->GetParent()) CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance()); active_entry->SetBindings(rfh->GetEnabledBindings()); details->entry = active_entry; details->is_main_frame = !rfh->GetParent(); details->http_status_code = params.http_status_code; NotifyNavigationEntryCommitted(details); if (active_entry->GetURL().SchemeIs(url::kHttpsScheme) && !rfh->GetParent() && navigation_handle->GetNetErrorCode() == net::OK) { UMA_HISTOGRAM_BOOLEAN("Navigation.SecureSchemeHasSSLStatus", !!active_entry->GetSSL().certificate); } if (overriding_user_agent_changed) delegate_->UpdateOverridingUserAgent(); int nav_entry_id = active_entry->GetUniqueID(); for (FrameTreeNode* node : delegate_->GetFrameTree()->Nodes()) node->current_frame_host()->set_nav_entry_id(nav_entry_id); return true; } Commit Message: Do not use NavigationEntry to block history navigations. This is no longer necessary after r477371. BUG=777419 TEST=See bug for repro steps. Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: I701e4d4853858281b43e3743b12274dbeadfbf18 Reviewed-on: https://chromium-review.googlesource.com/733959 Reviewed-by: Devlin <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#511942} CWE ID: CWE-20
bool NavigationControllerImpl::RendererDidNavigate( RenderFrameHostImpl* rfh, const FrameHostMsg_DidCommitProvisionalLoad_Params& params, LoadCommittedDetails* details, bool is_navigation_within_page, NavigationHandleImpl* navigation_handle) { is_initial_navigation_ = false; bool overriding_user_agent_changed = false; if (GetLastCommittedEntry()) { details->previous_url = GetLastCommittedEntry()->GetURL(); details->previous_entry_index = GetLastCommittedEntryIndex(); if (pending_entry_ && pending_entry_->GetIsOverridingUserAgent() != GetLastCommittedEntry()->GetIsOverridingUserAgent()) overriding_user_agent_changed = true; } else { details->previous_url = GURL(); details->previous_entry_index = -1; } bool was_restored = false; DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() || pending_entry_->restore_type() != RestoreType::NONE); if (pending_entry_ && pending_entry_->restore_type() != RestoreType::NONE) { pending_entry_->set_restore_type(RestoreType::NONE); was_restored = true; } details->did_replace_entry = params.should_replace_current_entry; details->type = ClassifyNavigation(rfh, params); details->is_same_document = is_navigation_within_page; if (PendingEntryMatchesHandle(navigation_handle)) { if (pending_entry_->reload_type() != ReloadType::NONE) { last_committed_reload_type_ = pending_entry_->reload_type(); last_committed_reload_time_ = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); } else if (!pending_entry_->is_renderer_initiated() || params.gesture == NavigationGestureUser) { last_committed_reload_type_ = ReloadType::NONE; last_committed_reload_time_ = base::Time(); } } switch (details->type) { case NAVIGATION_TYPE_NEW_PAGE: RendererDidNavigateToNewPage(rfh, params, details->is_same_document, details->did_replace_entry, navigation_handle); break; case NAVIGATION_TYPE_EXISTING_PAGE: details->did_replace_entry = details->is_same_document; RendererDidNavigateToExistingPage(rfh, params, details->is_same_document, was_restored, navigation_handle); break; case NAVIGATION_TYPE_SAME_PAGE: RendererDidNavigateToSamePage(rfh, params, navigation_handle); break; case NAVIGATION_TYPE_NEW_SUBFRAME: RendererDidNavigateNewSubframe(rfh, params, details->is_same_document, details->did_replace_entry); break; case NAVIGATION_TYPE_AUTO_SUBFRAME: if (!RendererDidNavigateAutoSubframe(rfh, params)) { NotifyEntryChanged(GetLastCommittedEntry()); return false; } break; case NAVIGATION_TYPE_NAV_IGNORE: if (pending_entry_) { DiscardNonCommittedEntries(); delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL); } return false; default: NOTREACHED(); } base::Time timestamp = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); DVLOG(1) << "Navigation finished at (smoothed) timestamp " << timestamp.ToInternalValue(); DiscardNonCommittedEntriesInternal(); DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState."; NavigationEntryImpl* active_entry = GetLastCommittedEntry(); active_entry->SetTimestamp(timestamp); active_entry->SetHttpStatusCode(params.http_status_code); FrameNavigationEntry* frame_entry = active_entry->GetFrameEntry(rfh->frame_tree_node()); if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance()) frame_entry = nullptr; if (frame_entry) { DCHECK(params.page_state == frame_entry->page_state()); } size_t redirect_chain_size = 0; for (size_t i = 0; i < params.redirects.size(); ++i) { redirect_chain_size += params.redirects[i].spec().length(); } UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size); active_entry->ResetForCommit(frame_entry); if (!rfh->GetParent()) CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance()); active_entry->SetBindings(rfh->GetEnabledBindings()); details->entry = active_entry; details->is_main_frame = !rfh->GetParent(); details->http_status_code = params.http_status_code; NotifyNavigationEntryCommitted(details); if (active_entry->GetURL().SchemeIs(url::kHttpsScheme) && !rfh->GetParent() && navigation_handle->GetNetErrorCode() == net::OK) { UMA_HISTOGRAM_BOOLEAN("Navigation.SecureSchemeHasSSLStatus", !!active_entry->GetSSL().certificate); } if (overriding_user_agent_changed) delegate_->UpdateOverridingUserAgent(); int nav_entry_id = active_entry->GetUniqueID(); for (FrameTreeNode* node : delegate_->GetFrameTree()->Nodes()) node->current_frame_host()->set_nav_entry_id(nav_entry_id); return true; }
172,932
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *cJSON_Print( cJSON *item ) { return print_value( item, 0, 1 ); } 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
char *cJSON_Print( cJSON *item )
167,293
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void finish_object(struct object *obj, struct strbuf *path, const char *name, void *cb_data) { struct rev_list_info *info = cb_data; if (obj->type == OBJ_BLOB && !has_object_file(&obj->oid)) die("missing blob object '%s'", oid_to_hex(&obj->oid)); if (info->revs->verify_objects && !obj->parsed && obj->type != OBJ_COMMIT) parse_object(obj->oid.hash); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119
static void finish_object(struct object *obj, static void finish_object(struct object *obj, const char *name, void *cb_data) { struct rev_list_info *info = cb_data; if (obj->type == OBJ_BLOB && !has_object_file(&obj->oid)) die("missing blob object '%s'", oid_to_hex(&obj->oid)); if (info->revs->verify_objects && !obj->parsed && obj->type != OBJ_COMMIT) parse_object(obj->oid.hash); }
167,416
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_be_short (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 2) { psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_short */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_be_short (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_be_short */
170,052
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: error::Error GLES2DecoderImpl::HandleDrawElements( uint32 immediate_data_size, const gles2::DrawElements& c) { if (!bound_element_array_buffer_ || bound_element_array_buffer_->IsDeleted()) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: No element array buffer bound"); return error::kNoError; } GLenum mode = c.mode; GLsizei count = c.count; GLenum type = c.type; int32 offset = c.index_offset; if (count < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: count < 0"); return error::kNoError; } if (offset < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: offset < 0"); return error::kNoError; } if (!validators_->draw_mode.IsValid(mode)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: mode GL_INVALID_ENUM"); return error::kNoError; } if (!validators_->index_type.IsValid(type)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: type GL_INVALID_ENUM"); return error::kNoError; } if (!CheckFramebufferComplete("glDrawElements")) { return error::kNoError; } if (count == 0) { return error::kNoError; } GLuint max_vertex_accessed; if (!bound_element_array_buffer_->GetMaxValueForRange( offset, count, type, &max_vertex_accessed)) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: range out of bounds for buffer"); return error::kNoError; } if (IsDrawValid(max_vertex_accessed)) { bool simulated_attrib_0 = SimulateAttrib0(max_vertex_accessed); bool simulated_fixed_attribs = false; if (SimulateFixedAttribs(max_vertex_accessed, &simulated_fixed_attribs)) { bool textures_set = SetBlackTextureForNonRenderableTextures(); ApplyDirtyState(); const GLvoid* indices = reinterpret_cast<const GLvoid*>(offset); glDrawElements(mode, count, type, indices); if (textures_set) { RestoreStateForNonRenderableTextures(); } if (simulated_fixed_attribs) { RestoreStateForSimulatedFixedAttribs(); } } if (simulated_attrib_0) { RestoreStateForSimulatedAttrib0(); } if (WasContextLost()) { LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawElements."; return error::kLostContext; } } return error::kNoError; } Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0.""" TEST=none BUG=95625 [email protected] Review URL: http://codereview.chromium.org/7796016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
error::Error GLES2DecoderImpl::HandleDrawElements( uint32 immediate_data_size, const gles2::DrawElements& c) { if (!bound_element_array_buffer_ || bound_element_array_buffer_->IsDeleted()) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: No element array buffer bound"); return error::kNoError; } GLenum mode = c.mode; GLsizei count = c.count; GLenum type = c.type; int32 offset = c.index_offset; if (count < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: count < 0"); return error::kNoError; } if (offset < 0) { SetGLError(GL_INVALID_VALUE, "glDrawElements: offset < 0"); return error::kNoError; } if (!validators_->draw_mode.IsValid(mode)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: mode GL_INVALID_ENUM"); return error::kNoError; } if (!validators_->index_type.IsValid(type)) { SetGLError(GL_INVALID_ENUM, "glDrawElements: type GL_INVALID_ENUM"); return error::kNoError; } if (!CheckFramebufferComplete("glDrawElements")) { return error::kNoError; } if (count == 0) { return error::kNoError; } GLuint max_vertex_accessed; if (!bound_element_array_buffer_->GetMaxValueForRange( offset, count, type, &max_vertex_accessed)) { SetGLError(GL_INVALID_OPERATION, "glDrawElements: range out of bounds for buffer"); return error::kNoError; } if (IsDrawValid(max_vertex_accessed)) { bool simulated_attrib_0 = false; if (!SimulateAttrib0(max_vertex_accessed, &simulated_attrib_0)) { return error::kNoError; } bool simulated_fixed_attribs = false; if (SimulateFixedAttribs(max_vertex_accessed, &simulated_fixed_attribs)) { bool textures_set = SetBlackTextureForNonRenderableTextures(); ApplyDirtyState(); const GLvoid* indices = reinterpret_cast<const GLvoid*>(offset); glDrawElements(mode, count, type, indices); if (textures_set) { RestoreStateForNonRenderableTextures(); } if (simulated_fixed_attribs) { RestoreStateForSimulatedFixedAttribs(); } } if (simulated_attrib_0) { RestoreStateForSimulatedAttrib0(); } if (WasContextLost()) { LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawElements."; return error::kLostContext; } } return error::kNoError; }
170,331
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int btsock_thread_wakeup(int h) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("thread handle:%d, cmd socket is not created", h); return FALSE; } sock_cmd_t cmd = {CMD_WAKEUP, 0, 0, 0, 0}; return send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
int btsock_thread_wakeup(int h) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("thread handle:%d, cmd socket is not created", h); return FALSE; } sock_cmd_t cmd = {CMD_WAKEUP, 0, 0, 0, 0}; return TEMP_FAILURE_RETRY(send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0)) == sizeof(cmd); }
173,464
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, buildFromDirectory) { char *dir, *error, *regex = NULL; int dir_len, regex_len = 0; zend_bool apply_reg = 0; zval arg, arg2, *iter, *iteriter, *regexiter = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write to archive - write operations restricted by INI setting"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, &regex, &regex_len) == FAILURE) { RETURN_FALSE; } MAKE_STD_ZVAL(iter); if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) { zval_ptr_dtor(&iter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg); ZVAL_STRINGL(&arg, dir, dir_len, 0); INIT_PZVAL(&arg2); #if PHP_VERSION_ID < 50300 ZVAL_LONG(&arg2, 0); #else ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS); #endif zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator, &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2); if (EG(exception)) { zval_ptr_dtor(&iter); RETURN_FALSE; } MAKE_STD_ZVAL(iteriter); if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator, &spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter); if (EG(exception)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); RETURN_FALSE; } zval_ptr_dtor(&iter); if (regex_len > 0) { apply_reg = 1; MAKE_STD_ZVAL(regexiter); if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) { zval_ptr_dtor(&iteriter); zval_dtor(regexiter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg2); ZVAL_STRINGL(&arg2, regex, regex_len, 0); zend_call_method_with_2_params(&regexiter, spl_ce_RegexIterator, &spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2); } array_init(return_value); pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter); pass.p = phar_obj; pass.b = dir; pass.l = dir_len; pass.count = 0; pass.ret = return_value; pass.fp = php_stream_fopen_tmpfile(); if (pass.fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname); return; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } else { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); } } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, buildFromDirectory) { char *dir, *error, *regex = NULL; int dir_len, regex_len = 0; zend_bool apply_reg = 0; zval arg, arg2, *iter, *iteriter, *regexiter = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write to archive - write operations restricted by INI setting"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, &regex, &regex_len) == FAILURE) { RETURN_FALSE; } MAKE_STD_ZVAL(iter); if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) { zval_ptr_dtor(&iter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg); ZVAL_STRINGL(&arg, dir, dir_len, 0); INIT_PZVAL(&arg2); #if PHP_VERSION_ID < 50300 ZVAL_LONG(&arg2, 0); #else ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS); #endif zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator, &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2); if (EG(exception)) { zval_ptr_dtor(&iter); RETURN_FALSE; } MAKE_STD_ZVAL(iteriter); if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator, &spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter); if (EG(exception)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); RETURN_FALSE; } zval_ptr_dtor(&iter); if (regex_len > 0) { apply_reg = 1; MAKE_STD_ZVAL(regexiter); if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) { zval_ptr_dtor(&iteriter); zval_dtor(regexiter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg2); ZVAL_STRINGL(&arg2, regex, regex_len, 0); zend_call_method_with_2_params(&regexiter, spl_ce_RegexIterator, &spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2); } array_init(return_value); pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter); pass.p = phar_obj; pass.b = dir; pass.l = dir_len; pass.count = 0; pass.ret = return_value; pass.fp = php_stream_fopen_tmpfile(); if (pass.fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname); return; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } else { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); } }
165,294
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { return gss_verify_mic_iov(minor_status, context_handle, qop_state, iov, iov_count); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); return gss_verify_mic_iov(minor_status, sc->ctx_handle, qop_state, iov, iov_count); }
166,670
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; struct xfrm_dump_info info; BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) > sizeof(cb->args) - sizeof(cb->args[0])); info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; if (!cb->args[0]) { cb->args[0] = 1; xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY); } (void) xfrm_policy_walk(net, walk, dump_one_policy, &info); return skb->len; } Commit Message: ipsec: Fix aborted xfrm policy dump crash An independent security researcher, Mohamed Ghannam, has reported this vulnerability to Beyond Security's SecuriTeam Secure Disclosure program. The xfrm_dump_policy_done function expects xfrm_dump_policy to have been called at least once or it will crash. This can be triggered if a dump fails because the target socket's receive buffer is full. This patch fixes it by using the cb->start mechanism to ensure that the initialisation is always done regardless of the buffer situation. Fixes: 12a169e7d8f4 ("ipsec: Put dumpers on the dump list") Signed-off-by: Herbert Xu <[email protected]> Signed-off-by: Steffen Klassert <[email protected]> CWE ID: CWE-416
static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args; struct xfrm_dump_info info; info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; (void) xfrm_policy_walk(net, walk, dump_one_policy, &info); return skb->len; }
167,662
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); env->insn_aux_data = new_data; vfree(old_data); return 0; } Commit Message: bpf: fix branch pruning logic when the verifier detects that register contains a runtime constant and it's compared with another constant it will prune exploration of the branch that is guaranteed not to be taken at runtime. This is all correct, but malicious program may be constructed in such a way that it always has a constant comparison and the other branch is never taken under any conditions. In this case such path through the program will not be explored by the verifier. It won't be taken at run-time either, but since all instructions are JITed the malicious program may cause JITs to complain about using reserved fields, etc. To fix the issue we have to track the instructions explored by the verifier and sanitize instructions that are dead at run time with NOPs. We cannot reject such dead code, since llvm generates it for valid C code, since it doesn't do as much data flow analysis as the verifier does. Fixes: 17a5267067f3 ("bpf: verifier (add verifier core)") Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-20
static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; int i; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); for (i = off; i < off + cnt - 1; i++) new_data[i].seen = true; env->insn_aux_data = new_data; vfree(old_data); return 0; }
167,637
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string TemplateURLRef::HandleReplacements( const SearchTermsArgs& search_terms_args, const SearchTermsData& search_terms_data, PostContent* post_content) const { if (replacements_.empty()) { if (!post_params_.empty()) EncodeFormData(post_params_, post_content); return parsed_url_; } bool is_in_query = true; for (Replacements::iterator i = replacements_.begin(); i != replacements_.end(); ++i) { if (i->type == SEARCH_TERMS) { base::string16::size_type query_start = parsed_url_.find('?'); is_in_query = query_start != base::string16::npos && (static_cast<base::string16::size_type>(i->index) > query_start); break; } } std::string input_encoding; base::string16 encoded_terms; base::string16 encoded_original_query; owner_->EncodeSearchTerms(search_terms_args, is_in_query, &input_encoding, &encoded_terms, &encoded_original_query); std::string url = parsed_url_; for (Replacements::reverse_iterator i = replacements_.rbegin(); i != replacements_.rend(); ++i) { switch (i->type) { case ENCODING: HandleReplacement(std::string(), input_encoding, *i, &url); break; case GOOGLE_ASSISTED_QUERY_STATS: DCHECK(!i->is_post_param); if (!search_terms_args.assisted_query_stats.empty()) { SearchTermsArgs search_terms_args_without_aqs(search_terms_args); search_terms_args_without_aqs.assisted_query_stats.clear(); GURL base_url(ReplaceSearchTerms( search_terms_args_without_aqs, search_terms_data, NULL)); if (base_url.SchemeIsCryptographic()) { HandleReplacement( "aqs", search_terms_args.assisted_query_stats, *i, &url); } } break; case GOOGLE_BASE_URL: DCHECK(!i->is_post_param); HandleReplacement( std::string(), search_terms_data.GoogleBaseURLValue(), *i, &url); break; case GOOGLE_BASE_SUGGEST_URL: DCHECK(!i->is_post_param); HandleReplacement( std::string(), search_terms_data.GoogleBaseSuggestURLValue(), *i, &url); break; case GOOGLE_CURRENT_PAGE_URL: DCHECK(!i->is_post_param); if (!search_terms_args.current_page_url.empty()) { const std::string& escaped_current_page_url = net::EscapeQueryParamValue(search_terms_args.current_page_url, true); HandleReplacement("url", escaped_current_page_url, *i, &url); } break; case GOOGLE_CURSOR_POSITION: DCHECK(!i->is_post_param); if (search_terms_args.cursor_position != base::string16::npos) HandleReplacement( "cp", base::StringPrintf("%" PRIuS, search_terms_args.cursor_position), *i, &url); break; case GOOGLE_FORCE_INSTANT_RESULTS: DCHECK(!i->is_post_param); HandleReplacement(std::string(), search_terms_data.ForceInstantResultsParam( search_terms_args.force_instant_results), *i, &url); break; case GOOGLE_INPUT_TYPE: DCHECK(!i->is_post_param); HandleReplacement( "oit", base::IntToString(search_terms_args.input_type), *i, &url); break; case GOOGLE_INSTANT_EXTENDED_ENABLED: DCHECK(!i->is_post_param); HandleReplacement(std::string(), search_terms_data.InstantExtendedEnabledParam( type_ == SEARCH), *i, &url); break; case GOOGLE_CONTEXTUAL_SEARCH_VERSION: if (search_terms_args.contextual_search_params.version >= 0) { HandleReplacement( "ctxs", base::IntToString( search_terms_args.contextual_search_params.version), *i, &url); } break; case GOOGLE_CONTEXTUAL_SEARCH_CONTEXT_DATA: { DCHECK(!i->is_post_param); std::string context_data; const SearchTermsArgs::ContextualSearchParams& params = search_terms_args.contextual_search_params; if (params.start != std::string::npos) { context_data.append("ctxs_start=" + base::SizeTToString(params.start) + "&"); } if (params.end != std::string::npos) { context_data.append("ctxs_end=" + base::SizeTToString(params.end) + "&"); } if (!params.selection.empty()) context_data.append("q=" + params.selection + "&"); if (!params.content.empty()) context_data.append("ctxs_content=" + params.content + "&"); if (!params.base_page_url.empty()) context_data.append("ctxsl_url=" + params.base_page_url + "&"); if (!params.encoding.empty()) { context_data.append("ctxs_encoding=" + params.encoding + "&"); } context_data.append("ctxsl_coca=" + base::IntToString(params.now_on_tap_version)); HandleReplacement(std::string(), context_data, *i, &url); break; } case GOOGLE_ORIGINAL_QUERY_FOR_SUGGESTION: DCHECK(!i->is_post_param); if (search_terms_args.accepted_suggestion >= 0 || !search_terms_args.assisted_query_stats.empty()) { HandleReplacement( "oq", base::UTF16ToUTF8(encoded_original_query), *i, &url); } break; case GOOGLE_PAGE_CLASSIFICATION: if (search_terms_args.page_classification != metrics::OmniboxEventProto::INVALID_SPEC) { HandleReplacement( "pgcl", base::IntToString(search_terms_args.page_classification), *i, &url); } break; case GOOGLE_PREFETCH_QUERY: { const std::string& query = search_terms_args.prefetch_query; const std::string& type = search_terms_args.prefetch_query_type; if (!query.empty() && !type.empty()) { HandleReplacement( std::string(), "pfq=" + query + "&qha=" + type + "&", *i, &url); } break; } case GOOGLE_RLZ: { DCHECK(!i->is_post_param); base::string16 rlz_string = search_terms_data.GetRlzParameterValue( search_terms_args.from_app_list); if (!rlz_string.empty()) { HandleReplacement("rlz", base::UTF16ToUTF8(rlz_string), *i, &url); } break; } case GOOGLE_SEARCH_CLIENT: { DCHECK(!i->is_post_param); std::string client = search_terms_data.GetSearchClient(); if (!client.empty()) HandleReplacement("client", client, *i, &url); break; } case GOOGLE_SEARCH_FIELDTRIAL_GROUP: break; case GOOGLE_SEARCH_VERSION: HandleReplacement("gs_rn", "42", *i, &url); break; case GOOGLE_SESSION_TOKEN: { std::string token = search_terms_args.session_token; if (!token.empty()) HandleReplacement("psi", token, *i, &url); break; } case GOOGLE_SUGGEST_CLIENT: HandleReplacement( std::string(), search_terms_data.GetSuggestClient(), *i, &url); break; case GOOGLE_SUGGEST_REQUEST_ID: HandleReplacement( std::string(), search_terms_data.GetSuggestRequestIdentifier(), *i, &url); break; case GOOGLE_UNESCAPED_SEARCH_TERMS: { std::string unescaped_terms; base::UTF16ToCodepage(search_terms_args.search_terms, input_encoding.c_str(), base::OnStringConversionError::SKIP, &unescaped_terms); HandleReplacement(std::string(), unescaped_terms, *i, &url); break; } case LANGUAGE: HandleReplacement( std::string(), search_terms_data.GetApplicationLocale(), *i, &url); break; case SEARCH_TERMS: HandleReplacement( std::string(), base::UTF16ToUTF8(encoded_terms), *i, &url); break; case GOOGLE_IMAGE_THUMBNAIL: HandleReplacement( std::string(), search_terms_args.image_thumbnail_content, *i, &url); post_params_[i->index].content_type = "image/jpeg"; break; case GOOGLE_IMAGE_URL: if (search_terms_args.image_url.is_valid()) { HandleReplacement( std::string(), search_terms_args.image_url.spec(), *i, &url); } break; case GOOGLE_IMAGE_ORIGINAL_WIDTH: if (!search_terms_args.image_original_size.IsEmpty()) { HandleReplacement( std::string(), base::IntToString(search_terms_args.image_original_size.width()), *i, &url); } break; case GOOGLE_IMAGE_ORIGINAL_HEIGHT: if (!search_terms_args.image_original_size.IsEmpty()) { HandleReplacement( std::string(), base::IntToString(search_terms_args.image_original_size.height()), *i, &url); } break; case GOOGLE_IMAGE_SEARCH_SOURCE: HandleReplacement( std::string(), search_terms_data.GoogleImageSearchSource(), *i, &url); break; case GOOGLE_IOS_SEARCH_LANGUAGE: #if defined(OS_IOS) HandleReplacement("hl", search_terms_data.GetApplicationLocale(), *i, &url); #endif break; default: NOTREACHED(); break; } } if (!post_params_.empty()) EncodeFormData(post_params_, post_content); return url; } Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899} CWE ID:
std::string TemplateURLRef::HandleReplacements( const SearchTermsArgs& search_terms_args, const SearchTermsData& search_terms_data, PostContent* post_content) const { if (replacements_.empty()) { if (!post_params_.empty()) EncodeFormData(post_params_, post_content); return parsed_url_; } bool is_in_query = true; for (Replacements::iterator i = replacements_.begin(); i != replacements_.end(); ++i) { if (i->type == SEARCH_TERMS) { base::string16::size_type query_start = parsed_url_.find('?'); is_in_query = query_start != base::string16::npos && (static_cast<base::string16::size_type>(i->index) > query_start); break; } } std::string input_encoding; base::string16 encoded_terms; base::string16 encoded_original_query; owner_->EncodeSearchTerms(search_terms_args, is_in_query, &input_encoding, &encoded_terms, &encoded_original_query); std::string url = parsed_url_; for (Replacements::reverse_iterator i = replacements_.rbegin(); i != replacements_.rend(); ++i) { switch (i->type) { case ENCODING: HandleReplacement(std::string(), input_encoding, *i, &url); break; case GOOGLE_ASSISTED_QUERY_STATS: DCHECK(!i->is_post_param); if (!search_terms_args.assisted_query_stats.empty()) { SearchTermsArgs search_terms_args_without_aqs(search_terms_args); search_terms_args_without_aqs.assisted_query_stats.clear(); GURL base_url(ReplaceSearchTerms( search_terms_args_without_aqs, search_terms_data, NULL)); if (base_url.SchemeIsCryptographic()) { HandleReplacement( "aqs", search_terms_args.assisted_query_stats, *i, &url); } } break; case GOOGLE_BASE_URL: DCHECK(!i->is_post_param); HandleReplacement( std::string(), search_terms_data.GoogleBaseURLValue(), *i, &url); break; case GOOGLE_BASE_SUGGEST_URL: DCHECK(!i->is_post_param); HandleReplacement( std::string(), search_terms_data.GoogleBaseSuggestURLValue(), *i, &url); break; case GOOGLE_CURRENT_PAGE_URL: DCHECK(!i->is_post_param); if (!search_terms_args.current_page_url.empty()) { const std::string& escaped_current_page_url = net::EscapeQueryParamValue(search_terms_args.current_page_url, true); HandleReplacement("url", escaped_current_page_url, *i, &url); } break; case GOOGLE_CURSOR_POSITION: DCHECK(!i->is_post_param); if (search_terms_args.cursor_position != base::string16::npos) HandleReplacement( "cp", base::StringPrintf("%" PRIuS, search_terms_args.cursor_position), *i, &url); break; case GOOGLE_FORCE_INSTANT_RESULTS: DCHECK(!i->is_post_param); HandleReplacement(std::string(), search_terms_data.ForceInstantResultsParam( search_terms_args.force_instant_results), *i, &url); break; case GOOGLE_INPUT_TYPE: DCHECK(!i->is_post_param); HandleReplacement( "oit", base::IntToString(search_terms_args.input_type), *i, &url); break; case GOOGLE_INSTANT_EXTENDED_ENABLED: DCHECK(!i->is_post_param); HandleReplacement(std::string(), search_terms_data.InstantExtendedEnabledParam( type_ == SEARCH), *i, &url); break; case GOOGLE_CONTEXTUAL_SEARCH_VERSION: if (search_terms_args.contextual_search_params.version >= 0) { HandleReplacement( "ctxs", base::IntToString( search_terms_args.contextual_search_params.version), *i, &url); } break; case GOOGLE_CONTEXTUAL_SEARCH_CONTEXT_DATA: { DCHECK(!i->is_post_param); std::string context_data; const SearchTermsArgs::ContextualSearchParams& params = search_terms_args.contextual_search_params; if (params.start != std::string::npos) { context_data.append("ctxs_start=" + base::SizeTToString(params.start) + "&"); } if (params.end != std::string::npos) { context_data.append("ctxs_end=" + base::SizeTToString(params.end) + "&"); } if (!params.selection.empty()) context_data.append("q=" + params.selection + "&"); if (!params.content.empty()) context_data.append("ctxs_content=" + params.content + "&"); if (!params.base_page_url.empty()) context_data.append("ctxsl_url=" + params.base_page_url + "&"); if (!params.encoding.empty()) { context_data.append("ctxs_encoding=" + params.encoding + "&"); } context_data.append("ctxsl_coca=" + base::IntToString( params.contextual_cards_version)); HandleReplacement(std::string(), context_data, *i, &url); break; } case GOOGLE_ORIGINAL_QUERY_FOR_SUGGESTION: DCHECK(!i->is_post_param); if (search_terms_args.accepted_suggestion >= 0 || !search_terms_args.assisted_query_stats.empty()) { HandleReplacement( "oq", base::UTF16ToUTF8(encoded_original_query), *i, &url); } break; case GOOGLE_PAGE_CLASSIFICATION: if (search_terms_args.page_classification != metrics::OmniboxEventProto::INVALID_SPEC) { HandleReplacement( "pgcl", base::IntToString(search_terms_args.page_classification), *i, &url); } break; case GOOGLE_PREFETCH_QUERY: { const std::string& query = search_terms_args.prefetch_query; const std::string& type = search_terms_args.prefetch_query_type; if (!query.empty() && !type.empty()) { HandleReplacement( std::string(), "pfq=" + query + "&qha=" + type + "&", *i, &url); } break; } case GOOGLE_RLZ: { DCHECK(!i->is_post_param); base::string16 rlz_string = search_terms_data.GetRlzParameterValue( search_terms_args.from_app_list); if (!rlz_string.empty()) { HandleReplacement("rlz", base::UTF16ToUTF8(rlz_string), *i, &url); } break; } case GOOGLE_SEARCH_CLIENT: { DCHECK(!i->is_post_param); std::string client = search_terms_data.GetSearchClient(); if (!client.empty()) HandleReplacement("client", client, *i, &url); break; } case GOOGLE_SEARCH_FIELDTRIAL_GROUP: break; case GOOGLE_SEARCH_VERSION: HandleReplacement("gs_rn", "42", *i, &url); break; case GOOGLE_SESSION_TOKEN: { std::string token = search_terms_args.session_token; if (!token.empty()) HandleReplacement("psi", token, *i, &url); break; } case GOOGLE_SUGGEST_CLIENT: HandleReplacement( std::string(), search_terms_data.GetSuggestClient(), *i, &url); break; case GOOGLE_SUGGEST_REQUEST_ID: HandleReplacement( std::string(), search_terms_data.GetSuggestRequestIdentifier(), *i, &url); break; case GOOGLE_UNESCAPED_SEARCH_TERMS: { std::string unescaped_terms; base::UTF16ToCodepage(search_terms_args.search_terms, input_encoding.c_str(), base::OnStringConversionError::SKIP, &unescaped_terms); HandleReplacement(std::string(), unescaped_terms, *i, &url); break; } case LANGUAGE: HandleReplacement( std::string(), search_terms_data.GetApplicationLocale(), *i, &url); break; case SEARCH_TERMS: HandleReplacement( std::string(), base::UTF16ToUTF8(encoded_terms), *i, &url); break; case GOOGLE_IMAGE_THUMBNAIL: HandleReplacement( std::string(), search_terms_args.image_thumbnail_content, *i, &url); post_params_[i->index].content_type = "image/jpeg"; break; case GOOGLE_IMAGE_URL: if (search_terms_args.image_url.is_valid()) { HandleReplacement( std::string(), search_terms_args.image_url.spec(), *i, &url); } break; case GOOGLE_IMAGE_ORIGINAL_WIDTH: if (!search_terms_args.image_original_size.IsEmpty()) { HandleReplacement( std::string(), base::IntToString(search_terms_args.image_original_size.width()), *i, &url); } break; case GOOGLE_IMAGE_ORIGINAL_HEIGHT: if (!search_terms_args.image_original_size.IsEmpty()) { HandleReplacement( std::string(), base::IntToString(search_terms_args.image_original_size.height()), *i, &url); } break; case GOOGLE_IMAGE_SEARCH_SOURCE: HandleReplacement( std::string(), search_terms_data.GoogleImageSearchSource(), *i, &url); break; case GOOGLE_IOS_SEARCH_LANGUAGE: #if defined(OS_IOS) HandleReplacement("hl", search_terms_data.GetApplicationLocale(), *i, &url); #endif break; default: NOTREACHED(); break; } } if (!post_params_.empty()) EncodeFormData(post_params_, post_content); return url; }
171,648
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_vdec::set_config(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE configIndex, OMX_IN OMX_PTR configData) { (void) hComp; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Get Config in Invalid State"); return OMX_ErrorInvalidState; } OMX_ERRORTYPE ret = OMX_ErrorNone; OMX_VIDEO_CONFIG_NALSIZE *pNal; DEBUG_PRINT_LOW("Set Config Called"); if (configIndex == (OMX_INDEXTYPE)OMX_IndexVendorVideoExtraData) { OMX_VENDOR_EXTRADATATYPE *config = (OMX_VENDOR_EXTRADATATYPE *) configData; DEBUG_PRINT_LOW("Index OMX_IndexVendorVideoExtraData called"); if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.avc") || !strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mvc")) { DEBUG_PRINT_LOW("Index OMX_IndexVendorVideoExtraData AVC"); OMX_U32 extra_size; nal_length = (config->pData[4] & 0x03) + 1; extra_size = 0; if (nal_length > 2) { /* Presently we assume that only one SPS and one PPS in AvC1 Atom */ extra_size = (nal_length - 2) * 2; } OMX_U8 *pSrcBuf = (OMX_U8 *) (&config->pData[6]); OMX_U8 *pDestBuf; m_vendor_config.nPortIndex = config->nPortIndex; m_vendor_config.nDataSize = config->nDataSize - 6 - 1 + extra_size; m_vendor_config.pData = (OMX_U8 *) malloc(m_vendor_config.nDataSize); OMX_U32 len; OMX_U8 index = 0; pDestBuf = m_vendor_config.pData; DEBUG_PRINT_LOW("Rxd SPS+PPS nPortIndex[%u] len[%u] data[%p]", (unsigned int)m_vendor_config.nPortIndex, (unsigned int)m_vendor_config.nDataSize, m_vendor_config.pData); while (index < 2) { uint8 *psize; len = *pSrcBuf; len = len << 8; len |= *(pSrcBuf + 1); psize = (uint8 *) & len; memcpy(pDestBuf + nal_length, pSrcBuf + 2,len); for (unsigned int i = 0; i < nal_length; i++) { pDestBuf[i] = psize[nal_length - 1 - i]; } pDestBuf += len + nal_length; pSrcBuf += len + 2; index++; pSrcBuf++; // skip picture param set len = 0; } } else if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg4") || !strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg2")) { m_vendor_config.nPortIndex = config->nPortIndex; m_vendor_config.nDataSize = config->nDataSize; m_vendor_config.pData = (OMX_U8 *) malloc((config->nDataSize)); memcpy(m_vendor_config.pData, config->pData,config->nDataSize); } else if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.vc1")) { if (m_vendor_config.pData) { free(m_vendor_config.pData); m_vendor_config.pData = NULL; m_vendor_config.nDataSize = 0; } if (((*((OMX_U32 *) config->pData)) & VC1_SP_MP_START_CODE_MASK) == VC1_SP_MP_START_CODE) { DEBUG_PRINT_LOW("set_config - VC1 simple/main profile"); m_vendor_config.nPortIndex = config->nPortIndex; m_vendor_config.nDataSize = config->nDataSize; m_vendor_config.pData = (OMX_U8 *) malloc(config->nDataSize); memcpy(m_vendor_config.pData, config->pData, config->nDataSize); m_vc1_profile = VC1_SP_MP_RCV; } else if (*((OMX_U32 *) config->pData) == VC1_AP_SEQ_START_CODE) { DEBUG_PRINT_LOW("set_config - VC1 Advance profile"); m_vendor_config.nPortIndex = config->nPortIndex; m_vendor_config.nDataSize = config->nDataSize; m_vendor_config.pData = (OMX_U8 *) malloc((config->nDataSize)); memcpy(m_vendor_config.pData, config->pData, config->nDataSize); m_vc1_profile = VC1_AP; } else if ((config->nDataSize == VC1_STRUCT_C_LEN)) { DEBUG_PRINT_LOW("set_config - VC1 Simple/Main profile struct C only"); m_vendor_config.nPortIndex = config->nPortIndex; m_vendor_config.nDataSize = config->nDataSize; m_vendor_config.pData = (OMX_U8*)malloc(config->nDataSize); memcpy(m_vendor_config.pData,config->pData,config->nDataSize); m_vc1_profile = VC1_SP_MP_RCV; } else { DEBUG_PRINT_LOW("set_config - Error: Unknown VC1 profile"); } } return ret; } else if (configIndex == OMX_IndexConfigVideoNalSize) { struct v4l2_control temp; temp.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT; VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_NALSIZE); pNal = reinterpret_cast < OMX_VIDEO_CONFIG_NALSIZE * >(configData); switch (pNal->nNaluBytes) { case 0: temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_STARTCODES; break; case 2: temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_TWO_BYTE_LENGTH; break; case 4: temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_FOUR_BYTE_LENGTH; break; default: return OMX_ErrorUnsupportedSetting; } if (!arbitrary_bytes) { /* In arbitrary bytes mode, the assembler strips out nal size and replaces * with start code, so only need to notify driver in frame by frame mode */ if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &temp)) { DEBUG_PRINT_ERROR("Failed to set V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT"); return OMX_ErrorHardware; } } nal_length = pNal->nNaluBytes; m_frame_parser.init_nal_length(nal_length); DEBUG_PRINT_LOW("OMX_IndexConfigVideoNalSize called with Size %d", nal_length); return ret; } else if ((int)configIndex == (int)OMX_IndexVendorVideoFrameRate) { OMX_VENDOR_VIDEOFRAMERATE *config = (OMX_VENDOR_VIDEOFRAMERATE *) configData; DEBUG_PRINT_HIGH("Index OMX_IndexVendorVideoFrameRate %u", (unsigned int)config->nFps); if (config->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) { if (config->bEnabled) { if ((config->nFps >> 16) > 0) { DEBUG_PRINT_HIGH("set_config: frame rate set by omx client : %u", (unsigned int)config->nFps >> 16); Q16ToFraction(config->nFps, drv_ctx.frame_rate.fps_numerator, drv_ctx.frame_rate.fps_denominator); if (!drv_ctx.frame_rate.fps_numerator) { DEBUG_PRINT_ERROR("Numerator is zero setting to 30"); drv_ctx.frame_rate.fps_numerator = 30; } if (drv_ctx.frame_rate.fps_denominator) { drv_ctx.frame_rate.fps_numerator = (int) drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator; } drv_ctx.frame_rate.fps_denominator = 1; frm_int = drv_ctx.frame_rate.fps_denominator * 1e6 / drv_ctx.frame_rate.fps_numerator; struct v4l2_outputparm oparm; /*XXX: we're providing timing info as seconds per frame rather than frames * per second.*/ oparm.timeperframe.numerator = drv_ctx.frame_rate.fps_denominator; oparm.timeperframe.denominator = drv_ctx.frame_rate.fps_numerator; struct v4l2_streamparm sparm; sparm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; sparm.parm.output = oparm; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_PARM, &sparm)) { DEBUG_PRINT_ERROR("Unable to convey fps info to driver, \ performance might be affected"); ret = OMX_ErrorHardware; } client_set_fps = true; } else { DEBUG_PRINT_ERROR("Frame rate not supported."); ret = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_HIGH("set_config: Disabled client's frame rate"); client_set_fps = false; } } else { DEBUG_PRINT_ERROR(" Set_config: Bad Port idx %d", (int)config->nPortIndex); ret = OMX_ErrorBadPortIndex; } return ret; } else if ((int)configIndex == (int)OMX_QcomIndexConfigPerfLevel) { OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf = (OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData; struct v4l2_control control; DEBUG_PRINT_LOW("Set perf level: %d", perf->ePerfLevel); control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL; switch (perf->ePerfLevel) { case OMX_QCOM_PerfLevelNominal: control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL; break; case OMX_QCOM_PerfLevelTurbo: control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO; break; default: ret = OMX_ErrorUnsupportedSetting; break; } if (ret == OMX_ErrorNone) { ret = (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control) < 0) ? OMX_ErrorUnsupportedSetting : OMX_ErrorNone; } return ret; } else if ((int)configIndex == (int)OMX_IndexConfigPriority) { OMX_PARAM_U32TYPE *priority = (OMX_PARAM_U32TYPE *)configData; DEBUG_PRINT_LOW("Set_config: priority %d", priority->nU32); struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY; if (priority->nU32 == 0) control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_ENABLE; else control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) { DEBUG_PRINT_ERROR("Failed to set Priority"); ret = OMX_ErrorUnsupportedSetting; } return ret; } else if ((int)configIndex == (int)OMX_IndexConfigOperatingRate) { OMX_PARAM_U32TYPE *rate = (OMX_PARAM_U32TYPE *)configData; DEBUG_PRINT_LOW("Set_config: operating-rate %u fps", rate->nU32 >> 16); struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_OPERATING_RATE; control.value = rate->nU32; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) { ret = errno == -EBUSY ? OMX_ErrorInsufficientResources : OMX_ErrorUnsupportedSetting; DEBUG_PRINT_ERROR("Failed to set operating rate %u fps (%s)", rate->nU32 >> 16, errno == -EBUSY ? "HW Overload" : strerror(errno)); } return ret; } return OMX_ErrorNotImplemented; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: deprecate unused config OMX_IndexVendorVideoExtraData This config (used to set header offline) is no longer used. Remove handling this config since it uses non-process-safe ways to pass memory pointers. Fixes: Security Vulnerability - Segfault in MediaServer (libOmxVdec problem #2) Bug: 27475409 Change-Id: I7a535a3da485cbe83cf4605a05f9faf70dcca42f CWE ID: CWE-20
OMX_ERRORTYPE omx_vdec::set_config(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE configIndex, OMX_IN OMX_PTR configData) { (void) hComp; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Get Config in Invalid State"); return OMX_ErrorInvalidState; } OMX_ERRORTYPE ret = OMX_ErrorNone; OMX_VIDEO_CONFIG_NALSIZE *pNal; DEBUG_PRINT_LOW("Set Config Called"); if (configIndex == OMX_IndexConfigVideoNalSize) { struct v4l2_control temp; temp.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT; VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_NALSIZE); pNal = reinterpret_cast < OMX_VIDEO_CONFIG_NALSIZE * >(configData); switch (pNal->nNaluBytes) { case 0: temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_STARTCODES; break; case 2: temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_TWO_BYTE_LENGTH; break; case 4: temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_FOUR_BYTE_LENGTH; break; default: return OMX_ErrorUnsupportedSetting; } if (!arbitrary_bytes) { /* In arbitrary bytes mode, the assembler strips out nal size and replaces * with start code, so only need to notify driver in frame by frame mode */ if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &temp)) { DEBUG_PRINT_ERROR("Failed to set V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT"); return OMX_ErrorHardware; } } nal_length = pNal->nNaluBytes; m_frame_parser.init_nal_length(nal_length); DEBUG_PRINT_LOW("OMX_IndexConfigVideoNalSize called with Size %d", nal_length); return ret; } else if ((int)configIndex == (int)OMX_IndexVendorVideoFrameRate) { OMX_VENDOR_VIDEOFRAMERATE *config = (OMX_VENDOR_VIDEOFRAMERATE *) configData; DEBUG_PRINT_HIGH("Index OMX_IndexVendorVideoFrameRate %u", (unsigned int)config->nFps); if (config->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) { if (config->bEnabled) { if ((config->nFps >> 16) > 0) { DEBUG_PRINT_HIGH("set_config: frame rate set by omx client : %u", (unsigned int)config->nFps >> 16); Q16ToFraction(config->nFps, drv_ctx.frame_rate.fps_numerator, drv_ctx.frame_rate.fps_denominator); if (!drv_ctx.frame_rate.fps_numerator) { DEBUG_PRINT_ERROR("Numerator is zero setting to 30"); drv_ctx.frame_rate.fps_numerator = 30; } if (drv_ctx.frame_rate.fps_denominator) { drv_ctx.frame_rate.fps_numerator = (int) drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator; } drv_ctx.frame_rate.fps_denominator = 1; frm_int = drv_ctx.frame_rate.fps_denominator * 1e6 / drv_ctx.frame_rate.fps_numerator; struct v4l2_outputparm oparm; /*XXX: we're providing timing info as seconds per frame rather than frames * per second.*/ oparm.timeperframe.numerator = drv_ctx.frame_rate.fps_denominator; oparm.timeperframe.denominator = drv_ctx.frame_rate.fps_numerator; struct v4l2_streamparm sparm; sparm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; sparm.parm.output = oparm; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_PARM, &sparm)) { DEBUG_PRINT_ERROR("Unable to convey fps info to driver, \ performance might be affected"); ret = OMX_ErrorHardware; } client_set_fps = true; } else { DEBUG_PRINT_ERROR("Frame rate not supported."); ret = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_HIGH("set_config: Disabled client's frame rate"); client_set_fps = false; } } else { DEBUG_PRINT_ERROR(" Set_config: Bad Port idx %d", (int)config->nPortIndex); ret = OMX_ErrorBadPortIndex; } return ret; } else if ((int)configIndex == (int)OMX_QcomIndexConfigPerfLevel) { OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf = (OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData; struct v4l2_control control; DEBUG_PRINT_LOW("Set perf level: %d", perf->ePerfLevel); control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL; switch (perf->ePerfLevel) { case OMX_QCOM_PerfLevelNominal: control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL; break; case OMX_QCOM_PerfLevelTurbo: control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO; break; default: ret = OMX_ErrorUnsupportedSetting; break; } if (ret == OMX_ErrorNone) { ret = (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control) < 0) ? OMX_ErrorUnsupportedSetting : OMX_ErrorNone; } return ret; } else if ((int)configIndex == (int)OMX_IndexConfigPriority) { OMX_PARAM_U32TYPE *priority = (OMX_PARAM_U32TYPE *)configData; DEBUG_PRINT_LOW("Set_config: priority %d", priority->nU32); struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY; if (priority->nU32 == 0) control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_ENABLE; else control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) { DEBUG_PRINT_ERROR("Failed to set Priority"); ret = OMX_ErrorUnsupportedSetting; } return ret; } else if ((int)configIndex == (int)OMX_IndexConfigOperatingRate) { OMX_PARAM_U32TYPE *rate = (OMX_PARAM_U32TYPE *)configData; DEBUG_PRINT_LOW("Set_config: operating-rate %u fps", rate->nU32 >> 16); struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_OPERATING_RATE; control.value = rate->nU32; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) { ret = errno == -EBUSY ? OMX_ErrorInsufficientResources : OMX_ErrorUnsupportedSetting; DEBUG_PRINT_ERROR("Failed to set operating rate %u fps (%s)", rate->nU32 >> 16, errno == -EBUSY ? "HW Overload" : strerror(errno)); } return ret; } return OMX_ErrorNotImplemented; }
173,797
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void show_object(struct object *obj, struct strbuf *path, const char *component, void *cb_data) { struct rev_list_info *info = cb_data; finish_object(obj, path, component, cb_data); if (info->flags & REV_LIST_QUIET) return; show_object_with_name(stdout, obj, path, component); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119
static void show_object(struct object *obj, static void show_object(struct object *obj, const char *name, void *cb_data) { struct rev_list_info *info = cb_data; finish_object(obj, name, cb_data); if (info->flags & REV_LIST_QUIET) return; show_object_with_name(stdout, obj, name); }
167,417
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) { fwd_txfm_(in, out, stride, tx_type_); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) { void RunFwdTxfm(const int16_t *in, tran_low_t *out, int stride) { fwd_txfm_(in, out, stride, tx_type_); }
174,550
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionRemoveEventListener(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestEventTarget::s_info)) return throwVMTypeError(exec); JSTestEventTarget* castedThis = jsCast<JSTestEventTarget*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestEventTarget::s_info); TestEventTarget* impl = static_cast<TestEventTarget*>(castedThis->impl()); if (exec->argumentCount() < 2) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); JSValue listener = exec->argument(1); if (!listener.isObject()) return JSValue::encode(jsUndefined()); impl->removeEventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), castedThis, false, currentWorld(exec)).get(), exec->argument(2).toBoolean(exec)); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionRemoveEventListener(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestEventTarget::s_info)) return throwVMTypeError(exec); JSTestEventTarget* castedThis = jsCast<JSTestEventTarget*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestEventTarget::s_info); TestEventTarget* impl = static_cast<TestEventTarget*>(castedThis->impl()); if (exec->argumentCount() < 2) return throwVMError(exec, createNotEnoughArgumentsError(exec)); JSValue listener = exec->argument(1); if (!listener.isObject()) return JSValue::encode(jsUndefined()); impl->removeEventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), castedThis, false, currentWorld(exec)).get(), exec->argument(2).toBoolean(exec)); return JSValue::encode(jsUndefined()); }
170,573
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void _ewk_frame_smart_del(Evas_Object* ewkFrame) { EWK_FRAME_SD_GET(ewkFrame, smartData); if (smartData) { if (smartData->frame) { WebCore::FrameLoaderClientEfl* flc = _ewk_frame_loader_efl_get(smartData->frame); flc->setWebFrame(0); smartData->frame->loader()->detachFromParent(); smartData->frame->loader()->cancelAndClear(); smartData->frame = 0; } eina_stringshare_del(smartData->title); eina_stringshare_del(smartData->uri); eina_stringshare_del(smartData->name); } _parent_sc.del(ewkFrame); } Commit Message: [EFL] fast/frames/frame-crash-with-page-cache.html is crashing https://bugs.webkit.org/show_bug.cgi?id=85879 Patch by Mikhail Pozdnyakov <[email protected]> on 2012-05-17 Reviewed by Noam Rosenthal. Source/WebKit/efl: _ewk_frame_smart_del() is considering now that the frame can be present in cache. loader()->detachFromParent() is only applied for the main frame. loader()->cancelAndClear() is not used anymore. * ewk/ewk_frame.cpp: (_ewk_frame_smart_del): LayoutTests: * platform/efl/test_expectations.txt: Removed fast/frames/frame-crash-with-page-cache.html. git-svn-id: svn://svn.chromium.org/blink/trunk@117409 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void _ewk_frame_smart_del(Evas_Object* ewkFrame) { EWK_FRAME_SD_GET(ewkFrame, smartData); if (smartData) { if (smartData->frame) { WebCore::FrameLoaderClientEfl* flc = _ewk_frame_loader_efl_get(smartData->frame); flc->setWebFrame(0); EWK_FRAME_SD_GET(ewk_view_frame_main_get(smartData->view), mainSmartData); if (mainSmartData->frame == smartData->frame) // applying only for main frame is enough (will traverse through frame tree) smartData->frame->loader()->detachFromParent(); smartData->frame = 0; } eina_stringshare_del(smartData->title); eina_stringshare_del(smartData->uri); eina_stringshare_del(smartData->name); } _parent_sc.del(ewkFrame); }
170,978
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + (nbytes + 1); length = *ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); } Commit Message: CWE ID: CWE-682
char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + nbytes; length = *ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); }
164,748
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: validate_as_request(kdc_realm_t *kdc_active_realm, register krb5_kdc_req *request, krb5_db_entry client, krb5_db_entry server, krb5_timestamp kdc_time, const char **status, krb5_pa_data ***e_data) { int errcode; krb5_error_code ret; /* * If an option is set that is only allowed in TGS requests, complain. */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = "INVALID AS OPTIONS"; return KDC_ERR_BADOPTION; } /* The client must not be expired */ if (client.expiration && client.expiration < kdc_time) { *status = "CLIENT EXPIRED"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_NAME_EXP); } /* The client's password must not be expired, unless the server is a KRB5_KDC_PWCHANGE_SERVICE. */ if (client.pw_expiration && client.pw_expiration < kdc_time && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = "CLIENT KEY EXPIRED"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_KEY_EXP); } /* The server must not be expired */ if (server.expiration && server.expiration < kdc_time) { *status = "SERVICE EXPIRED"; return(KDC_ERR_SERVICE_EXP); } /* * If the client requires password changing, then only allow the * pwchange service. */ if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = "REQUIRED PWCHANGE"; return(KDC_ERR_KEY_EXP); } /* Client and server must allow postdating tickets */ if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) || isflagset(request->kdc_options, KDC_OPT_POSTDATED)) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) || isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) { *status = "POSTDATE NOT ALLOWED"; return(KDC_ERR_CANNOT_POSTDATE); } /* * A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of * KDC_ERR_POLICY in the following case: * * - KDC_OPT_FORWARDABLE is set in KDCOptions but local * policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the * client, and; * - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but * preauthentication data is absent in the request. * * Hence, this check most be done after the check for preauth * data, and is now performed by validate_forwardable() (the * contents of which were previously below). */ /* Client and server must allow proxiable tickets */ if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) || isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) { *status = "PROXIABLE NOT ALLOWED"; return(KDC_ERR_POLICY); } /* Check to see if client is locked out */ if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = "CLIENT LOCKED OUT"; return(KDC_ERR_CLIENT_REVOKED); } /* Check to see if server is locked out */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = "SERVICE LOCKED OUT"; return(KDC_ERR_S_PRINCIPAL_UNKNOWN); } /* Check to see if server is allowed to be a service */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) { *status = "SERVICE NOT ALLOWED"; return(KDC_ERR_MUST_USE_USER2USER); } if (check_anon(kdc_active_realm, request->client, request->server) != 0) { *status = "ANONYMOUS NOT ALLOWED"; return(KDC_ERR_POLICY); } /* Perform KDB module policy checks. */ ret = krb5_db_check_policy_as(kdc_context, request, &client, &server, kdc_time, status, e_data); if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP) return errcode_to_protocol(ret); /* Check against local policy. */ errcode = against_local_policy_as(request, client, server, kdc_time, status, e_data); if (errcode) return errcode; return 0; } Commit Message: Fix S4U2Self KDC crash when anon is restricted In validate_as_request(), when enforcing restrict_anonymous_to_tgt, use client.princ instead of request->client; the latter is NULL when validating S4U2Self requests. CVE-2016-3120: In MIT krb5 1.9 and later, an authenticated attacker can cause krb5kdc to dereference a null pointer if the restrict_anonymous_to_tgt option is set to true, by making an S4U2Self request. CVSSv2 Vector: AV:N/AC:H/Au:S/C:N/I:N/A:C/E:H/RL:OF/RC:C ticket: 8458 (new) target_version: 1.14-next target_version: 1.13-next CWE ID: CWE-476
validate_as_request(kdc_realm_t *kdc_active_realm, register krb5_kdc_req *request, krb5_db_entry client, krb5_db_entry server, krb5_timestamp kdc_time, const char **status, krb5_pa_data ***e_data) { int errcode; krb5_error_code ret; /* * If an option is set that is only allowed in TGS requests, complain. */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = "INVALID AS OPTIONS"; return KDC_ERR_BADOPTION; } /* The client must not be expired */ if (client.expiration && client.expiration < kdc_time) { *status = "CLIENT EXPIRED"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_NAME_EXP); } /* The client's password must not be expired, unless the server is a KRB5_KDC_PWCHANGE_SERVICE. */ if (client.pw_expiration && client.pw_expiration < kdc_time && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = "CLIENT KEY EXPIRED"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_KEY_EXP); } /* The server must not be expired */ if (server.expiration && server.expiration < kdc_time) { *status = "SERVICE EXPIRED"; return(KDC_ERR_SERVICE_EXP); } /* * If the client requires password changing, then only allow the * pwchange service. */ if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = "REQUIRED PWCHANGE"; return(KDC_ERR_KEY_EXP); } /* Client and server must allow postdating tickets */ if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) || isflagset(request->kdc_options, KDC_OPT_POSTDATED)) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) || isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) { *status = "POSTDATE NOT ALLOWED"; return(KDC_ERR_CANNOT_POSTDATE); } /* * A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of * KDC_ERR_POLICY in the following case: * * - KDC_OPT_FORWARDABLE is set in KDCOptions but local * policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the * client, and; * - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but * preauthentication data is absent in the request. * * Hence, this check most be done after the check for preauth * data, and is now performed by validate_forwardable() (the * contents of which were previously below). */ /* Client and server must allow proxiable tickets */ if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) || isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) { *status = "PROXIABLE NOT ALLOWED"; return(KDC_ERR_POLICY); } /* Check to see if client is locked out */ if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = "CLIENT LOCKED OUT"; return(KDC_ERR_CLIENT_REVOKED); } /* Check to see if server is locked out */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = "SERVICE LOCKED OUT"; return(KDC_ERR_S_PRINCIPAL_UNKNOWN); } /* Check to see if server is allowed to be a service */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) { *status = "SERVICE NOT ALLOWED"; return(KDC_ERR_MUST_USE_USER2USER); } if (check_anon(kdc_active_realm, client.princ, request->server) != 0) { *status = "ANONYMOUS NOT ALLOWED"; return(KDC_ERR_POLICY); } /* Perform KDB module policy checks. */ ret = krb5_db_check_policy_as(kdc_context, request, &client, &server, kdc_time, status, e_data); if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP) return errcode_to_protocol(ret); /* Check against local policy. */ errcode = against_local_policy_as(request, client, server, kdc_time, status, e_data); if (errcode) return errcode; return 0; }
167,378
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned int ReferenceSAD(unsigned int max_sad, int block_idx = 0) { unsigned int sad = 0; const uint8_t* const reference = GetReference(block_idx); for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { sad += abs(source_data_[h * source_stride_ + w] - reference[h * reference_stride_ + w]); } if (sad > max_sad) { break; } } return sad; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
unsigned int ReferenceSAD(unsigned int max_sad, int block_idx = 0) { unsigned int ReferenceSAD(int block_idx) { unsigned int sad = 0; const uint8_t *const reference8 = GetReference(block_idx); const uint8_t *const source8 = source_data_; #if CONFIG_VP9_HIGHBITDEPTH const uint16_t *const reference16 = CONVERT_TO_SHORTPTR(GetReference(block_idx)); const uint16_t *const source16 = CONVERT_TO_SHORTPTR(source_data_); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { sad += abs(source8[h * source_stride_ + w] - reference8[h * reference_stride_ + w]); #if CONFIG_VP9_HIGHBITDEPTH } else { sad += abs(source16[h * source_stride_ + w] - reference16[h * reference_stride_ + w]); #endif // CONFIG_VP9_HIGHBITDEPTH } } } return sad; }
174,574
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: flush_signal_handlers(struct task_struct *t, int force_default) { int i; struct k_sigaction *ka = &t->sighand->action[0]; for (i = _NSIG ; i != 0 ; i--) { if (force_default || ka->sa.sa_handler != SIG_IGN) ka->sa.sa_handler = SIG_DFL; ka->sa.sa_flags = 0; sigemptyset(&ka->sa.sa_mask); ka++; } } Commit Message: signal: always clear sa_restorer on execve When the new signal handlers are set up, the location of sa_restorer is not cleared, leaking a parent process's address space location to children. This allows for a potential bypass of the parent's ASLR by examining the sa_restorer value returned when calling sigaction(). Based on what should be considered "secret" about addresses, it only matters across the exec not the fork (since the VMAs haven't changed until the exec). But since exec sets SIG_DFL and keeps sa_restorer, this is where it should be fixed. Given the few uses of sa_restorer, a "set" function was not written since this would be the only use. Instead, we use __ARCH_HAS_SA_RESTORER, as already done in other places. Example of the leak before applying this patch: $ cat /proc/$$/maps ... 7fb9f3083000-7fb9f3238000 r-xp 00000000 fd:01 404469 .../libc-2.15.so ... $ ./leak ... 7f278bc74000-7f278be29000 r-xp 00000000 fd:01 404469 .../libc-2.15.so ... 1 0 (nil) 0x7fb9f30b94a0 2 4000000 (nil) 0x7f278bcaa4a0 3 4000000 (nil) 0x7f278bcaa4a0 4 0 (nil) 0x7fb9f30b94a0 ... [[email protected]: use SA_RESTORER for backportability] Signed-off-by: Kees Cook <[email protected]> Reported-by: Emese Revfy <[email protected]> Cc: Emese Revfy <[email protected]> Cc: PaX Team <[email protected]> Cc: Al Viro <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: "Eric W. Biederman" <[email protected]> Cc: Serge Hallyn <[email protected]> Cc: Julien Tinnes <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
flush_signal_handlers(struct task_struct *t, int force_default) { int i; struct k_sigaction *ka = &t->sighand->action[0]; for (i = _NSIG ; i != 0 ; i--) { if (force_default || ka->sa.sa_handler != SIG_IGN) ka->sa.sa_handler = SIG_DFL; ka->sa.sa_flags = 0; #ifdef SA_RESTORER ka->sa.sa_restorer = NULL; #endif sigemptyset(&ka->sa.sa_mask); ka++; } }
166,134
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII("options_page")); GURL omnibox(chrome::kChromeUIOmniboxURL); ui_test_utils::NavigateToURL(browser(), omnibox); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(omnibox, tab1->GetURL()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2); GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph1); GURL extension_url("chrome-extension://" + extension->id()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), extension_url); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), extension_url); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285
void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII("options_page")); // Change the first tab to be the omnibox page (WebUI). GURL omnibox(chrome::kChromeUIOmniboxURL); ui_test_utils::NavigateToURL(browser(), omnibox); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(omnibox, tab1->GetURL()); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create a new normal tab with a data URL. It should be in its own process. GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); // Create another data URL tab. With Site Isolation, this will require its // own process, but without Site Isolation, it can share the previous // process. GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; if (content::AreAllSitesIsolatedForTesting()) host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); if (content::AreAllSitesIsolatedForTesting()) EXPECT_NE(tab2->GetMainFrame()->GetProcess(), rph2); else EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2); // Create another WebUI tab. It should share the process with omnibox. // Note: intentionally create this tab after the normal tabs to exercise bug // 43448 where extension and WebUI tabs could get combined into normal // renderers. GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph1); // Create an extension tab. It should be in its own process. GURL extension_url("chrome-extension://" + extension->id()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), extension_url); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), extension_url); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); }
173,180
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int dccp_rcv_state_process(struct sock *sk, struct sk_buff *skb, struct dccp_hdr *dh, unsigned int len) { struct dccp_sock *dp = dccp_sk(sk); struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb); const int old_state = sk->sk_state; int queued = 0; /* * Step 3: Process LISTEN state * * If S.state == LISTEN, * If P.type == Request or P contains a valid Init Cookie option, * (* Must scan the packet's options to check for Init * Cookies. Only Init Cookies are processed here, * however; other options are processed in Step 8. This * scan need only be performed if the endpoint uses Init * Cookies *) * (* Generate a new socket and switch to that socket *) * Set S := new socket for this port pair * S.state = RESPOND * Choose S.ISS (initial seqno) or set from Init Cookies * Initialize S.GAR := S.ISS * Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init * Cookies Continue with S.state == RESPOND * (* A Response packet will be generated in Step 11 *) * Otherwise, * Generate Reset(No Connection) unless P.type == Reset * Drop packet and return */ if (sk->sk_state == DCCP_LISTEN) { if (dh->dccph_type == DCCP_PKT_REQUEST) { if (inet_csk(sk)->icsk_af_ops->conn_request(sk, skb) < 0) return 1; goto discard; } if (dh->dccph_type == DCCP_PKT_RESET) goto discard; /* Caller (dccp_v4_do_rcv) will send Reset */ dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION; return 1; } else if (sk->sk_state == DCCP_CLOSED) { dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION; return 1; } /* Step 6: Check sequence numbers (omitted in LISTEN/REQUEST state) */ if (sk->sk_state != DCCP_REQUESTING && dccp_check_seqno(sk, skb)) goto discard; /* * Step 7: Check for unexpected packet types * If (S.is_server and P.type == Response) * or (S.is_client and P.type == Request) * or (S.state == RESPOND and P.type == Data), * Send Sync packet acknowledging P.seqno * Drop packet and return */ if ((dp->dccps_role != DCCP_ROLE_CLIENT && dh->dccph_type == DCCP_PKT_RESPONSE) || (dp->dccps_role == DCCP_ROLE_CLIENT && dh->dccph_type == DCCP_PKT_REQUEST) || (sk->sk_state == DCCP_RESPOND && dh->dccph_type == DCCP_PKT_DATA)) { dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNC); goto discard; } /* Step 8: Process options */ if (dccp_parse_options(sk, NULL, skb)) return 1; /* * Step 9: Process Reset * If P.type == Reset, * Tear down connection * S.state := TIMEWAIT * Set TIMEWAIT timer * Drop packet and return */ if (dh->dccph_type == DCCP_PKT_RESET) { dccp_rcv_reset(sk, skb); return 0; } else if (dh->dccph_type == DCCP_PKT_CLOSEREQ) { /* Step 13 */ if (dccp_rcv_closereq(sk, skb)) return 0; goto discard; } else if (dh->dccph_type == DCCP_PKT_CLOSE) { /* Step 14 */ if (dccp_rcv_close(sk, skb)) return 0; goto discard; } switch (sk->sk_state) { case DCCP_REQUESTING: queued = dccp_rcv_request_sent_state_process(sk, skb, dh, len); if (queued >= 0) return queued; __kfree_skb(skb); return 0; case DCCP_PARTOPEN: /* Step 8: if using Ack Vectors, mark packet acknowledgeable */ dccp_handle_ackvec_processing(sk, skb); dccp_deliver_input_to_ccids(sk, skb); /* fall through */ case DCCP_RESPOND: queued = dccp_rcv_respond_partopen_state_process(sk, skb, dh, len); break; } if (dh->dccph_type == DCCP_PKT_ACK || dh->dccph_type == DCCP_PKT_DATAACK) { switch (old_state) { case DCCP_PARTOPEN: sk->sk_state_change(sk); sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); break; } } else if (unlikely(dh->dccph_type == DCCP_PKT_SYNC)) { dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNCACK); goto discard; } if (!queued) { discard: __kfree_skb(skb); } return 0; } Commit Message: dccp: fix freeing skb too early for IPV6_RECVPKTINFO In the current DCCP implementation an skb for a DCCP_PKT_REQUEST packet is forcibly freed via __kfree_skb in dccp_rcv_state_process if dccp_v6_conn_request successfully returns. However, if IPV6_RECVPKTINFO is set on a socket, the address of the skb is saved to ireq->pktopts and the ref count for skb is incremented in dccp_v6_conn_request, so skb is still in use. Nevertheless, it gets freed in dccp_rcv_state_process. Fix by calling consume_skb instead of doing goto discard and therefore calling __kfree_skb. Similar fixes for TCP: fb7e2399ec17f1004c0e0ccfd17439f8759ede01 [TCP]: skb is unexpectedly freed. 0aea76d35c9651d55bbaf746e7914e5f9ae5a25d tcp: SYN packets are now simply consumed Signed-off-by: Andrey Konovalov <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-415
int dccp_rcv_state_process(struct sock *sk, struct sk_buff *skb, struct dccp_hdr *dh, unsigned int len) { struct dccp_sock *dp = dccp_sk(sk); struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb); const int old_state = sk->sk_state; int queued = 0; /* * Step 3: Process LISTEN state * * If S.state == LISTEN, * If P.type == Request or P contains a valid Init Cookie option, * (* Must scan the packet's options to check for Init * Cookies. Only Init Cookies are processed here, * however; other options are processed in Step 8. This * scan need only be performed if the endpoint uses Init * Cookies *) * (* Generate a new socket and switch to that socket *) * Set S := new socket for this port pair * S.state = RESPOND * Choose S.ISS (initial seqno) or set from Init Cookies * Initialize S.GAR := S.ISS * Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init * Cookies Continue with S.state == RESPOND * (* A Response packet will be generated in Step 11 *) * Otherwise, * Generate Reset(No Connection) unless P.type == Reset * Drop packet and return */ if (sk->sk_state == DCCP_LISTEN) { if (dh->dccph_type == DCCP_PKT_REQUEST) { if (inet_csk(sk)->icsk_af_ops->conn_request(sk, skb) < 0) return 1; consume_skb(skb); return 0; } if (dh->dccph_type == DCCP_PKT_RESET) goto discard; /* Caller (dccp_v4_do_rcv) will send Reset */ dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION; return 1; } else if (sk->sk_state == DCCP_CLOSED) { dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION; return 1; } /* Step 6: Check sequence numbers (omitted in LISTEN/REQUEST state) */ if (sk->sk_state != DCCP_REQUESTING && dccp_check_seqno(sk, skb)) goto discard; /* * Step 7: Check for unexpected packet types * If (S.is_server and P.type == Response) * or (S.is_client and P.type == Request) * or (S.state == RESPOND and P.type == Data), * Send Sync packet acknowledging P.seqno * Drop packet and return */ if ((dp->dccps_role != DCCP_ROLE_CLIENT && dh->dccph_type == DCCP_PKT_RESPONSE) || (dp->dccps_role == DCCP_ROLE_CLIENT && dh->dccph_type == DCCP_PKT_REQUEST) || (sk->sk_state == DCCP_RESPOND && dh->dccph_type == DCCP_PKT_DATA)) { dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNC); goto discard; } /* Step 8: Process options */ if (dccp_parse_options(sk, NULL, skb)) return 1; /* * Step 9: Process Reset * If P.type == Reset, * Tear down connection * S.state := TIMEWAIT * Set TIMEWAIT timer * Drop packet and return */ if (dh->dccph_type == DCCP_PKT_RESET) { dccp_rcv_reset(sk, skb); return 0; } else if (dh->dccph_type == DCCP_PKT_CLOSEREQ) { /* Step 13 */ if (dccp_rcv_closereq(sk, skb)) return 0; goto discard; } else if (dh->dccph_type == DCCP_PKT_CLOSE) { /* Step 14 */ if (dccp_rcv_close(sk, skb)) return 0; goto discard; } switch (sk->sk_state) { case DCCP_REQUESTING: queued = dccp_rcv_request_sent_state_process(sk, skb, dh, len); if (queued >= 0) return queued; __kfree_skb(skb); return 0; case DCCP_PARTOPEN: /* Step 8: if using Ack Vectors, mark packet acknowledgeable */ dccp_handle_ackvec_processing(sk, skb); dccp_deliver_input_to_ccids(sk, skb); /* fall through */ case DCCP_RESPOND: queued = dccp_rcv_respond_partopen_state_process(sk, skb, dh, len); break; } if (dh->dccph_type == DCCP_PKT_ACK || dh->dccph_type == DCCP_PKT_DATAACK) { switch (old_state) { case DCCP_PARTOPEN: sk->sk_state_change(sk); sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); break; } } else if (unlikely(dh->dccph_type == DCCP_PKT_SYNC)) { dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNCACK); goto discard; } if (!queued) { discard: __kfree_skb(skb); } return 0; }
168,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } Commit Message: re_lexer: Make reading escape sequences more robust (#586) * Add test for issue #503 * re_lexer: Make reading escape sequences more robust This commit fixes parsing incomplete escape sequences at the end of a regular expression and parsing things like \xxy (invalid hex digits) which before were silently turned into (char)255. Close #503 * Update re_lexer.c CWE ID: CWE-476
int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; }
168,483
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SyncBackendHost::Core::DoInitialize(const DoInitializeOptions& options) { DCHECK(!sync_loop_); sync_loop_ = options.sync_loop; DCHECK(sync_loop_); if (options.delete_sync_data_folder) { DeleteSyncDataFolder(); } bool success = file_util::CreateDirectory(sync_data_folder_path_); DCHECK(success); DCHECK(!registrar_); registrar_ = options.registrar; DCHECK(registrar_); sync_manager_.reset(new sync_api::SyncManager(name_)); sync_manager_->AddObserver(this); success = sync_manager_->Init( sync_data_folder_path_, options.event_handler, options.service_url.host() + options.service_url.path(), options.service_url.EffectiveIntPort(), options.service_url.SchemeIsSecure(), BrowserThread::GetBlockingPool(), options.make_http_bridge_factory_fn.Run(), options.registrar /* as ModelSafeWorkerRegistrar */, options.extensions_activity_monitor, options.registrar /* as SyncManager::ChangeDelegate */, MakeUserAgentForSyncApi(), options.credentials, true, new BridgedSyncNotifier( options.chrome_sync_notification_bridge, options.sync_notifier_factory->CreateSyncNotifier()), options.restored_key_for_bootstrapping, options.testing_mode, &encryptor_, options.unrecoverable_error_handler, options.report_unrecoverable_error_function); LOG_IF(ERROR, !success) << "Syncapi initialization failed!"; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kSyncThrowUnrecoverableError)) { sync_manager_->ThrowUnrecoverableError(); } } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void SyncBackendHost::Core::DoInitialize(const DoInitializeOptions& options) { DCHECK(!sync_loop_); sync_loop_ = options.sync_loop; DCHECK(sync_loop_); if (options.delete_sync_data_folder) { DeleteSyncDataFolder(); } bool success = file_util::CreateDirectory(sync_data_folder_path_); DCHECK(success); DCHECK(!registrar_); registrar_ = options.registrar; DCHECK(registrar_); sync_manager_.reset(new sync_api::SyncManager(name_)); sync_manager_->AddObserver(this); success = sync_manager_->Init( sync_data_folder_path_, options.event_handler, options.service_url.host() + options.service_url.path(), options.service_url.EffectiveIntPort(), options.service_url.SchemeIsSecure(), BrowserThread::GetBlockingPool(), options.make_http_bridge_factory_fn.Run(), options.registrar /* as ModelSafeWorkerRegistrar */, options.extensions_activity_monitor, options.registrar /* as SyncManager::ChangeDelegate */, MakeUserAgentForSyncApi(), options.credentials, new BridgedSyncNotifier( options.chrome_sync_notification_bridge, options.sync_notifier_factory->CreateSyncNotifier()), options.restored_key_for_bootstrapping, options.testing_mode, &encryptor_, options.unrecoverable_error_handler, options.report_unrecoverable_error_function); LOG_IF(ERROR, !success) << "Syncapi initialization failed!"; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kSyncThrowUnrecoverableError)) { sync_manager_->ThrowUnrecoverableError(); } }
170,785
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static js_Ast *callexp(js_State *J) { js_Ast *a = newexp(J); loop: if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } if (jsP_accept(J, '(')) { a = EXP2(CALL, a, arguments(J)); jsP_expect(J, ')'); goto loop; } return a; } Commit Message: CWE ID: CWE-674
static js_Ast *callexp(js_State *J) { js_Ast *a = newexp(J); SAVEREC(); loop: INCREC(); if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } if (jsP_accept(J, '(')) { a = EXP2(CALL, a, arguments(J)); jsP_expect(J, ')'); goto loop; } POPREC(); return a; }
165,135
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bgp_size_t bgp_packet_attribute(struct bgp *bgp, struct peer *peer, struct stream *s, struct attr *attr, struct bpacket_attr_vec_arr *vecarr, struct prefix *p, afi_t afi, safi_t safi, struct peer *from, struct prefix_rd *prd, mpls_label_t *label, uint32_t num_labels, int addpath_encode, uint32_t addpath_tx_id) { size_t cp; size_t aspath_sizep; struct aspath *aspath; int send_as4_path = 0; int send_as4_aggregator = 0; int use32bit = (CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)) ? 1 : 0; if (!bgp) bgp = peer->bgp; /* Remember current pointer. */ cp = stream_get_endp(s); if (p && !((afi == AFI_IP && safi == SAFI_UNICAST) && !peer_cap_enhe(peer, afi, safi))) { size_t mpattrlen_pos = 0; mpattrlen_pos = bgp_packet_mpattr_start(s, peer, afi, safi, vecarr, attr); bgp_packet_mpattr_prefix(s, afi, safi, p, prd, label, num_labels, addpath_encode, addpath_tx_id, attr); bgp_packet_mpattr_end(s, mpattrlen_pos); } /* Origin attribute. */ stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ORIGIN); stream_putc(s, 1); stream_putc(s, attr->origin); /* AS path attribute. */ /* If remote-peer is EBGP */ if (peer->sort == BGP_PEER_EBGP && (!CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_AS_PATH_UNCHANGED) || attr->aspath->segments == NULL) && (!CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_RSERVER_CLIENT))) { aspath = aspath_dup(attr->aspath); /* Even though we may not be configured for confederations we * may have * RXed an AS_PATH with AS_CONFED_SEQUENCE or AS_CONFED_SET */ aspath = aspath_delete_confed_seq(aspath); if (CHECK_FLAG(bgp->config, BGP_CONFIG_CONFEDERATION)) { /* Stuff our path CONFED_ID on the front */ aspath = aspath_add_seq(aspath, bgp->confed_id); } else { if (peer->change_local_as) { /* If replace-as is specified, we only use the change_local_as when advertising routes. */ if (!CHECK_FLAG( peer->flags, PEER_FLAG_LOCAL_AS_REPLACE_AS)) { aspath = aspath_add_seq(aspath, peer->local_as); } aspath = aspath_add_seq(aspath, peer->change_local_as); } else { aspath = aspath_add_seq(aspath, peer->local_as); } } } else if (peer->sort == BGP_PEER_CONFED) { /* A confed member, so we need to do the AS_CONFED_SEQUENCE * thing */ aspath = aspath_dup(attr->aspath); aspath = aspath_add_confed_seq(aspath, peer->local_as); } else aspath = attr->aspath; /* If peer is not AS4 capable, then: * - send the created AS_PATH out as AS4_PATH (optional, transitive), * but ensure that no AS_CONFED_SEQUENCE and AS_CONFED_SET path * segment * types are in it (i.e. exclude them if they are there) * AND do this only if there is at least one asnum > 65535 in the * path! * - send an AS_PATH out, but put 16Bit ASnums in it, not 32bit, and * change * all ASnums > 65535 to BGP_AS_TRANS */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_AS_PATH); aspath_sizep = stream_get_endp(s); stream_putw(s, 0); stream_putw_at(s, aspath_sizep, aspath_put(s, aspath, use32bit)); /* OLD session may need NEW_AS_PATH sent, if there are 4-byte ASNs * in the path */ if (!use32bit && aspath_has_as4(aspath)) send_as4_path = 1; /* we'll do this later, at the correct place */ /* Nexthop attribute. */ if (afi == AFI_IP && safi == SAFI_UNICAST && !peer_cap_enhe(peer, afi, safi)) { if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_NEXT_HOP)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_NEXT_HOP); bpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s, attr); stream_putc(s, 4); stream_put_ipv4(s, attr->nexthop.s_addr); } else if (peer_cap_enhe(from, afi, safi)) { /* * Likely this is the case when an IPv4 prefix was * received with * Extended Next-hop capability and now being advertised * to * non-ENHE peers. * Setting the mandatory (ipv4) next-hop attribute here * to enable * implicit next-hop self with correct (ipv4 address * family). */ stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_NEXT_HOP); bpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s, NULL); stream_putc(s, 4); stream_put_ipv4(s, 0); } } /* MED attribute. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_MULTI_EXIT_DISC) || bgp->maxmed_active) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_MULTI_EXIT_DISC); stream_putc(s, 4); stream_putl(s, (bgp->maxmed_active ? bgp->maxmed_value : attr->med)); } /* Local preference. */ if (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LOCAL_PREF); stream_putc(s, 4); stream_putl(s, attr->local_pref); } /* Atomic aggregate. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ATOMIC_AGGREGATE)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ATOMIC_AGGREGATE); stream_putc(s, 0); } /* Aggregator. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR)) { /* Common to BGP_ATTR_AGGREGATOR, regardless of ASN size */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_AGGREGATOR); if (use32bit) { /* AS4 capable peer */ stream_putc(s, 8); stream_putl(s, attr->aggregator_as); } else { /* 2-byte AS peer */ stream_putc(s, 6); /* Is ASN representable in 2-bytes? Or must AS_TRANS be * used? */ if (attr->aggregator_as > 65535) { stream_putw(s, BGP_AS_TRANS); /* we have to send AS4_AGGREGATOR, too. * we'll do that later in order to send * attributes in ascending * order. */ send_as4_aggregator = 1; } else stream_putw(s, (uint16_t)attr->aggregator_as); } stream_put_ipv4(s, attr->aggregator_addr.s_addr); } /* Community attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_COMMUNITIES))) { if (attr->community->size * 4 > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putw(s, attr->community->size * 4); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putc(s, attr->community->size * 4); } stream_put(s, attr->community->val, attr->community->size * 4); } /* * Large Community attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_LARGE_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_LARGE_COMMUNITIES))) { if (lcom_length(attr->lcommunity) > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putw(s, lcom_length(attr->lcommunity)); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putc(s, lcom_length(attr->lcommunity)); } stream_put(s, attr->lcommunity->val, lcom_length(attr->lcommunity)); } /* Route Reflector. */ if (peer->sort == BGP_PEER_IBGP && from && from->sort == BGP_PEER_IBGP) { /* Originator ID. */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_ORIGINATOR_ID); stream_putc(s, 4); if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ORIGINATOR_ID)) stream_put_in_addr(s, &attr->originator_id); else stream_put_in_addr(s, &from->remote_id); /* Cluster list. */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_CLUSTER_LIST); if (attr->cluster) { stream_putc(s, attr->cluster->length + 4); /* If this peer configuration's parent BGP has * cluster_id. */ if (bgp->config & BGP_CONFIG_CLUSTER_ID) stream_put_in_addr(s, &bgp->cluster_id); else stream_put_in_addr(s, &bgp->router_id); stream_put(s, attr->cluster->list, attr->cluster->length); } else { stream_putc(s, 4); /* If this peer configuration's parent BGP has * cluster_id. */ if (bgp->config & BGP_CONFIG_CLUSTER_ID) stream_put_in_addr(s, &bgp->cluster_id); else stream_put_in_addr(s, &bgp->router_id); } } /* Extended Communities attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_EXT_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_EXT_COMMUNITIES))) { if (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED) { if (attr->ecommunity->size * 8 > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putw(s, attr->ecommunity->size * 8); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putc(s, attr->ecommunity->size * 8); } stream_put(s, attr->ecommunity->val, attr->ecommunity->size * 8); } else { uint8_t *pnt; int tbit; int ecom_tr_size = 0; int i; for (i = 0; i < attr->ecommunity->size; i++) { pnt = attr->ecommunity->val + (i * 8); tbit = *pnt; if (CHECK_FLAG(tbit, ECOMMUNITY_FLAG_NON_TRANSITIVE)) continue; ecom_tr_size++; } if (ecom_tr_size) { if (ecom_tr_size * 8 > 255) { stream_putc( s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putw(s, ecom_tr_size * 8); } else { stream_putc( s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putc(s, ecom_tr_size * 8); } for (i = 0; i < attr->ecommunity->size; i++) { pnt = attr->ecommunity->val + (i * 8); tbit = *pnt; if (CHECK_FLAG( tbit, ECOMMUNITY_FLAG_NON_TRANSITIVE)) continue; stream_put(s, pnt, 8); } } } } /* Label index attribute. */ if (safi == SAFI_LABELED_UNICAST) { if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PREFIX_SID)) { uint32_t label_index; label_index = attr->label_index; if (label_index != BGP_INVALID_LABEL_INDEX) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_PREFIX_SID); stream_putc(s, 10); stream_putc(s, BGP_PREFIX_SID_LABEL_INDEX); stream_putw(s, BGP_PREFIX_SID_LABEL_INDEX_LENGTH); stream_putc(s, 0); // reserved stream_putw(s, 0); // flags stream_putl(s, label_index); } } } if (send_as4_path) { /* If the peer is NOT As4 capable, AND */ /* there are ASnums > 65535 in path THEN * give out AS4_PATH */ /* Get rid of all AS_CONFED_SEQUENCE and AS_CONFED_SET * path segments! * Hm, I wonder... confederation things *should* only be at * the beginning of an aspath, right? Then we should use * aspath_delete_confed_seq for this, because it is already * there! (JK) * Folks, talk to me: what is reasonable here!? */ aspath = aspath_delete_confed_seq(aspath); stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_AS4_PATH); aspath_sizep = stream_get_endp(s); stream_putw(s, 0); stream_putw_at(s, aspath_sizep, aspath_put(s, aspath, 1)); } if (aspath != attr->aspath) aspath_free(aspath); if (send_as4_aggregator) { /* send AS4_AGGREGATOR, at this place */ /* this section of code moved here in order to ensure the * correct * *ascending* order of attributes */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_AS4_AGGREGATOR); stream_putc(s, 8); stream_putl(s, attr->aggregator_as); stream_put_ipv4(s, attr->aggregator_addr.s_addr); } if (((afi == AFI_IP || afi == AFI_IP6) && (safi == SAFI_ENCAP || safi == SAFI_MPLS_VPN)) || (afi == AFI_L2VPN && safi == SAFI_EVPN)) { /* Tunnel Encap attribute */ bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_ENCAP); #if ENABLE_BGP_VNC /* VNC attribute */ bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_VNC); #endif } /* PMSI Tunnel */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PMSI_TUNNEL)) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_PMSI_TUNNEL); stream_putc(s, 9); // Length stream_putc(s, 0); // Flags stream_putc(s, PMSI_TNLTYPE_INGR_REPL); // IR (6) stream_put(s, &(attr->label), BGP_LABEL_BYTES); // MPLS Label / VXLAN VNI stream_put_ipv4(s, attr->nexthop.s_addr); } /* Unknown transit attribute. */ if (attr->transit) stream_put(s, attr->transit->val, attr->transit->length); /* Return total size of attribute. */ return stream_get_endp(s) - cp; } Commit Message: bgpd: don't use BGP_ATTR_VNC(255) unless ENABLE_BGP_VNC_ATTR is defined Signed-off-by: Lou Berger <[email protected]> CWE ID:
bgp_size_t bgp_packet_attribute(struct bgp *bgp, struct peer *peer, struct stream *s, struct attr *attr, struct bpacket_attr_vec_arr *vecarr, struct prefix *p, afi_t afi, safi_t safi, struct peer *from, struct prefix_rd *prd, mpls_label_t *label, uint32_t num_labels, int addpath_encode, uint32_t addpath_tx_id) { size_t cp; size_t aspath_sizep; struct aspath *aspath; int send_as4_path = 0; int send_as4_aggregator = 0; int use32bit = (CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)) ? 1 : 0; if (!bgp) bgp = peer->bgp; /* Remember current pointer. */ cp = stream_get_endp(s); if (p && !((afi == AFI_IP && safi == SAFI_UNICAST) && !peer_cap_enhe(peer, afi, safi))) { size_t mpattrlen_pos = 0; mpattrlen_pos = bgp_packet_mpattr_start(s, peer, afi, safi, vecarr, attr); bgp_packet_mpattr_prefix(s, afi, safi, p, prd, label, num_labels, addpath_encode, addpath_tx_id, attr); bgp_packet_mpattr_end(s, mpattrlen_pos); } /* Origin attribute. */ stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ORIGIN); stream_putc(s, 1); stream_putc(s, attr->origin); /* AS path attribute. */ /* If remote-peer is EBGP */ if (peer->sort == BGP_PEER_EBGP && (!CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_AS_PATH_UNCHANGED) || attr->aspath->segments == NULL) && (!CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_RSERVER_CLIENT))) { aspath = aspath_dup(attr->aspath); /* Even though we may not be configured for confederations we * may have * RXed an AS_PATH with AS_CONFED_SEQUENCE or AS_CONFED_SET */ aspath = aspath_delete_confed_seq(aspath); if (CHECK_FLAG(bgp->config, BGP_CONFIG_CONFEDERATION)) { /* Stuff our path CONFED_ID on the front */ aspath = aspath_add_seq(aspath, bgp->confed_id); } else { if (peer->change_local_as) { /* If replace-as is specified, we only use the change_local_as when advertising routes. */ if (!CHECK_FLAG( peer->flags, PEER_FLAG_LOCAL_AS_REPLACE_AS)) { aspath = aspath_add_seq(aspath, peer->local_as); } aspath = aspath_add_seq(aspath, peer->change_local_as); } else { aspath = aspath_add_seq(aspath, peer->local_as); } } } else if (peer->sort == BGP_PEER_CONFED) { /* A confed member, so we need to do the AS_CONFED_SEQUENCE * thing */ aspath = aspath_dup(attr->aspath); aspath = aspath_add_confed_seq(aspath, peer->local_as); } else aspath = attr->aspath; /* If peer is not AS4 capable, then: * - send the created AS_PATH out as AS4_PATH (optional, transitive), * but ensure that no AS_CONFED_SEQUENCE and AS_CONFED_SET path * segment * types are in it (i.e. exclude them if they are there) * AND do this only if there is at least one asnum > 65535 in the * path! * - send an AS_PATH out, but put 16Bit ASnums in it, not 32bit, and * change * all ASnums > 65535 to BGP_AS_TRANS */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_AS_PATH); aspath_sizep = stream_get_endp(s); stream_putw(s, 0); stream_putw_at(s, aspath_sizep, aspath_put(s, aspath, use32bit)); /* OLD session may need NEW_AS_PATH sent, if there are 4-byte ASNs * in the path */ if (!use32bit && aspath_has_as4(aspath)) send_as4_path = 1; /* we'll do this later, at the correct place */ /* Nexthop attribute. */ if (afi == AFI_IP && safi == SAFI_UNICAST && !peer_cap_enhe(peer, afi, safi)) { if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_NEXT_HOP)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_NEXT_HOP); bpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s, attr); stream_putc(s, 4); stream_put_ipv4(s, attr->nexthop.s_addr); } else if (peer_cap_enhe(from, afi, safi)) { /* * Likely this is the case when an IPv4 prefix was * received with * Extended Next-hop capability and now being advertised * to * non-ENHE peers. * Setting the mandatory (ipv4) next-hop attribute here * to enable * implicit next-hop self with correct (ipv4 address * family). */ stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_NEXT_HOP); bpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s, NULL); stream_putc(s, 4); stream_put_ipv4(s, 0); } } /* MED attribute. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_MULTI_EXIT_DISC) || bgp->maxmed_active) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_MULTI_EXIT_DISC); stream_putc(s, 4); stream_putl(s, (bgp->maxmed_active ? bgp->maxmed_value : attr->med)); } /* Local preference. */ if (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LOCAL_PREF); stream_putc(s, 4); stream_putl(s, attr->local_pref); } /* Atomic aggregate. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ATOMIC_AGGREGATE)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ATOMIC_AGGREGATE); stream_putc(s, 0); } /* Aggregator. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR)) { /* Common to BGP_ATTR_AGGREGATOR, regardless of ASN size */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_AGGREGATOR); if (use32bit) { /* AS4 capable peer */ stream_putc(s, 8); stream_putl(s, attr->aggregator_as); } else { /* 2-byte AS peer */ stream_putc(s, 6); /* Is ASN representable in 2-bytes? Or must AS_TRANS be * used? */ if (attr->aggregator_as > 65535) { stream_putw(s, BGP_AS_TRANS); /* we have to send AS4_AGGREGATOR, too. * we'll do that later in order to send * attributes in ascending * order. */ send_as4_aggregator = 1; } else stream_putw(s, (uint16_t)attr->aggregator_as); } stream_put_ipv4(s, attr->aggregator_addr.s_addr); } /* Community attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_COMMUNITIES))) { if (attr->community->size * 4 > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putw(s, attr->community->size * 4); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putc(s, attr->community->size * 4); } stream_put(s, attr->community->val, attr->community->size * 4); } /* * Large Community attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_LARGE_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_LARGE_COMMUNITIES))) { if (lcom_length(attr->lcommunity) > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putw(s, lcom_length(attr->lcommunity)); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putc(s, lcom_length(attr->lcommunity)); } stream_put(s, attr->lcommunity->val, lcom_length(attr->lcommunity)); } /* Route Reflector. */ if (peer->sort == BGP_PEER_IBGP && from && from->sort == BGP_PEER_IBGP) { /* Originator ID. */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_ORIGINATOR_ID); stream_putc(s, 4); if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ORIGINATOR_ID)) stream_put_in_addr(s, &attr->originator_id); else stream_put_in_addr(s, &from->remote_id); /* Cluster list. */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_CLUSTER_LIST); if (attr->cluster) { stream_putc(s, attr->cluster->length + 4); /* If this peer configuration's parent BGP has * cluster_id. */ if (bgp->config & BGP_CONFIG_CLUSTER_ID) stream_put_in_addr(s, &bgp->cluster_id); else stream_put_in_addr(s, &bgp->router_id); stream_put(s, attr->cluster->list, attr->cluster->length); } else { stream_putc(s, 4); /* If this peer configuration's parent BGP has * cluster_id. */ if (bgp->config & BGP_CONFIG_CLUSTER_ID) stream_put_in_addr(s, &bgp->cluster_id); else stream_put_in_addr(s, &bgp->router_id); } } /* Extended Communities attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_EXT_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_EXT_COMMUNITIES))) { if (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED) { if (attr->ecommunity->size * 8 > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putw(s, attr->ecommunity->size * 8); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putc(s, attr->ecommunity->size * 8); } stream_put(s, attr->ecommunity->val, attr->ecommunity->size * 8); } else { uint8_t *pnt; int tbit; int ecom_tr_size = 0; int i; for (i = 0; i < attr->ecommunity->size; i++) { pnt = attr->ecommunity->val + (i * 8); tbit = *pnt; if (CHECK_FLAG(tbit, ECOMMUNITY_FLAG_NON_TRANSITIVE)) continue; ecom_tr_size++; } if (ecom_tr_size) { if (ecom_tr_size * 8 > 255) { stream_putc( s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putw(s, ecom_tr_size * 8); } else { stream_putc( s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putc(s, ecom_tr_size * 8); } for (i = 0; i < attr->ecommunity->size; i++) { pnt = attr->ecommunity->val + (i * 8); tbit = *pnt; if (CHECK_FLAG( tbit, ECOMMUNITY_FLAG_NON_TRANSITIVE)) continue; stream_put(s, pnt, 8); } } } } /* Label index attribute. */ if (safi == SAFI_LABELED_UNICAST) { if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PREFIX_SID)) { uint32_t label_index; label_index = attr->label_index; if (label_index != BGP_INVALID_LABEL_INDEX) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_PREFIX_SID); stream_putc(s, 10); stream_putc(s, BGP_PREFIX_SID_LABEL_INDEX); stream_putw(s, BGP_PREFIX_SID_LABEL_INDEX_LENGTH); stream_putc(s, 0); // reserved stream_putw(s, 0); // flags stream_putl(s, label_index); } } } if (send_as4_path) { /* If the peer is NOT As4 capable, AND */ /* there are ASnums > 65535 in path THEN * give out AS4_PATH */ /* Get rid of all AS_CONFED_SEQUENCE and AS_CONFED_SET * path segments! * Hm, I wonder... confederation things *should* only be at * the beginning of an aspath, right? Then we should use * aspath_delete_confed_seq for this, because it is already * there! (JK) * Folks, talk to me: what is reasonable here!? */ aspath = aspath_delete_confed_seq(aspath); stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_AS4_PATH); aspath_sizep = stream_get_endp(s); stream_putw(s, 0); stream_putw_at(s, aspath_sizep, aspath_put(s, aspath, 1)); } if (aspath != attr->aspath) aspath_free(aspath); if (send_as4_aggregator) { /* send AS4_AGGREGATOR, at this place */ /* this section of code moved here in order to ensure the * correct * *ascending* order of attributes */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_AS4_AGGREGATOR); stream_putc(s, 8); stream_putl(s, attr->aggregator_as); stream_put_ipv4(s, attr->aggregator_addr.s_addr); } if (((afi == AFI_IP || afi == AFI_IP6) && (safi == SAFI_ENCAP || safi == SAFI_MPLS_VPN)) || (afi == AFI_L2VPN && safi == SAFI_EVPN)) { /* Tunnel Encap attribute */ bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_ENCAP); #if ENABLE_BGP_VNC_ATTR /* VNC attribute */ bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_VNC); #endif } /* PMSI Tunnel */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PMSI_TUNNEL)) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_PMSI_TUNNEL); stream_putc(s, 9); // Length stream_putc(s, 0); // Flags stream_putc(s, PMSI_TNLTYPE_INGR_REPL); // IR (6) stream_put(s, &(attr->label), BGP_LABEL_BYTES); // MPLS Label / VXLAN VNI stream_put_ipv4(s, attr->nexthop.s_addr); } /* Unknown transit attribute. */ if (attr->transit) stream_put(s, attr->transit->val, attr->transit->length); /* Return total size of attribute. */ return stream_get_endp(s) - cp; }
169,743
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_getdeviceinfo *gdev) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops = nfsd4_layout_ops[gdev->gd_layout_type]; u32 starting_len = xdr->buf->len, needed_len; __be32 *p; dprintk("%s: err %d\n", __func__, be32_to_cpu(nfserr)); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = cpu_to_be32(gdev->gd_layout_type); /* If maxcount is 0 then just update notifications */ if (gdev->gd_maxcount != 0) { nfserr = ops->encode_getdeviceinfo(xdr, gdev); if (nfserr) { /* * We don't bother to burden the layout drivers with * enforcing gd_maxcount, just tell the client to * come back with a bigger buffer if it's not enough. */ if (xdr->buf->len + 4 > gdev->gd_maxcount) goto toosmall; goto out; } } nfserr = nfserr_resource; if (gdev->gd_notify_types) { p = xdr_reserve_space(xdr, 4 + 4); if (!p) goto out; *p++ = cpu_to_be32(1); /* bitmap length */ *p++ = cpu_to_be32(gdev->gd_notify_types); } else { p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = 0; } nfserr = 0; out: kfree(gdev->gd_device); dprintk("%s: done: %d\n", __func__, be32_to_cpu(nfserr)); return nfserr; toosmall: dprintk("%s: maxcount too small\n", __func__); needed_len = xdr->buf->len + 4 /* notifications */; xdr_truncate_encode(xdr, starting_len); p = xdr_reserve_space(xdr, 4); if (!p) { nfserr = nfserr_resource; } else { *p++ = cpu_to_be32(needed_len); nfserr = nfserr_toosmall; } goto out; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_getdeviceinfo *gdev) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops; u32 starting_len = xdr->buf->len, needed_len; __be32 *p; dprintk("%s: err %d\n", __func__, be32_to_cpu(nfserr)); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = cpu_to_be32(gdev->gd_layout_type); /* If maxcount is 0 then just update notifications */ if (gdev->gd_maxcount != 0) { ops = nfsd4_layout_ops[gdev->gd_layout_type]; nfserr = ops->encode_getdeviceinfo(xdr, gdev); if (nfserr) { /* * We don't bother to burden the layout drivers with * enforcing gd_maxcount, just tell the client to * come back with a bigger buffer if it's not enough. */ if (xdr->buf->len + 4 > gdev->gd_maxcount) goto toosmall; goto out; } } nfserr = nfserr_resource; if (gdev->gd_notify_types) { p = xdr_reserve_space(xdr, 4 + 4); if (!p) goto out; *p++ = cpu_to_be32(1); /* bitmap length */ *p++ = cpu_to_be32(gdev->gd_notify_types); } else { p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = 0; } nfserr = 0; out: kfree(gdev->gd_device); dprintk("%s: done: %d\n", __func__, be32_to_cpu(nfserr)); return nfserr; toosmall: dprintk("%s: maxcount too small\n", __func__); needed_len = xdr->buf->len + 4 /* notifications */; xdr_truncate_encode(xdr, starting_len); p = xdr_reserve_space(xdr, 4); if (!p) { nfserr = nfserr_resource; } else { *p++ = cpu_to_be32(needed_len); nfserr = nfserr_toosmall; } goto out; }
168,148
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebsiteSettings::WebsiteSettings( WebsiteSettingsUI* ui, Profile* profile, TabSpecificContentSettings* tab_specific_content_settings, InfoBarService* infobar_service, const GURL& url, const content::SSLStatus& ssl, content::CertStore* cert_store) : TabSpecificContentSettings::SiteDataObserver( tab_specific_content_settings), ui_(ui), infobar_service_(infobar_service), show_info_bar_(false), site_url_(url), site_identity_status_(SITE_IDENTITY_STATUS_UNKNOWN), cert_id_(0), site_connection_status_(SITE_CONNECTION_STATUS_UNKNOWN), cert_store_(cert_store), content_settings_(profile->GetHostContentSettingsMap()), chrome_ssl_host_state_delegate_( ChromeSSLHostStateDelegateFactory::GetForProfile(profile)), did_revoke_user_ssl_decisions_(false) { Init(profile, url, ssl); PresentSitePermissions(); PresentSiteData(); PresentSiteIdentity(); RecordWebsiteSettingsAction(WEBSITE_SETTINGS_OPENED); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID:
WebsiteSettings::WebsiteSettings( WebsiteSettingsUI* ui, Profile* profile, TabSpecificContentSettings* tab_specific_content_settings, content::WebContents* web_contents, const GURL& url, const content::SSLStatus& ssl, content::CertStore* cert_store) : TabSpecificContentSettings::SiteDataObserver( tab_specific_content_settings), ui_(ui), web_contents_(web_contents), show_info_bar_(false), site_url_(url), site_identity_status_(SITE_IDENTITY_STATUS_UNKNOWN), cert_id_(0), site_connection_status_(SITE_CONNECTION_STATUS_UNKNOWN), cert_store_(cert_store), content_settings_(profile->GetHostContentSettingsMap()), chrome_ssl_host_state_delegate_( ChromeSSLHostStateDelegateFactory::GetForProfile(profile)), did_revoke_user_ssl_decisions_(false) { Init(profile, url, ssl); PresentSitePermissions(); PresentSiteData(); PresentSiteIdentity(); RecordWebsiteSettingsAction(WEBSITE_SETTINGS_OPENED); }
171,781
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAMRNBEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_encoder.amrnb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAMR)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (amrParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (amrParams->nChannels != 1 || amrParams->eAMRDTXMode != OMX_AUDIO_AMRDTXModeOff || amrParams->eAMRFrameFormat != OMX_AUDIO_AMRFrameFormatFSF || amrParams->eAMRBandMode < OMX_AUDIO_AMRBandModeNB0 || amrParams->eAMRBandMode > OMX_AUDIO_AMRBandModeNB7) { return OMX_ErrorUndefined; } mBitRate = amrParams->nBitRate; mMode = amrParams->eAMRBandMode - 1; amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } if (pcmParams->nChannels != 1 || pcmParams->nSamplingRate != (OMX_U32)kSampleRate) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAMRNBEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_encoder.amrnb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAMR)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (!isValidOMXParam(amrParams)) { return OMX_ErrorBadParameter; } if (amrParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (amrParams->nChannels != 1 || amrParams->eAMRDTXMode != OMX_AUDIO_AMRDTXModeOff || amrParams->eAMRFrameFormat != OMX_AUDIO_AMRFrameFormatFSF || amrParams->eAMRBandMode < OMX_AUDIO_AMRBandModeNB0 || amrParams->eAMRBandMode > OMX_AUDIO_AMRBandModeNB7) { return OMX_ErrorUndefined; } mBitRate = amrParams->nBitRate; mMode = amrParams->eAMRBandMode - 1; amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } if (pcmParams->nChannels != 1 || pcmParams->nSamplingRate != (OMX_U32)kSampleRate) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,195
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _XcursorThemeInherits (const char *full) { char line[8192]; char *result = NULL; FILE *f; if (!full) return NULL; f = fopen (full, "r"); if (f) { while (fgets (line, sizeof (line), f)) { if (!strncmp (line, "Inherits", 8)) { char *l = line + 8; char *r; while (*l == ' ') l++; if (*l != '=') continue; l++; while (*l == ' ') l++; result = malloc (strlen (l)); if (result) { r = result; while (*l) { while (XcursorSep(*l) || XcursorWhite (*l)) l++; if (!*l) break; if (r != result) *r++ = ':'; while (*l && !XcursorWhite(*l) && !XcursorSep(*l)) *r++ = *l++; } *r++ = '\0'; } break; } } fclose (f); } return result; } Commit Message: CWE ID: CWE-119
_XcursorThemeInherits (const char *full) { char line[8192]; char *result = NULL; FILE *f; if (!full) return NULL; f = fopen (full, "r"); if (f) { while (fgets (line, sizeof (line), f)) { if (!strncmp (line, "Inherits", 8)) { char *l = line + 8; char *r; while (*l == ' ') l++; if (*l != '=') continue; l++; while (*l == ' ') l++; result = malloc (strlen (l) + 1); if (result) { r = result; while (*l) { while (XcursorSep(*l) || XcursorWhite (*l)) l++; if (!*l) break; if (r != result) *r++ = ':'; while (*l && !XcursorWhite(*l) && !XcursorSep(*l)) *r++ = *l++; } *r++ = '\0'; } break; } } fclose (f); } return result; }
165,507