project
stringclasses
633 values
commit_id
stringlengths
7
81
target
int64
0
1
func
stringlengths
5
484k
cwe
stringclasses
131 values
big_vul_idx
float64
0
189k
idx
int64
0
522k
hash
stringlengths
34
39
size
float64
1
24k
message
stringlengths
0
11.5k
dataset
stringclasses
1 value
poppler
9cf2325fb22f812b31858e519411f57747d39bd8
1
GBool SplashFTFont::makeGlyph(int c, int xFrac, int yFrac, SplashGlyphBitmap *bitmap, int x0, int y0, SplashClip *clip, SplashClipResult *clipRes) { SplashFTFontFile *ff; FT_Vector offset; FT_GlyphSlot slot; FT_UInt gid; int rowSize; Guchar *p, *q; int i; ff = (SplashFTFontFile *)fontFile; ff->face->size = sizeObj; offset.x = (FT_Pos)(int)((SplashCoord)xFrac * splashFontFractionMul * 64); offset.y = 0; FT_Set_Transform(ff->face, &matrix, &offset); slot = ff->face->glyph; if (ff->codeToGID && c < ff->codeToGIDLen) { gid = (FT_UInt)ff->codeToGID[c]; } else { gid = (FT_UInt)c; } if (ff->trueType && gid == 0) { // skip the TrueType notdef glyph return gFalse; } // if we have the FT2 bytecode interpreter, autohinting won't be used #ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER if (FT_Load_Glyph(ff->face, gid, aa ? FT_LOAD_NO_BITMAP : FT_LOAD_DEFAULT)) { return gFalse; } #else // FT2's autohinting doesn't always work very well (especially with // font subsets), so turn it off if anti-aliasing is enabled; if // anti-aliasing is disabled, this seems to be a tossup - some fonts // look better with hinting, some without, so leave hinting on if (FT_Load_Glyph(ff->face, gid, aa ? FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP : FT_LOAD_DEFAULT)) { return gFalse; } #endif FT_Glyph_Metrics *glyphMetrics = &(ff->face->glyph->metrics); // prelimirary values from FT_Glyph_Metrics bitmap->x = splashRound(-glyphMetrics->horiBearingX / 64.0); bitmap->y = splashRound(glyphMetrics->horiBearingY / 64.0); bitmap->w = splashRound(glyphMetrics->width / 64.0); bitmap->h = splashRound(glyphMetrics->height / 64.0); *clipRes = clip->testRect(x0 - bitmap->x, y0 - bitmap->y, x0 - bitmap->x + bitmap->w, y0 - bitmap->y + bitmap->h); if (*clipRes == splashClipAllOutside) { bitmap->freeData = gFalse; return gTrue; } if (FT_Render_Glyph(slot, aa ? ft_render_mode_normal : ft_render_mode_mono)) { return gFalse; } bitmap->x = -slot->bitmap_left; bitmap->y = slot->bitmap_top; bitmap->w = slot->bitmap.width; bitmap->h = slot->bitmap.rows; bitmap->aa = aa; if (aa) { rowSize = bitmap->w; } else { rowSize = (bitmap->w + 7) >> 3; } bitmap->data = (Guchar *)gmalloc(rowSize * bitmap->h); bitmap->freeData = gTrue; for (i = 0, p = bitmap->data, q = slot->bitmap.buffer; i < bitmap->h; ++i, p += rowSize, q += slot->bitmap.pitch) { memcpy(p, q, rowSize); } return gTrue; }
nan
null
10,735
320507127576760393617432982959447579733
87
More gmalloc → gmallocn
null
qemu
93060258ae748573ca7197204125a2670047896d
1
static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt) { struct iovec *l2_hdr, *l3_hdr; size_t bytes_read; size_t full_ip6hdr_len; uint16_t l3_proto; assert(pkt); l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG]; l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG]; bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base, ETH_MAX_L2_HDR_LEN); if (bytes_read < sizeof(struct eth_header)) { l2_hdr->iov_len = 0; return false; } l2_hdr->iov_len = sizeof(struct eth_header); switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) { case ETH_P_VLAN: l2_hdr->iov_len += sizeof(struct vlan_header); break; case ETH_P_DVLAN: l2_hdr->iov_len += 2 * sizeof(struct vlan_header); break; } if (bytes_read < l2_hdr->iov_len) { l2_hdr->iov_len = 0; return false; } l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len); switch (l3_proto) { case ETH_P_IP: l3_hdr->iov_base = g_malloc(ETH_MAX_IP4_HDR_LEN); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, sizeof(struct ip_header)); if (bytes_read < sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base); pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p; /* copy optional IPv4 header data */ bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len + sizeof(struct ip_header), l3_hdr->iov_base + sizeof(struct ip_header), l3_hdr->iov_len - sizeof(struct ip_header)); if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } break; case ETH_P_IPV6: if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, &pkt->l4proto, &full_ip6hdr_len)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_base = g_malloc(full_ip6hdr_len); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, full_ip6hdr_len); if (bytes_read < full_ip6hdr_len) { l3_hdr->iov_len = 0; return false; } else { l3_hdr->iov_len = full_ip6hdr_len; } break; default: l3_hdr->iov_len = 0; break; } vmxnet_tx_pkt_calculate_hdr_len(pkt); pkt->packet_type = get_eth_packet_type(l2_hdr->iov_base); return true; }
nan
null
10,737
279902556539940055235183485480577059732
91
net: vmxnet: check IP header length Vmxnet3 device emulator when parsing packet headers does not check for IP header length. It could lead to a OOB access when reading further packet data. Add check to avoid it. Reported-by: Li Qiang <liqiang6-s@360.cn> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Reviewed-by: Dmitry Fleytman <dmitry@daynix.com> Signed-off-by: Michael Roth <mdroth@linux.vnet.ibm.com>
null
qemu
167d97a3def77ee2dbf6e908b0ecbfe2103977db
1
static void vmsvga_fifo_run(struct vmsvga_state_s *s) { uint32_t cmd, colour; int args, len, maxloop = 1024; int x, y, dx, dy, width, height; struct vmsvga_cursor_definition_s cursor; uint32_t cmd_start; len = vmsvga_fifo_length(s); while (len > 0 && --maxloop > 0) { /* May need to go back to the start of the command if incomplete */ cmd_start = s->fifo_stop; switch (cmd = vmsvga_fifo_read(s)) { case SVGA_CMD_UPDATE: case SVGA_CMD_UPDATE_VERBOSE: len -= 5; if (len < 0) { goto rewind; } x = vmsvga_fifo_read(s); y = vmsvga_fifo_read(s); width = vmsvga_fifo_read(s); height = vmsvga_fifo_read(s); vmsvga_update_rect_delayed(s, x, y, width, height); break; case SVGA_CMD_RECT_FILL: len -= 6; if (len < 0) { goto rewind; } colour = vmsvga_fifo_read(s); x = vmsvga_fifo_read(s); y = vmsvga_fifo_read(s); width = vmsvga_fifo_read(s); height = vmsvga_fifo_read(s); #ifdef HW_FILL_ACCEL if (vmsvga_fill_rect(s, colour, x, y, width, height) == 0) { break; } #endif args = 0; goto badcmd; case SVGA_CMD_RECT_COPY: len -= 7; if (len < 0) { goto rewind; } x = vmsvga_fifo_read(s); y = vmsvga_fifo_read(s); dx = vmsvga_fifo_read(s); dy = vmsvga_fifo_read(s); width = vmsvga_fifo_read(s); height = vmsvga_fifo_read(s); #ifdef HW_RECT_ACCEL if (vmsvga_copy_rect(s, x, y, dx, dy, width, height) == 0) { break; } #endif args = 0; goto badcmd; case SVGA_CMD_DEFINE_CURSOR: len -= 8; if (len < 0) { goto rewind; } cursor.id = vmsvga_fifo_read(s); cursor.hot_x = vmsvga_fifo_read(s); cursor.hot_y = vmsvga_fifo_read(s); cursor.width = x = vmsvga_fifo_read(s); cursor.height = y = vmsvga_fifo_read(s); vmsvga_fifo_read(s); cursor.bpp = vmsvga_fifo_read(s); args = SVGA_BITMAP_SIZE(x, y) + SVGA_PIXMAP_SIZE(x, y, cursor.bpp); if (cursor.width > 256 || cursor.height > 256 || cursor.bpp > 32 || SVGA_BITMAP_SIZE(x, y) > sizeof cursor.mask || SVGA_PIXMAP_SIZE(x, y, cursor.bpp) > sizeof cursor.image) { goto badcmd; } len -= args; if (len < 0) { goto rewind; } for (args = 0; args < SVGA_BITMAP_SIZE(x, y); args++) { cursor.mask[args] = vmsvga_fifo_read_raw(s); } for (args = 0; args < SVGA_PIXMAP_SIZE(x, y, cursor.bpp); args++) { cursor.image[args] = vmsvga_fifo_read_raw(s); } #ifdef HW_MOUSE_ACCEL vmsvga_cursor_define(s, &cursor); break; #else args = 0; goto badcmd; #endif /* * Other commands that we at least know the number of arguments * for so we can avoid FIFO desync if driver uses them illegally. */ case SVGA_CMD_DEFINE_ALPHA_CURSOR: len -= 6; if (len < 0) { goto rewind; } vmsvga_fifo_read(s); vmsvga_fifo_read(s); vmsvga_fifo_read(s); x = vmsvga_fifo_read(s); y = vmsvga_fifo_read(s); args = x * y; goto badcmd; case SVGA_CMD_RECT_ROP_FILL: args = 6; goto badcmd; case SVGA_CMD_RECT_ROP_COPY: args = 7; goto badcmd; case SVGA_CMD_DRAW_GLYPH_CLIPPED: len -= 4; if (len < 0) { goto rewind; } vmsvga_fifo_read(s); vmsvga_fifo_read(s); args = 7 + (vmsvga_fifo_read(s) >> 2); goto badcmd; case SVGA_CMD_SURFACE_ALPHA_BLEND: args = 12; goto badcmd; /* * Other commands that are not listed as depending on any * CAPABILITIES bits, but are not described in the README either. */ case SVGA_CMD_SURFACE_FILL: case SVGA_CMD_SURFACE_COPY: case SVGA_CMD_FRONT_ROP_FILL: case SVGA_CMD_FENCE: case SVGA_CMD_INVALID_CMD: break; /* Nop */ default: args = 0; badcmd: len -= args; if (len < 0) { goto rewind; } while (args--) { vmsvga_fifo_read(s); } printf("%s: Unknown command 0x%02x in SVGA command FIFO\n", __func__, cmd); break; rewind: s->fifo_stop = cmd_start; s->fifo[SVGA_FIFO_STOP] = cpu_to_le32(s->fifo_stop); break; } } s->syncing = 0; }
nan
null
10,738
133450826690414793801144499382261523494
178
vmsvga: correct bitmap and pixmap size checks When processing svga command DEFINE_CURSOR in vmsvga_fifo_run, the computed BITMAP and PIXMAP size are checked against the 'cursor.mask[]' and 'cursor.image[]' array sizes in bytes. Correct these checks to avoid OOB memory access. Reported-by: Qinghao Tang <luodalongde@gmail.com> Reported-by: Li Qiang <liqiang6-s@360.cn> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Message-id: 1473338754-15430-1-git-send-email-ppandit@redhat.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>
null
php-src
523f230c831d7b33353203fa34aee4e92ac12bba
1
php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, char **opened_path, php_stream_context *context, int redirect_max, int flags STREAMS_DC TSRMLS_DC) /* {{{ */ { php_stream *stream = NULL; php_url *resource = NULL; int use_ssl; int use_proxy = 0; char *scratch = NULL; char *tmp = NULL; char *ua_str = NULL; zval **ua_zval = NULL, **tmpzval = NULL, *ssl_proxy_peer_name = NULL; int scratch_len = 0; int body = 0; char location[HTTP_HEADER_BLOCK_SIZE]; zval *response_header = NULL; int reqok = 0; char *http_header_line = NULL; char tmp_line[128]; size_t chunk_size = 0, file_size = 0; int eol_detect = 0; char *transport_string, *errstr = NULL; int transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0; char *protocol_version = NULL; int protocol_version_len = 3; /* Default: "1.0" */ struct timeval timeout; char *user_headers = NULL; int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0); int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0); int follow_location = 1; php_stream_filter *transfer_encoding = NULL; int response_code; tmp_line[0] = '\0'; if (redirect_max < 1) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting"); return NULL; } resource = php_url_parse(path); if (resource == NULL) { return NULL; } if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) { if (!context || php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE || Z_TYPE_PP(tmpzval) != IS_STRING || Z_STRLEN_PP(tmpzval) <= 0) { php_url_free(resource); return php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context); } /* Called from a non-http wrapper with http proxying requested (i.e. ftp) */ request_fulluri = 1; use_ssl = 0; use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { /* Normal http request (possibly with proxy) */ if (strpbrk(mode, "awx+")) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections"); php_url_free(resource); return NULL; } use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's'; /* choose default ports */ if (use_ssl && resource->port == 0) resource->port = 443; else if (resource->port == 0) resource->port = 80; if (context && php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port); } } if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval); timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000); } else { timeout.tv_sec = FG(default_socket_timeout); timeout.tv_usec = 0; } stream = php_stream_xport_create(transport_string, transport_len, options, STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT, NULL, &timeout, context, &errstr, NULL); if (stream) { php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout); } if (errstr) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr); efree(errstr); errstr = NULL; } efree(transport_string); if (stream && use_proxy && use_ssl) { smart_str header = {0}; /* Set peer_name or name verification will try to use the proxy server name */ if (!context || php_stream_context_get_option(context, "ssl", "peer_name", &tmpzval) == FAILURE) { MAKE_STD_ZVAL(ssl_proxy_peer_name); ZVAL_STRING(ssl_proxy_peer_name, resource->host, 1); php_stream_context_set_option(stream->context, "ssl", "peer_name", ssl_proxy_peer_name); } smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1); smart_str_appends(&header, resource->host); smart_str_appendc(&header, ':'); smart_str_append_unsigned(&header, resource->port); smart_str_appendl(&header, " HTTP/1.0\r\n", sizeof(" HTTP/1.0\r\n")-1); /* check if we have Proxy-Authorization header */ if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) { char *s, *p; if (Z_TYPE_PP(tmpzval) == IS_ARRAY) { HashPosition pos; zval **tmpheader = NULL; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos); SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos); zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)) { if (Z_TYPE_PP(tmpheader) == IS_STRING) { s = Z_STRVAL_PP(tmpheader); do { while (*s == ' ' || *s == '\t') s++; p = s; while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++; if (*p == ':') { p++; if (p - s == sizeof("Proxy-Authorization:") - 1 && zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1, "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) { while (*p != 0 && *p != '\r' && *p !='\n') p++; smart_str_appendl(&header, s, p - s); smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); goto finish; } else { while (*p != 0 && *p != '\r' && *p !='\n') p++; } } s = p; while (*s == '\r' || *s == '\n') s++; } while (*s != 0); } } } else if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { s = Z_STRVAL_PP(tmpzval); do { while (*s == ' ' || *s == '\t') s++; p = s; while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++; if (*p == ':') { p++; if (p - s == sizeof("Proxy-Authorization:") - 1 && zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1, "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) { while (*p != 0 && *p != '\r' && *p !='\n') p++; smart_str_appendl(&header, s, p - s); smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); goto finish; } else { while (*p != 0 && *p != '\r' && *p !='\n') p++; } } s = p; while (*s == '\r' || *s == '\n') s++; } while (*s != 0); } } finish: smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); if (php_stream_write(stream, header.c, header.len) != header.len) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } smart_str_free(&header); if (stream) { char header_line[HTTP_HEADER_BLOCK_SIZE]; /* get response header */ while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) { if (header_line[0] == '\n' || header_line[0] == '\r' || header_line[0] == '\0') { break; } } } /* enable SSL transport layer */ if (stream) { if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 || php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } } } if (stream == NULL) goto out; /* avoid buffering issues while reading header */ if (options & STREAM_WILL_CAST) chunk_size = php_stream_set_chunk_size(stream, 1); /* avoid problems with auto-detecting when reading the headers -> the headers * are always in canonical \r\n format */ eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); php_stream_context_set(stream, context); php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0); if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); redirect_max = Z_LVAL_PP(tmpzval); } if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) { if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { /* As per the RFC, automatically redirected requests MUST NOT use other methods than * GET and HEAD unless it can be confirmed by the user */ if (!redirected || (Z_STRLEN_PP(tmpzval) == 3 && memcmp("GET", Z_STRVAL_PP(tmpzval), 3) == 0) || (Z_STRLEN_PP(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_PP(tmpzval), 4) == 0) ) { scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval); scratch = emalloc(scratch_len); strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1); strncat(scratch, " ", 1); } } } if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval)); } if (!scratch) { scratch_len = strlen(path) + 29 + protocol_version_len; scratch = emalloc(scratch_len); strncpy(scratch, "GET ", scratch_len); } /* Should we send the entire path in the request line, default to no. */ if (!request_fulluri && context && php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) { zval ztmp = **tmpzval; zval_copy_ctor(&ztmp); convert_to_boolean(&ztmp); request_fulluri = Z_BVAL(ztmp) ? 1 : 0; zval_dtor(&ztmp); } if (request_fulluri) { /* Ask for everything */ strcat(scratch, path); } else { /* Send the traditional /path/to/file?query_string */ /* file */ if (resource->path && *resource->path) { strlcat(scratch, resource->path, scratch_len); } else { strlcat(scratch, "/", scratch_len); } /* query string */ if (resource->query) { strlcat(scratch, "?", scratch_len); strlcat(scratch, resource->query, scratch_len); } } /* protocol version we are speaking */ if (protocol_version) { strlcat(scratch, " HTTP/", scratch_len); strlcat(scratch, protocol_version, scratch_len); strlcat(scratch, "\r\n", scratch_len); } else { strlcat(scratch, " HTTP/1.0\r\n", scratch_len); } /* send it */ php_stream_write(stream, scratch, strlen(scratch)); if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) { tmp = NULL; if (Z_TYPE_PP(tmpzval) == IS_ARRAY) { HashPosition pos; zval **tmpheader = NULL; smart_str tmpstr = {0}; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos); SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos); zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos) ) { if (Z_TYPE_PP(tmpheader) == IS_STRING) { smart_str_appendl(&tmpstr, Z_STRVAL_PP(tmpheader), Z_STRLEN_PP(tmpheader)); smart_str_appendl(&tmpstr, "\r\n", sizeof("\r\n") - 1); } } smart_str_0(&tmpstr); /* Remove newlines and spaces from start and end. there's at least one extra \r\n at the end that needs to go. */ if (tmpstr.c) { tmp = php_trim(tmpstr.c, strlen(tmpstr.c), NULL, 0, NULL, 3 TSRMLS_CC); smart_str_free(&tmpstr); } } if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { /* Remove newlines and spaces from start and end php_trim will estrndup() */ tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC); } if (tmp && strlen(tmp) > 0) { char *s; user_headers = estrdup(tmp); /* Make lowercase for easy comparison against 'standard' headers */ php_strtolower(tmp, strlen(tmp)); if (!header_init) { /* strip POST headers on redirect */ strip_header(user_headers, tmp, "content-length:"); strip_header(user_headers, tmp, "content-type:"); } if ((s = strstr(tmp, "user-agent:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_USER_AGENT; } if ((s = strstr(tmp, "host:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_HOST; } if ((s = strstr(tmp, "from:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_FROM; } if ((s = strstr(tmp, "authorization:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_AUTH; } if ((s = strstr(tmp, "content-length:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_CONTENT_LENGTH; } if ((s = strstr(tmp, "content-type:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_TYPE; } if ((s = strstr(tmp, "connection:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_CONNECTION; } /* remove Proxy-Authorization header */ if (use_proxy && use_ssl && (s = strstr(tmp, "proxy-authorization:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { char *p = s + sizeof("proxy-authorization:") - 1; while (s > tmp && (*(s-1) == ' ' || *(s-1) == '\t')) s--; while (*p != 0 && *p != '\r' && *p != '\n') p++; while (*p == '\r' || *p == '\n') p++; if (*p == 0) { if (s == tmp) { efree(user_headers); user_headers = NULL; } else { while (s > tmp && (*(s-1) == '\r' || *(s-1) == '\n')) s--; user_headers[s - tmp] = 0; } } else { memmove(user_headers + (s - tmp), user_headers + (p - tmp), strlen(p) + 1); } } } if (tmp) { efree(tmp); } } /* auth header if it was specified */ if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) { /* decode the strings first */ php_url_decode(resource->user, strlen(resource->user)); /* scratch is large enough, since it was made large enough for the whole URL */ strcpy(scratch, resource->user); strcat(scratch, ":"); /* Note: password is optional! */ if (resource->pass) { php_url_decode(resource->pass, strlen(resource->pass)); strcat(scratch, resource->pass); } tmp = (char*)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL); if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) { php_stream_write(stream, scratch, strlen(scratch)); php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0); } efree(tmp); tmp = NULL; } /* if the user has configured who they are, send a From: line */ if (((have_header & HTTP_HEADER_FROM) == 0) && FG(from_address)) { if (snprintf(scratch, scratch_len, "From: %s\r\n", FG(from_address)) > 0) php_stream_write(stream, scratch, strlen(scratch)); } /* Send Host: header so name-based virtual hosts work */ if ((have_header & HTTP_HEADER_HOST) == 0) { if ((use_ssl && resource->port != 443 && resource->port != 0) || (!use_ssl && resource->port != 80 && resource->port != 0)) { if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0) php_stream_write(stream, scratch, strlen(scratch)); } else { if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) { php_stream_write(stream, scratch, strlen(scratch)); } } } /* Send a Connection: close header to avoid hanging when the server * interprets the RFC literally and establishes a keep-alive connection, * unless the user specifically requests something else by specifying a * Connection header in the context options. Send that header even for * HTTP/1.0 to avoid issues when the server respond with a HTTP/1.1 * keep-alive response, which is the preferred response type. */ if ((have_header & HTTP_HEADER_CONNECTION) == 0) { php_stream_write_string(stream, "Connection: close\r\n"); } if (context && php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS && Z_TYPE_PP(ua_zval) == IS_STRING) { ua_str = Z_STRVAL_PP(ua_zval); } else if (FG(user_agent)) { ua_str = FG(user_agent); } if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) { #define _UA_HEADER "User-Agent: %s\r\n" char *ua; size_t ua_len; ua_len = sizeof(_UA_HEADER) + strlen(ua_str); /* ensure the header is only sent if user_agent is not blank */ if (ua_len > sizeof(_UA_HEADER)) { ua = emalloc(ua_len + 1); if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) { ua[ua_len] = 0; php_stream_write(stream, ua, ua_len); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header"); } if (ua) { efree(ua); } } } if (user_headers) { /* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first. */ if ( header_init && context && !(have_header & HTTP_HEADER_CONTENT_LENGTH) && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0 ) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); have_header |= HTTP_HEADER_CONTENT_LENGTH; } php_stream_write(stream, user_headers, strlen(user_headers)); php_stream_write(stream, "\r\n", sizeof("\r\n")-1); efree(user_headers); } /* Request content, such as for POST requests */ if (header_init && context && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); } if (!(have_header & HTTP_HEADER_TYPE)) { php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n", sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1); php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded"); } php_stream_write(stream, "\r\n", sizeof("\r\n")-1); php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { php_stream_write(stream, "\r\n", sizeof("\r\n")-1); } location[0] = '\0'; if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (header_init) { zval *ztmp; MAKE_STD_ZVAL(ztmp); array_init(ztmp); ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", ztmp); } { zval **rh; if(zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh) != SUCCESS || Z_TYPE_PP(rh) != IS_ARRAY) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, http_response_header overwritten"); goto out; } response_header = *rh; Z_ADDREF_P(response_header); } if (!php_stream_eof(stream)) { size_t tmp_line_len; /* get response header */ if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) { zval *http_response; if (tmp_line_len > 9) { response_code = atoi(tmp_line + 9); } else { response_code = 0; } if (context && SUCCESS==php_stream_context_get_option(context, "http", "ignore_errors", &tmpzval)) { ignore_errors = zend_is_true(*tmpzval); } /* when we request only the header, don't fail even on error codes */ if ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) { reqok = 1; } /* status codes of 1xx are "informational", and will be followed by a real response * e.g "100 Continue". RFC 7231 states that unexpected 1xx status MUST be parsed, * and MAY be ignored. As such, we need to skip ahead to the "real" status*/ if (response_code >= 100 && response_code < 200) { /* consume lines until we find a line starting 'HTTP/1' */ while ( !php_stream_eof(stream) && php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL && ( tmp_line_len < sizeof("HTTP/1") - 1 || strncasecmp(tmp_line, "HTTP/1", sizeof("HTTP/1") - 1) ) ); if (tmp_line_len > 9) { response_code = atoi(tmp_line + 9); } else { response_code = 0; } } /* all status codes in the 2xx range are defined by the specification as successful; * all status codes in the 3xx range are for redirection, and so also should never * fail */ if (response_code >= 200 && response_code < 400) { reqok = 1; } else { switch(response_code) { case 403: php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT, tmp_line, response_code); break; default: /* safety net in the event tmp_line == NULL */ if (!tmp_line_len) { tmp_line[0] = '\0'; } php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE, tmp_line, response_code); } } if (tmp_line[tmp_line_len - 1] == '\n') { --tmp_line_len; if (tmp_line[tmp_line_len - 1] == '\r') { --tmp_line_len; } } MAKE_STD_ZVAL(http_response); ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL); } } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!"); goto out; } /* read past HTTP headers */ http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE); while (!body && !php_stream_eof(stream)) { size_t http_header_line_length; if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') { char *e = http_header_line + http_header_line_length - 1; if (*e != '\n') { do { /* partial header */ if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Failed to read HTTP headers"); goto out; } e = http_header_line + http_header_line_length - 1; } while (*e != '\n'); continue; } while (*e == '\n' || *e == '\r') { e--; } http_header_line_length = e - http_header_line + 1; http_header_line[http_header_line_length] = '\0'; if (!strncasecmp(http_header_line, "Location: ", 10)) { if (context && php_stream_context_get_option(context, "http", "follow_location", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); follow_location = Z_LVAL_PP(tmpzval); } else if (!(response_code >= 300 && response_code < 304 || 307 == response_code || 308 == response_code)) { /* we shouldn't redirect automatically if follow_location isn't set and response_code not in (300, 301, 302, 303 and 307) see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1 RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */ follow_location = 0; } strlcpy(location, http_header_line + 10, sizeof(location)); } else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) { php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0); } else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) { file_size = atoi(http_header_line + 16); php_stream_notify_file_size(context, file_size, http_header_line, 0); } else if (!strncasecmp(http_header_line, "Transfer-Encoding: chunked", sizeof("Transfer-Encoding: chunked"))) { /* create filter to decode response body */ if (!(options & STREAM_ONLY_GET_HEADERS)) { long decode = 1; if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_boolean(*tmpzval); decode = Z_LVAL_PP(tmpzval); } if (decode) { transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC); if (transfer_encoding) { /* don't store transfer-encodeing header */ continue; } } } } if (http_header_line[0] == '\0') { body = 1; } else { zval *http_header; MAKE_STD_ZVAL(http_header); ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL); } } else { break; } } if (!reqok || (location[0] != '\0' && follow_location)) { if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) { goto out; } if (location[0] != '\0') php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0); php_stream_close(stream); stream = NULL; if (location[0] != '\0') { char new_path[HTTP_HEADER_BLOCK_SIZE]; char loc_path[HTTP_HEADER_BLOCK_SIZE]; *new_path='\0'; if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) && strncasecmp(location, "https://", sizeof("https://")-1) && strncasecmp(location, "ftp://", sizeof("ftp://")-1) && strncasecmp(location, "ftps://", sizeof("ftps://")-1))) { if (*location != '/') { if (*(location+1) != '\0' && resource->path) { char *s = strrchr(resource->path, '/'); if (!s) { s = resource->path; if (!s[0]) { efree(s); s = resource->path = estrdup("/"); } else { *s = '/'; } } s[1] = '\0'; if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') { snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location); } else { snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location); } } else { snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location); } } else { strlcpy(loc_path, location, sizeof(loc_path)); } if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) { snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path); } else { snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path); } } else { strlcpy(new_path, location, sizeof(new_path)); } php_url_free(resource); /* check for invalid redirection URLs */ if ((resource = php_url_parse(new_path)) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); goto out; } #define CHECK_FOR_CNTRL_CHARS(val) { \ if (val) { \ unsigned char *s, *e; \ int l; \ l = php_url_decode(val, strlen(val)); \ s = (unsigned char*)val; e = s + l; \ while (s < e) { \ if (iscntrl(*s)) { \ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); \ goto out; \ } \ s++; \ } \ } \ } /* check for control characters in login, password & path */ if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) { CHECK_FOR_CNTRL_CHARS(resource->user) CHECK_FOR_CNTRL_CHARS(resource->pass) CHECK_FOR_CNTRL_CHARS(resource->path) } stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC); } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed! %s", tmp_line); } } out: if (protocol_version) { efree(protocol_version); } if (http_header_line) { efree(http_header_line); } if (scratch) { efree(scratch); } if (resource) { php_url_free(resource); } if (stream) { if (header_init) { stream->wrapperdata = response_header; } else { if(response_header) { Z_DELREF_P(response_header); } } php_stream_notify_progress_init(context, 0, file_size); /* Restore original chunk size now that we're done with headers */ if (options & STREAM_WILL_CAST) php_stream_set_chunk_size(stream, chunk_size); /* restore the users auto-detect-line-endings setting */ stream->flags |= eol_detect; /* as far as streams are concerned, we are now at the start of * the stream */ stream->position = 0; /* restore mode */ strlcpy(stream->mode, mode, sizeof(stream->mode)); if (transfer_encoding) { php_stream_filter_append(&stream->readfilters, transfer_encoding); } } else { if(response_header) { Z_DELREF_P(response_header); } if (transfer_encoding) { php_stream_filter_free(transfer_encoding TSRMLS_CC); } } return stream; }
nan
null
10,739
79315660875678487053158330706317435509
865
Fix bug #75981: prevent reading beyond buffer start
null
qemu
dd248ed7e204ee8a1873914e02b8b526e8f1b80d
1
static void virtio_gpu_set_scanout(VirtIOGPU *g, struct virtio_gpu_ctrl_command *cmd) { struct virtio_gpu_simple_resource *res; struct virtio_gpu_scanout *scanout; pixman_format_code_t format; uint32_t offset; int bpp; struct virtio_gpu_set_scanout ss; VIRTIO_GPU_FILL_CMD(ss); trace_virtio_gpu_cmd_set_scanout(ss.scanout_id, ss.resource_id, ss.r.width, ss.r.height, ss.r.x, ss.r.y); if (ss.scanout_id >= g->conf.max_outputs) { qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout id specified %d", __func__, ss.scanout_id); cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID; return; } g->enable = 1; if (ss.resource_id == 0) { scanout = &g->scanout[ss.scanout_id]; if (scanout->resource_id) { res = virtio_gpu_find_resource(g, scanout->resource_id); if (res) { res->scanout_bitmask &= ~(1 << ss.scanout_id); } } if (ss.scanout_id == 0) { qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout id specified %d", __func__, ss.scanout_id); cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID; return; } dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, NULL); scanout->ds = NULL; scanout->width = 0; scanout->height = 0; return; } /* create a surface for this scanout */ res = virtio_gpu_find_resource(g, ss.resource_id); if (!res) { qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal resource specified %d\n", __func__, ss.resource_id); cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID; return; } if (ss.r.x > res->width || ss.r.y > res->height || ss.r.width > res->width || ss.r.height > res->height || ss.r.x + ss.r.width > res->width || ss.r.y + ss.r.height > res->height) { qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout %d bounds for" " resource %d, (%d,%d)+%d,%d vs %d %d\n", __func__, ss.scanout_id, ss.resource_id, ss.r.x, ss.r.y, ss.r.width, ss.r.height, res->width, res->height); cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER; return; } scanout = &g->scanout[ss.scanout_id]; format = pixman_image_get_format(res->image); bpp = (PIXMAN_FORMAT_BPP(format) + 7) / 8; offset = (ss.r.x * bpp) + ss.r.y * pixman_image_get_stride(res->image); if (!scanout->ds || surface_data(scanout->ds) != ((uint8_t *)pixman_image_get_data(res->image) + offset) || scanout->width != ss.r.width || scanout->height != ss.r.height) { pixman_image_t *rect; void *ptr = (uint8_t *)pixman_image_get_data(res->image) + offset; rect = pixman_image_create_bits(format, ss.r.width, ss.r.height, ptr, pixman_image_get_stride(res->image)); pixman_image_ref(res->image); pixman_image_set_destroy_function(rect, virtio_unref_resource, res->image); /* realloc the surface ptr */ scanout->ds = qemu_create_displaysurface_pixman(rect); if (!scanout->ds) { cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC; return; } dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, scanout->ds); } res->scanout_bitmask |= (1 << ss.scanout_id); scanout->resource_id = ss.resource_id; scanout->x = ss.r.x; scanout->y = ss.r.y; scanout->width = ss.r.width; scanout->height = ss.r.height; }
nan
null
10,740
280786379160405414494226432616391096943
99
virtio-gpu: fix memory leak in set scanout In virtio_gpu_set_scanout function, when creating the 'rect' its refcount is set to 2, by pixman_image_create_bits and qemu_create_displaysurface_pixman function. This can lead a memory leak issues. This patch avoid this issue. Signed-off-by: Li Qiang <liqiang6-s@360.cn> Reviewed-by: Marc-André Lureau <marcandre.lureau@redhat.com> Message-id: 5884626f.5b2f6b0a.1bfff.3037@mx.google.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>
null
pngquant
b7c217680cda02dddced245d237ebe8c383be285
1
static pngquant_error rwpng_read_image24_libpng(FILE *infile, png24_image *mainprog_ptr, int verbose) { png_structp png_ptr = NULL; png_infop info_ptr = NULL; png_size_t rowbytes; int color_type, bit_depth; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, rwpng_error_handler, verbose ? rwpng_warning_stderr_handler : rwpng_warning_silent_handler); if (!png_ptr) { return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ } /* setjmp() must be called in every function that calls a non-trivial * libpng function */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return LIBPNG_FATAL_ERROR; /* fatal libpng error (via longjmp()) */ } #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) png_set_option(png_ptr, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif #if PNG_LIBPNG_VER >= 10500 && defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* copy standard chunks too */ png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_IF_SAFE, (png_const_bytep)"pHYs\0iTXt\0tEXt\0zTXt", 4); #endif png_set_read_user_chunk_fn(png_ptr, &mainprog_ptr->chunks, read_chunk_callback); struct rwpng_read_data read_data = {infile, 0}; png_set_read_fn(png_ptr, &read_data, user_read_data); png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ /* alternatively, could make separate calls to png_get_image_width(), * etc., but want bit_depth and color_type for later [don't care about * compression_type and filter_type => NULLs] */ png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width, &mainprog_ptr->height, &bit_depth, &color_type, NULL, NULL, NULL); // For overflow safety reject images that won't fit in 32-bit if (mainprog_ptr->width > INT_MAX/mainprog_ptr->height) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return PNG_OUT_OF_MEMORY_ERROR; /* not quite true, but whatever */ } /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits, * transparency chunks to full alpha channel; strip 16-bit-per-sample * images to 8 bits per sample; and convert grayscale to RGB[A] */ /* GRR TO DO: preserve all safe-to-copy ancillary PNG chunks */ if (!(color_type & PNG_COLOR_MASK_ALPHA)) { #ifdef PNG_READ_FILLER_SUPPORTED png_set_expand(png_ptr); png_set_filler(png_ptr, 65535L, PNG_FILLER_AFTER); #else fprintf(stderr, "pngquant readpng: image is neither RGBA nor GA\n"); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->retval = WRONG_INPUT_COLOR_TYPE; return mainprog_ptr->retval; #endif } if (bit_depth == 16) { png_set_strip_16(png_ptr); } if (!(color_type & PNG_COLOR_MASK_COLOR)) { png_set_gray_to_rgb(png_ptr); } /* get source gamma for gamma correction, or use sRGB default */ double gamma = 0.45455; if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) { mainprog_ptr->input_color = RWPNG_SRGB; mainprog_ptr->output_color = RWPNG_SRGB; } else { png_get_gAMA(png_ptr, info_ptr, &gamma); if (gamma > 0 && gamma <= 1.0) { mainprog_ptr->input_color = RWPNG_GAMA_ONLY; mainprog_ptr->output_color = RWPNG_GAMA_ONLY; } else { fprintf(stderr, "pngquant readpng: ignored out-of-range gamma %f\n", gamma); mainprog_ptr->input_color = RWPNG_NONE; mainprog_ptr->output_color = RWPNG_NONE; gamma = 0.45455; } } mainprog_ptr->gamma = gamma; png_set_interlace_handling(png_ptr); /* all transformations have been registered; now update info_ptr data, * get rowbytes and channels, and allocate image memory */ png_read_update_info(png_ptr, info_ptr); rowbytes = png_get_rowbytes(png_ptr, info_ptr); if ((mainprog_ptr->rgba_data = malloc(rowbytes * mainprog_ptr->height)) == NULL) { fprintf(stderr, "pngquant readpng: unable to allocate image data\n"); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return PNG_OUT_OF_MEMORY_ERROR; } png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0); /* now we can go ahead and just read the whole image */ png_read_image(png_ptr, row_pointers); /* and we're done! (png_read_end() can be omitted if no processing of * post-IDAT text/time/etc. is desired) */ png_read_end(png_ptr, NULL); #if USE_LCMS #if PNG_LIBPNG_VER < 10500 png_charp ProfileData; #else png_bytep ProfileData; #endif png_uint_32 ProfileLen; cmsHPROFILE hInProfile = NULL; /* color_type is read from the image before conversion to RGBA */ int COLOR_PNG = color_type & PNG_COLOR_MASK_COLOR; /* embedded ICC profile */ if (png_get_iCCP(png_ptr, info_ptr, &(png_charp){0}, &(int){0}, &ProfileData, &ProfileLen)) { hInProfile = cmsOpenProfileFromMem(ProfileData, ProfileLen); cmsColorSpaceSignature colorspace = cmsGetColorSpace(hInProfile); /* only RGB (and GRAY) valid for PNGs */ if (colorspace == cmsSigRgbData && COLOR_PNG) { mainprog_ptr->input_color = RWPNG_ICCP; mainprog_ptr->output_color = RWPNG_SRGB; } else { if (colorspace == cmsSigGrayData && !COLOR_PNG) { mainprog_ptr->input_color = RWPNG_ICCP_WARN_GRAY; mainprog_ptr->output_color = RWPNG_SRGB; } cmsCloseProfile(hInProfile); hInProfile = NULL; } } /* build RGB profile from cHRM and gAMA */ if (hInProfile == NULL && COLOR_PNG && !png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB) && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) && png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) { cmsCIExyY WhitePoint; cmsCIExyYTRIPLE Primaries; png_get_cHRM(png_ptr, info_ptr, &WhitePoint.x, &WhitePoint.y, &Primaries.Red.x, &Primaries.Red.y, &Primaries.Green.x, &Primaries.Green.y, &Primaries.Blue.x, &Primaries.Blue.y); WhitePoint.Y = Primaries.Red.Y = Primaries.Green.Y = Primaries.Blue.Y = 1.0; cmsToneCurve *GammaTable[3]; GammaTable[0] = GammaTable[1] = GammaTable[2] = cmsBuildGamma(NULL, 1/gamma); hInProfile = cmsCreateRGBProfile(&WhitePoint, &Primaries, GammaTable); cmsFreeToneCurve(GammaTable[0]); mainprog_ptr->input_color = RWPNG_GAMA_CHRM; mainprog_ptr->output_color = RWPNG_SRGB; } /* transform image to sRGB colorspace */ if (hInProfile != NULL) { cmsHPROFILE hOutProfile = cmsCreate_sRGBProfile(); cmsHTRANSFORM hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_8, hOutProfile, TYPE_RGBA_8, INTENT_PERCEPTUAL, omp_get_max_threads() > 1 ? cmsFLAGS_NOCACHE : 0); #pragma omp parallel for \ if (mainprog_ptr->height*mainprog_ptr->width > 8000) \ schedule(static) for (unsigned int i = 0; i < mainprog_ptr->height; i++) { /* It is safe to use the same block for input and output, when both are of the same TYPE. */ cmsDoTransform(hTransform, row_pointers[i], row_pointers[i], mainprog_ptr->width); } cmsDeleteTransform(hTransform); cmsCloseProfile(hOutProfile); cmsCloseProfile(hInProfile); mainprog_ptr->gamma = 0.45455; } #endif png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->file_size = read_data.bytes_read; mainprog_ptr->row_pointers = (unsigned char **)row_pointers; return SUCCESS; }
nan
null
10,741
205294190601256370613222196131194576515
221
Fix integer overflow in rwpng.h (CVE-2016-5735) Reported by Choi Jaeseung Found with Sparrow (http://ropas.snu.ac.kr/sparrow)
null
libav
0a49a62f998747cfa564d98d36a459fe70d3299b
1
int ff_h263_decode_picture_header(MpegEncContext *s) { int format, width, height, i; uint32_t startcode; align_get_bits(&s->gb); startcode= get_bits(&s->gb, 22-8); for(i= get_bits_left(&s->gb); i>24; i-=8) { startcode = ((startcode << 8) | get_bits(&s->gb, 8)) & 0x003FFFFF; if(startcode == 0x20) break; } if (startcode != 0x20) { av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n"); return -1; } /* temporal reference */ i = get_bits(&s->gb, 8); /* picture timestamp */ if( (s->picture_number&~0xFF)+i < s->picture_number) i+= 256; s->picture_number= (s->picture_number&~0xFF) + i; /* PTYPE starts here */ if (get_bits1(&s->gb) != 1) { /* marker */ av_log(s->avctx, AV_LOG_ERROR, "Bad marker\n"); return -1; } if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Bad H263 id\n"); return -1; /* h263 id */ } skip_bits1(&s->gb); /* split screen off */ skip_bits1(&s->gb); /* camera off */ skip_bits1(&s->gb); /* freeze picture release off */ format = get_bits(&s->gb, 3); /* 0 forbidden 1 sub-QCIF 10 QCIF 7 extended PTYPE (PLUSPTYPE) */ if (format != 7 && format != 6) { s->h263_plus = 0; /* H.263v1 */ width = ff_h263_format[format][0]; height = ff_h263_format[format][1]; if (!width) return -1; s->pict_type = AV_PICTURE_TYPE_I + get_bits1(&s->gb); s->h263_long_vectors = get_bits1(&s->gb); if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "H263 SAC not supported\n"); return -1; /* SAC: off */ } s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */ s->unrestricted_mv = s->h263_long_vectors || s->obmc; s->pb_frame = get_bits1(&s->gb); s->chroma_qscale= s->qscale = get_bits(&s->gb, 5); skip_bits1(&s->gb); /* Continuous Presence Multipoint mode: off */ s->width = width; s->height = height; s->avctx->sample_aspect_ratio= (AVRational){12,11}; s->avctx->framerate = (AVRational){ 30000, 1001 }; } else { int ufep; /* H.263v2 */ s->h263_plus = 1; ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */ /* ufep other than 0 and 1 are reserved */ if (ufep == 1) { /* OPPTYPE */ format = get_bits(&s->gb, 3); ff_dlog(s->avctx, "ufep=1, format: %d\n", format); s->custom_pcf= get_bits1(&s->gb); s->umvplus = get_bits1(&s->gb); /* Unrestricted Motion Vector */ if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Syntax-based Arithmetic Coding (SAC) not supported\n"); } s->obmc= get_bits1(&s->gb); /* Advanced prediction mode */ s->h263_aic = get_bits1(&s->gb); /* Advanced Intra Coding (AIC) */ s->loop_filter= get_bits1(&s->gb); s->unrestricted_mv = s->umvplus || s->obmc || s->loop_filter; s->h263_slice_structured= get_bits1(&s->gb); if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Reference Picture Selection not supported\n"); } if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "Independent Segment Decoding not supported\n"); } s->alt_inter_vlc= get_bits1(&s->gb); s->modified_quant= get_bits1(&s->gb); if(s->modified_quant) s->chroma_qscale_table= ff_h263_chroma_qscale_table; skip_bits(&s->gb, 1); /* Prevent start code emulation */ skip_bits(&s->gb, 3); /* Reserved */ } else if (ufep != 0) { av_log(s->avctx, AV_LOG_ERROR, "Bad UFEP type (%d)\n", ufep); return -1; } /* MPPTYPE */ s->pict_type = get_bits(&s->gb, 3); switch(s->pict_type){ case 0: s->pict_type= AV_PICTURE_TYPE_I;break; case 1: s->pict_type= AV_PICTURE_TYPE_P;break; case 2: s->pict_type= AV_PICTURE_TYPE_P;s->pb_frame = 3;break; case 3: s->pict_type= AV_PICTURE_TYPE_B;break; case 7: s->pict_type= AV_PICTURE_TYPE_I;break; //ZYGO default: return -1; } skip_bits(&s->gb, 2); s->no_rounding = get_bits1(&s->gb); skip_bits(&s->gb, 4); /* Get the picture dimensions */ if (ufep) { if (format == 6) { /* Custom Picture Format (CPFMT) */ s->aspect_ratio_info = get_bits(&s->gb, 4); ff_dlog(s->avctx, "aspect: %d\n", s->aspect_ratio_info); /* aspect ratios: 0 - forbidden 1 - 1:1 2 - 12:11 (CIF 4:3) 3 - 10:11 (525-type 4:3) 4 - 16:11 (CIF 16:9) 5 - 40:33 (525-type 16:9) 6-14 - reserved */ width = (get_bits(&s->gb, 9) + 1) * 4; skip_bits1(&s->gb); height = get_bits(&s->gb, 9) * 4; ff_dlog(s->avctx, "\nH.263+ Custom picture: %dx%d\n",width,height); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { /* aspected dimensions */ s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 8); s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 8); }else{ s->avctx->sample_aspect_ratio= ff_h263_pixel_aspect[s->aspect_ratio_info]; } } else { width = ff_h263_format[format][0]; height = ff_h263_format[format][1]; s->avctx->sample_aspect_ratio= (AVRational){12,11}; } if ((width == 0) || (height == 0)) return -1; s->width = width; s->height = height; if(s->custom_pcf){ int gcd; s->avctx->framerate.num = 1800000; s->avctx->framerate.den = 1000 + get_bits1(&s->gb); s->avctx->framerate.den *= get_bits(&s->gb, 7); if(s->avctx->framerate.den == 0){ av_log(s, AV_LOG_ERROR, "zero framerate\n"); return -1; } gcd= av_gcd(s->avctx->framerate.den, s->avctx->framerate.num); s->avctx->framerate.den /= gcd; s->avctx->framerate.num /= gcd; }else{ s->avctx->framerate = (AVRational){ 30000, 1001 }; } } if(s->custom_pcf){ skip_bits(&s->gb, 2); //extended Temporal reference } if (ufep) { if (s->umvplus) { if(get_bits1(&s->gb)==0) /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */ skip_bits1(&s->gb); } if(s->h263_slice_structured){ if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "rectangular slices not supported\n"); } if (get_bits1(&s->gb) != 0) { av_log(s->avctx, AV_LOG_ERROR, "unordered slices not supported\n"); } } } s->qscale = get_bits(&s->gb, 5); } s->mb_width = (s->width + 15) / 16; s->mb_height = (s->height + 15) / 16; s->mb_num = s->mb_width * s->mb_height; if (s->pb_frame) { skip_bits(&s->gb, 3); /* Temporal reference for B-pictures */ if (s->custom_pcf) skip_bits(&s->gb, 2); //extended Temporal reference skip_bits(&s->gb, 2); /* Quantization information for B-pictures */ } if (s->pict_type!=AV_PICTURE_TYPE_B) { s->time = s->picture_number; s->pp_time = s->time - s->last_non_b_time; s->last_non_b_time = s->time; }else{ s->time = s->picture_number; s->pb_time = s->pp_time - (s->last_non_b_time - s->time); if (s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time <= 0){ s->pp_time = 2; s->pb_time = 1; } ff_mpeg4_init_direct_mv(s); } /* PEI */ while (get_bits1(&s->gb) != 0) { skip_bits(&s->gb, 8); } if(s->h263_slice_structured){ if (get_bits1(&s->gb) != 1) { av_log(s->avctx, AV_LOG_ERROR, "SEPB1 marker missing\n"); return -1; } ff_h263_decode_mba(s); if (get_bits1(&s->gb) != 1) { av_log(s->avctx, AV_LOG_ERROR, "SEPB2 marker missing\n"); return -1; } } s->f_code = 1; if(s->h263_aic){ s->y_dc_scale_table= s->c_dc_scale_table= ff_aic_dc_scale_table; }else{ s->y_dc_scale_table= s->c_dc_scale_table= ff_mpeg1_dc_scale_table; } ff_h263_show_pict_info(s); if (s->pict_type == AV_PICTURE_TYPE_I && s->codec_tag == AV_RL32("ZYGO")){ int i,j; for(i=0; i<85; i++) av_log(s->avctx, AV_LOG_DEBUG, "%d", get_bits1(&s->gb)); av_log(s->avctx, AV_LOG_DEBUG, "\n"); for(i=0; i<13; i++){ for(j=0; j<3; j++){ int v= get_bits(&s->gb, 8); v |= get_sbits(&s->gb, 8)<<8; av_log(s->avctx, AV_LOG_DEBUG, " %5d", v); } av_log(s->avctx, AV_LOG_DEBUG, "\n"); } for(i=0; i<50; i++) av_log(s->avctx, AV_LOG_DEBUG, "%d", get_bits1(&s->gb)); } return 0; }
nan
null
10,742
197626158404532314510739945572144125657
280
h263: Always check both dimensions CC: libav-stable@libav.org Found-By: ago@gentoo.org
null
qemu
3a15cc0e1ee7168db0782133d2607a6bfa422d66
1
static ssize_t stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, size_t size) { stellaris_enet_state *s = qemu_get_nic_opaque(nc); int n; uint8_t *p; uint32_t crc; if ((s->rctl & SE_RCTL_RXEN) == 0) return -1; if (s->np >= 31) { return 0; } DPRINTF("Received packet len=%zu\n", size); n = s->next_packet + s->np; if (n >= 31) n -= 31; s->np++; s->rx[n].len = size + 6; p = s->rx[n].data; *(p++) = (size + 6); *(p++) = (size + 6) >> 8; memcpy (p, buf, size); p += size; crc = crc32(~0, buf, size); *(p++) = crc; *(p++) = crc >> 8; *(p++) = crc >> 16; *(p++) = crc >> 24; /* Clear the remaining bytes in the last word. */ if ((size & 3) != 2) { memset(p, 0, (6 - size) & 3); } s->ris |= SE_INT_RX; stellaris_enet_update(s); return size; }
nan
null
10,743
96844957878192263069603680775030823173
40
net: stellaris_enet: check packet length against receive buffer When receiving packets over Stellaris ethernet controller, it uses receive buffer of size 2048 bytes. In case the controller accepts large(MTU) packets, it could lead to memory corruption. Add check to avoid it. Reported-by: Oleksandr Bazhaniuk <oleksandr.bazhaniuk@intel.com> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Message-id: 1460095428-22698-1-git-send-email-ppandit@redhat.com Reviewed-by: Peter Maydell <peter.maydell@linaro.org> Signed-off-by: Peter Maydell <peter.maydell@linaro.org>
null
qemu
a6b3167fa0e825aebb5a7cd8b437b6d41584a196
1
static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs, unsigned long int req, void *buf, BlockCompletionFunc *cb, void *opaque) { IscsiLun *iscsilun = bs->opaque; struct iscsi_context *iscsi = iscsilun->iscsi; struct iscsi_data data; IscsiAIOCB *acb; acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque); acb->iscsilun = iscsilun; acb->bh = NULL; acb->status = -EINPROGRESS; acb->buf = NULL; acb->ioh = buf; if (req != SG_IO) { iscsi_ioctl_handle_emulated(acb, req, buf); return &acb->common; } acb->task = malloc(sizeof(struct scsi_task)); if (acb->task == NULL) { error_report("iSCSI: Failed to allocate task for scsi command. %s", iscsi_get_error(iscsi)); qemu_aio_unref(acb); return NULL; } memset(acb->task, 0, sizeof(struct scsi_task)); switch (acb->ioh->dxfer_direction) { case SG_DXFER_TO_DEV: acb->task->xfer_dir = SCSI_XFER_WRITE; break; case SG_DXFER_FROM_DEV: acb->task->xfer_dir = SCSI_XFER_READ; break; default: acb->task->xfer_dir = SCSI_XFER_NONE; break; } acb->task->cdb_size = acb->ioh->cmd_len; memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len); acb->task->expxferlen = acb->ioh->dxfer_len; data.size = 0; if (acb->task->xfer_dir == SCSI_XFER_WRITE) { if (acb->ioh->iovec_count == 0) { data.data = acb->ioh->dxferp; data.size = acb->ioh->dxfer_len; } else { scsi_task_set_iov_out(acb->task, (struct scsi_iovec *) acb->ioh->dxferp, acb->ioh->iovec_count); } } if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task, iscsi_aio_ioctl_cb, (data.size > 0) ? &data : NULL, acb) != 0) { scsi_free_scsi_task(acb->task); qemu_aio_unref(acb); return NULL; } /* tell libiscsi to read straight into the buffer we got from ioctl */ if (acb->task->xfer_dir == SCSI_XFER_READ) { if (acb->ioh->iovec_count == 0) { scsi_task_add_data_in_buffer(acb->task, acb->ioh->dxfer_len, acb->ioh->dxferp); } else { scsi_task_set_iov_in(acb->task, (struct scsi_iovec *) acb->ioh->dxferp, acb->ioh->iovec_count); } } iscsi_set_events(iscsilun); return &acb->common; }
nan
null
10,744
281431584605820921133702870695605823047
85
block/iscsi: avoid potential overflow of acb->task->cdb at least in the path via virtio-blk the maximum size is not restricted. Cc: qemu-stable@nongnu.org Signed-off-by: Peter Lieven <pl@kamp.de> Message-Id: <1464080368-29584-1-git-send-email-pl@kamp.de> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
null
FFmpeg
ed188f6dcdf0935c939ed813cf8745d50742014b
1
static int aa_read_header(AVFormatContext *s) { int i, j, idx, largest_idx = -1; uint32_t nkey, nval, toc_size, npairs, header_seed = 0, start; char key[128], val[128], codec_name[64] = {0}; uint8_t output[24], dst[8], src[8]; int64_t largest_size = -1, current_size = -1, chapter_pos; struct toc_entry { uint32_t offset; uint32_t size; } TOC[MAX_TOC_ENTRIES]; uint32_t header_key_part[4]; uint8_t header_key[16] = {0}; AADemuxContext *c = s->priv_data; AVIOContext *pb = s->pb; AVStream *st; /* parse .aa header */ avio_skip(pb, 4); // file size avio_skip(pb, 4); // magic string toc_size = avio_rb32(pb); // TOC size avio_skip(pb, 4); // unidentified integer if (toc_size > MAX_TOC_ENTRIES) return AVERROR_INVALIDDATA; for (i = 0; i < toc_size; i++) { // read TOC avio_skip(pb, 4); // TOC entry index TOC[i].offset = avio_rb32(pb); // block offset TOC[i].size = avio_rb32(pb); // block size } avio_skip(pb, 24); // header termination block (ignored) npairs = avio_rb32(pb); // read dictionary entries if (npairs > MAX_DICTIONARY_ENTRIES) return AVERROR_INVALIDDATA; for (i = 0; i < npairs; i++) { memset(val, 0, sizeof(val)); memset(key, 0, sizeof(key)); avio_skip(pb, 1); // unidentified integer nkey = avio_rb32(pb); // key string length nval = avio_rb32(pb); // value string length avio_get_str(pb, nkey, key, sizeof(key)); avio_get_str(pb, nval, val, sizeof(val)); if (!strcmp(key, "codec")) { av_log(s, AV_LOG_DEBUG, "Codec is <%s>\n", val); strncpy(codec_name, val, sizeof(codec_name) - 1); } else if (!strcmp(key, "HeaderSeed")) { av_log(s, AV_LOG_DEBUG, "HeaderSeed is <%s>\n", val); header_seed = atoi(val); } else if (!strcmp(key, "HeaderKey")) { // this looks like "1234567890 1234567890 1234567890 1234567890" av_log(s, AV_LOG_DEBUG, "HeaderKey is <%s>\n", val); sscanf(val, "%"SCNu32"%"SCNu32"%"SCNu32"%"SCNu32, &header_key_part[0], &header_key_part[1], &header_key_part[2], &header_key_part[3]); for (idx = 0; idx < 4; idx++) { AV_WB32(&header_key[idx * 4], header_key_part[idx]); // convert each part to BE! } av_log(s, AV_LOG_DEBUG, "Processed HeaderKey is "); for (i = 0; i < 16; i++) av_log(s, AV_LOG_DEBUG, "%02x", header_key[i]); av_log(s, AV_LOG_DEBUG, "\n"); } else { av_dict_set(&s->metadata, key, val, 0); } } /* verify fixed key */ if (c->aa_fixed_key_len != 16) { av_log(s, AV_LOG_ERROR, "aa_fixed_key value needs to be 16 bytes!\n"); return AVERROR(EINVAL); } /* verify codec */ if ((c->codec_second_size = get_second_size(codec_name)) == -1) { av_log(s, AV_LOG_ERROR, "unknown codec <%s>!\n", codec_name); return AVERROR(EINVAL); } /* decryption key derivation */ c->tea_ctx = av_tea_alloc(); if (!c->tea_ctx) return AVERROR(ENOMEM); av_tea_init(c->tea_ctx, c->aa_fixed_key, 16); output[0] = output[1] = 0; // purely for padding purposes memcpy(output + 2, header_key, 16); idx = 0; for (i = 0; i < 3; i++) { // TEA CBC with weird mixed endianness AV_WB32(src, header_seed); AV_WB32(src + 4, header_seed + 1); header_seed += 2; av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 0); // TEA ECB encrypt for (j = 0; j < TEA_BLOCK_SIZE && idx < 18; j+=1, idx+=1) { output[idx] = output[idx] ^ dst[j]; } } memcpy(c->file_key, output + 2, 16); // skip first 2 bytes of output av_log(s, AV_LOG_DEBUG, "File key is "); for (i = 0; i < 16; i++) av_log(s, AV_LOG_DEBUG, "%02x", c->file_key[i]); av_log(s, AV_LOG_DEBUG, "\n"); /* decoder setup */ st = avformat_new_stream(s, NULL); if (!st) { av_freep(&c->tea_ctx); return AVERROR(ENOMEM); } st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; if (!strcmp(codec_name, "mp332")) { st->codecpar->codec_id = AV_CODEC_ID_MP3; st->codecpar->sample_rate = 22050; st->need_parsing = AVSTREAM_PARSE_FULL_RAW; avpriv_set_pts_info(st, 64, 8, 32000 * TIMEPREC); // encoded audio frame is MP3_FRAME_SIZE bytes (+1 with padding, unlikely) } else if (!strcmp(codec_name, "acelp85")) { st->codecpar->codec_id = AV_CODEC_ID_SIPR; st->codecpar->block_align = 19; st->codecpar->channels = 1; st->codecpar->sample_rate = 8500; st->codecpar->bit_rate = 8500; st->need_parsing = AVSTREAM_PARSE_FULL_RAW; avpriv_set_pts_info(st, 64, 8, 8500 * TIMEPREC); } else if (!strcmp(codec_name, "acelp16")) { st->codecpar->codec_id = AV_CODEC_ID_SIPR; st->codecpar->block_align = 20; st->codecpar->channels = 1; st->codecpar->sample_rate = 16000; st->codecpar->bit_rate = 16000; st->need_parsing = AVSTREAM_PARSE_FULL_RAW; avpriv_set_pts_info(st, 64, 8, 16000 * TIMEPREC); } /* determine, and jump to audio start offset */ for (i = 1; i < toc_size; i++) { // skip the first entry! current_size = TOC[i].size; if (current_size > largest_size) { largest_idx = i; largest_size = current_size; } } start = TOC[largest_idx].offset; avio_seek(pb, start, SEEK_SET); // extract chapter positions. since all formats have constant bit rate, use it // as time base in bytes/s, for easy stream position <-> timestamp conversion st->start_time = 0; c->content_start = start; c->content_end = start + largest_size; while ((chapter_pos = avio_tell(pb)) >= 0 && chapter_pos < c->content_end) { int chapter_idx = s->nb_chapters; uint32_t chapter_size = avio_rb32(pb); if (chapter_size == 0) break; chapter_pos -= start + CHAPTER_HEADER_SIZE * chapter_idx; avio_skip(pb, 4 + chapter_size); if (!avpriv_new_chapter(s, chapter_idx, st->time_base, chapter_pos * TIMEPREC, (chapter_pos + chapter_size) * TIMEPREC, NULL)) return AVERROR(ENOMEM); } st->duration = (largest_size - CHAPTER_HEADER_SIZE * s->nb_chapters) * TIMEPREC; ff_update_cur_dts(s, st, 0); avio_seek(pb, start, SEEK_SET); c->current_chapter_size = 0; c->seek_offset = 0; return 0; }
nan
null
10,745
62314827938333340386787035223287805078
166
avformat/aadec: Check for scanf() failure Fixes: use of uninitialized variables Fixes: blank.aa Found-by: Chamal De Silva <chamal.desilva@gmail.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
samba
b000da128b5fb519d2d3f2e7fd20e4a25b7dae7d
1
static int samldb_check_user_account_control_acl(struct samldb_ctx *ac, struct dom_sid *sid, uint32_t user_account_control, uint32_t user_account_control_old) { int i, ret = 0; bool need_acl_check = false; struct ldb_result *res; const char * const sd_attrs[] = {"ntSecurityDescriptor", NULL}; struct security_token *user_token; struct security_descriptor *domain_sd; struct ldb_dn *domain_dn = ldb_get_default_basedn(ldb_module_get_ctx(ac->module)); const struct uac_to_guid { uint32_t uac; const char *oid; const char *guid; enum sec_privilege privilege; bool delete_is_privileged; const char *error_string; } map[] = { { .uac = UF_PASSWD_NOTREQD, .guid = GUID_DRS_UPDATE_PASSWORD_NOT_REQUIRED_BIT, .error_string = "Adding the UF_PASSWD_NOTREQD bit in userAccountControl requires the Update-Password-Not-Required-Bit right that was not given on the Domain object" }, { .uac = UF_DONT_EXPIRE_PASSWD, .guid = GUID_DRS_UNEXPIRE_PASSWORD, .error_string = "Adding the UF_DONT_EXPIRE_PASSWD bit in userAccountControl requires the Unexpire-Password right that was not given on the Domain object" }, { .uac = UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED, .guid = GUID_DRS_ENABLE_PER_USER_REVERSIBLY_ENCRYPTED_PASSWORD, .error_string = "Adding the UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED bit in userAccountControl requires the Enable-Per-User-Reversibly-Encrypted-Password right that was not given on the Domain object" }, { .uac = UF_SERVER_TRUST_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_SERVER_TRUST_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_PARTIAL_SECRETS_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_INTERDOMAIN_TRUST_ACCOUNT, .oid = DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID, .error_string = "Updating the UF_INTERDOMAIN_TRUST_ACCOUNT bit in userAccountControl is not permitted over LDAP. This bit is restricted to the LSA CreateTrustedDomain interface", .delete_is_privileged = true }, { .uac = UF_TRUSTED_FOR_DELEGATION, .privilege = SEC_PRIV_ENABLE_DELEGATION, .delete_is_privileged = true, .error_string = "Updating the UF_TRUSTED_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege" }, { .uac = UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION, .privilege = SEC_PRIV_ENABLE_DELEGATION, .delete_is_privileged = true, .error_string = "Updating the UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege" } }; if (dsdb_module_am_system(ac->module)) { return LDB_SUCCESS; } for (i = 0; i < ARRAY_SIZE(map); i++) { if (user_account_control & map[i].uac) { need_acl_check = true; break; } } if (need_acl_check == false) { return LDB_SUCCESS; } user_token = acl_user_token(ac->module); if (user_token == NULL) { return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS; } ret = dsdb_module_search_dn(ac->module, ac, &res, domain_dn, sd_attrs, DSDB_FLAG_NEXT_MODULE | DSDB_SEARCH_SHOW_DELETED, ac->req); if (ret != LDB_SUCCESS) { return ret; } if (res->count != 1) { return ldb_module_operr(ac->module); } ret = dsdb_get_sd_from_ldb_message(ldb_module_get_ctx(ac->module), ac, res->msgs[0], &domain_sd); if (ret != LDB_SUCCESS) { return ret; } for (i = 0; i < ARRAY_SIZE(map); i++) { uint32_t this_uac_new = user_account_control & map[i].uac; uint32_t this_uac_old = user_account_control_old & map[i].uac; if (this_uac_new != this_uac_old) { if (this_uac_old != 0) { if (map[i].delete_is_privileged == false) { continue; } } if (map[i].oid) { struct ldb_control *control = ldb_request_get_control(ac->req, map[i].oid); if (control == NULL) { ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS; } } else if (map[i].privilege != SEC_PRIV_INVALID) { bool have_priv = security_token_has_privilege(user_token, map[i].privilege); if (have_priv == false) { ret = LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS; } } else { ret = acl_check_extended_right(ac, domain_sd, user_token, map[i].guid, SEC_ADS_CONTROL_ACCESS, sid); } if (ret != LDB_SUCCESS) { break; } } } if (ret == LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS) { switch (ac->req->operation) { case LDB_ADD: ldb_asprintf_errstring(ldb_module_get_ctx(ac->module), "Failed to add %s: %s", ldb_dn_get_linearized(ac->msg->dn), map[i].error_string); break; case LDB_MODIFY: ldb_asprintf_errstring(ldb_module_get_ctx(ac->module), "Failed to modify %s: %s", ldb_dn_get_linearized(ac->msg->dn), map[i].error_string); break; default: return ldb_module_operr(ac->module); } if (map[i].guid) { dsdb_acl_debug(domain_sd, acl_user_token(ac->module), domain_dn, true, 10); } } return ret; }
nan
null
10,746
59441307753859117358796866247851560097
162
CVE-2015-8467: samdb: Match MS15-096 behaviour for userAccountControl Swapping between account types is now restricted Bug: https://bugzilla.samba.org/show_bug.cgi?id=11552 Signed-off-by: Andrew Bartlett <abartlet@samba.org> Reviewed-by: Jeremy Allison <jra@samba.org> Reviewed-by: Ralph Boehme <slow@samba.org>
null
spice
8af619009660b24e0b41ad26b30289eea288fcc2
1
static void reds_handle_ticket(void *opaque) { RedLinkInfo *link = (RedLinkInfo *)opaque; char password[SPICE_MAX_PASSWORD_LENGTH]; time_t ltime; //todo: use monotonic time time(&ltime); RSA_private_decrypt(link->tiTicketing.rsa_size, link->tiTicketing.encrypted_ticket.encrypted_data, (unsigned char *)password, link->tiTicketing.rsa, RSA_PKCS1_OAEP_PADDING); if (ticketing_enabled && !link->skip_auth) { int expired = taTicket.expiration_time < ltime; if (strlen(taTicket.password) == 0) { reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); spice_warning("Ticketing is enabled, but no password is set. " "please set a ticket first"); reds_link_free(link); return; } if (expired || strncmp(password, taTicket.password, SPICE_MAX_PASSWORD_LENGTH) != 0) { if (expired) { spice_warning("Ticket has expired"); } else { spice_warning("Invalid password"); } reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); reds_link_free(link); return; } } reds_handle_link(link); }
nan
null
10,747
18934837448161982598837945635303451949
37
Fix buffer overflow when decrypting client SPICE ticket reds_handle_ticket uses a fixed size 'password' buffer for the decrypted password whose size is SPICE_MAX_PASSWORD_LENGTH. However, RSA_private_decrypt which we call for the decryption expects the destination buffer to be at least RSA_size(link->tiTicketing.rsa) bytes long. On my spice-server build, SPICE_MAX_PASSWORD_LENGTH is 60 while RSA_size() is 128, so we end up overflowing 'password' when using long passwords (this was reproduced using the string: 'fullscreen=1proxy=#enter proxy here; e.g spice_proxy = http://[proxy]:[port]' as a password). When the overflow occurs, QEMU dies with: *** stack smashing detected ***: qemu-system-x86_64 terminated This commit ensures we use a corectly sized 'password' buffer, and that it's correctly nul-terminated so that we can use strcmp instead of strncmp. To keep using strncmp, we'd need to figure out which one of 'password' and 'taTicket.password' is the smaller buffer, and use that size. This fixes rhbz#999839
null
qemu
eea750a5623ddac7a61982eec8f1c93481857578
1
static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) { VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); int ret, i, link_down; if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION) return -EINVAL; ret = virtio_load(vdev, f); if (ret) { return ret; } qemu_get_buffer(f, n->mac, ETH_ALEN); n->vqs[0].tx_waiting = qemu_get_be32(f); virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f)); if (version_id >= 3) n->status = qemu_get_be16(f); if (version_id >= 4) { if (version_id < 8) { n->promisc = qemu_get_be32(f); n->allmulti = qemu_get_be32(f); } else { n->promisc = qemu_get_byte(f); n->allmulti = qemu_get_byte(f); } } if (version_id >= 5) { n->mac_table.in_use = qemu_get_be32(f); /* MAC_TABLE_ENTRIES may be different from the saved image */ if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) { qemu_get_buffer(f, n->mac_table.macs, n->mac_table.in_use * ETH_ALEN); } else if (n->mac_table.in_use) { uint8_t *buf = g_malloc0(n->mac_table.in_use); qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN); g_free(buf); n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1; n->mac_table.in_use = 0; } } if (version_id >= 6) qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3); if (version_id >= 7) { if (qemu_get_be32(f) && !peer_has_vnet_hdr(n)) { error_report("virtio-net: saved image requires vnet_hdr=on"); return -1; } } if (version_id >= 9) { n->mac_table.multi_overflow = qemu_get_byte(f); n->mac_table.uni_overflow = qemu_get_byte(f); } if (version_id >= 10) { n->alluni = qemu_get_byte(f); n->nomulti = qemu_get_byte(f); n->nouni = qemu_get_byte(f); n->nobcast = qemu_get_byte(f); } if (version_id >= 11) { if (qemu_get_byte(f) && !peer_has_ufo(n)) { error_report("virtio-net: saved image requires TUN_F_UFO support"); return -1; } } if (n->max_queues > 1) { if (n->max_queues != qemu_get_be16(f)) { error_report("virtio-net: different max_queues "); return -1; } n->curr_queues = qemu_get_be16(f); for (i = 1; i < n->curr_queues; i++) { n->vqs[i].tx_waiting = qemu_get_be32(f); } } if ((1 << VIRTIO_NET_F_CTRL_GUEST_OFFLOADS) & vdev->guest_features) { n->curr_guest_offloads = qemu_get_be64(f); } else { n->curr_guest_offloads = virtio_net_supported_guest_offloads(n); } if (peer_has_vnet_hdr(n)) { virtio_net_apply_guest_offloads(n); } virtio_net_set_queues(n); /* Find the first multicast entry in the saved MAC filter */ for (i = 0; i < n->mac_table.in_use; i++) { if (n->mac_table.macs[i * ETH_ALEN] & 1) { break; } } n->mac_table.first_multi = i; /* nc.link_down can't be migrated, so infer link_down according * to link status bit in n->status */ link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0; for (i = 0; i < n->max_queues; i++) { qemu_get_subqueue(n->nic, i)->link_down = link_down; } return 0; }
nan
null
10,748
279963136302441123708496853992224586998
117
virtio-net: out-of-bounds buffer write on invalid state load CVE-2013-4150 QEMU 1.5.0 out-of-bounds buffer write in virtio_net_load()@hw/net/virtio-net.c This code is in hw/net/virtio-net.c: if (n->max_queues > 1) { if (n->max_queues != qemu_get_be16(f)) { error_report("virtio-net: different max_queues "); return -1; } n->curr_queues = qemu_get_be16(f); for (i = 1; i < n->curr_queues; i++) { n->vqs[i].tx_waiting = qemu_get_be32(f); } } Number of vqs is max_queues, so if we get invalid input here, for example if max_queues = 2, curr_queues = 3, we get write beyond end of the buffer, with data that comes from wire. This might be used to corrupt qemu memory in hard to predict ways. Since we have lots of function pointers around, RCE might be possible. Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Acked-by: Jason Wang <jasowang@redhat.com> Reviewed-by: Michael Roth <mdroth@linux.vnet.ibm.com> Signed-off-by: Juan Quintela <quintela@redhat.com>
null
Espruino
bed844f109b6c222816740555068de2e101e8018
1
void jslTokenAsString(int token, char *str, size_t len) { // see JS_ERROR_TOKEN_BUF_SIZE if (token>32 && token<128) { assert(len>=4); str[0] = '\''; str[1] = (char)token; str[2] = '\''; str[3] = 0; return; } switch (token) { case LEX_EOF : strncpy(str, "EOF", len); return; case LEX_ID : strncpy(str, "ID", len); return; case LEX_INT : strncpy(str, "INT", len); return; case LEX_FLOAT : strncpy(str, "FLOAT", len); return; case LEX_STR : strncpy(str, "STRING", len); return; case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return; case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return; case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return; case LEX_REGEX : strncpy(str, "REGEX", len); return; case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return; case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return; } if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) { const char tokenNames[] = /* LEX_EQUAL : */ "==\0" /* LEX_TYPEEQUAL : */ "===\0" /* LEX_NEQUAL : */ "!=\0" /* LEX_NTYPEEQUAL : */ "!==\0" /* LEX_LEQUAL : */ "<=\0" /* LEX_LSHIFT : */ "<<\0" /* LEX_LSHIFTEQUAL : */ "<<=\0" /* LEX_GEQUAL : */ ">=\0" /* LEX_RSHIFT : */ ">>\0" /* LEX_RSHIFTUNSIGNED */ ">>>\0" /* LEX_RSHIFTEQUAL : */ ">>=\0" /* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0" /* LEX_PLUSEQUAL : */ "+=\0" /* LEX_MINUSEQUAL : */ "-=\0" /* LEX_PLUSPLUS : */ "++\0" /* LEX_MINUSMINUS */ "--\0" /* LEX_MULEQUAL : */ "*=\0" /* LEX_DIVEQUAL : */ "/=\0" /* LEX_MODEQUAL : */ "%=\0" /* LEX_ANDEQUAL : */ "&=\0" /* LEX_ANDAND : */ "&&\0" /* LEX_OREQUAL : */ "|=\0" /* LEX_OROR : */ "||\0" /* LEX_XOREQUAL : */ "^=\0" /* LEX_ARROW_FUNCTION */ "=>\0" // reserved words /*LEX_R_IF : */ "if\0" /*LEX_R_ELSE : */ "else\0" /*LEX_R_DO : */ "do\0" /*LEX_R_WHILE : */ "while\0" /*LEX_R_FOR : */ "for\0" /*LEX_R_BREAK : */ "return\0" /*LEX_R_CONTINUE */ "continue\0" /*LEX_R_FUNCTION */ "function\0" /*LEX_R_RETURN */ "return\0" /*LEX_R_VAR : */ "var\0" /*LEX_R_LET : */ "let\0" /*LEX_R_CONST : */ "const\0" /*LEX_R_THIS : */ "this\0" /*LEX_R_THROW : */ "throw\0" /*LEX_R_TRY : */ "try\0" /*LEX_R_CATCH : */ "catch\0" /*LEX_R_FINALLY : */ "finally\0" /*LEX_R_TRUE : */ "true\0" /*LEX_R_FALSE : */ "false\0" /*LEX_R_NULL : */ "null\0" /*LEX_R_UNDEFINED */ "undefined\0" /*LEX_R_NEW : */ "new\0" /*LEX_R_IN : */ "in\0" /*LEX_R_INSTANCEOF */ "instanceof\0" /*LEX_R_SWITCH */ "switch\0" /*LEX_R_CASE */ "case\0" /*LEX_R_DEFAULT */ "default\0" /*LEX_R_DELETE */ "delete\0" /*LEX_R_TYPEOF : */ "typeof\0" /*LEX_R_VOID : */ "void\0" /*LEX_R_DEBUGGER : */ "debugger\0" /*LEX_R_CLASS : */ "class\0" /*LEX_R_EXTENDS : */ "extends\0" /*LEX_R_SUPER : */ "super\0" /*LEX_R_STATIC : */ "static\0" ; unsigned int p = 0; int n = token-_LEX_OPERATOR_START; while (n>0 && p<sizeof(tokenNames)) { while (tokenNames[p] && p<sizeof(tokenNames)) p++; p++; // skip the zero n--; // next token } assert(n==0); strncpy(str, &tokenNames[p], len); return; } assert(len>=10); espruino_snprintf(str, len, "?[%d]", token); }
nan
null
10,749
335155697690853052459747906082748307864
104
remove strncpy usage as it's effectively useless, replace with an assertion since fn is only used internally (fix #1426)
null
radare2
52b1526443c1f433087928291d1c3d37a5600515
1
int wasm_dis(WasmOp *op, const unsigned char *buf, int buf_len) { op->len = 1; op->op = buf[0]; if (op->op > 0xbf) return 1; // add support for extension opcodes (SIMD + atomics) WasmOpDef *opdef = &opcodes[op->op]; switch (op->op) { case WASM_OP_TRAP: case WASM_OP_NOP: case WASM_OP_ELSE: case WASM_OP_RETURN: case WASM_OP_DROP: case WASM_OP_SELECT: case WASM_OP_I32EQZ: case WASM_OP_I32EQ: case WASM_OP_I32NE: case WASM_OP_I32LTS: case WASM_OP_I32LTU: case WASM_OP_I32GTS: case WASM_OP_I32GTU: case WASM_OP_I32LES: case WASM_OP_I32LEU: case WASM_OP_I32GES: case WASM_OP_I32GEU: case WASM_OP_I64EQZ: case WASM_OP_I64EQ: case WASM_OP_I64NE: case WASM_OP_I64LTS: case WASM_OP_I64LTU: case WASM_OP_I64GTS: case WASM_OP_I64GTU: case WASM_OP_I64LES: case WASM_OP_I64LEU: case WASM_OP_I64GES: case WASM_OP_I64GEU: case WASM_OP_F32EQ: case WASM_OP_F32NE: case WASM_OP_F32LT: case WASM_OP_F32GT: case WASM_OP_F32LE: case WASM_OP_F32GE: case WASM_OP_F64EQ: case WASM_OP_F64NE: case WASM_OP_F64LT: case WASM_OP_F64GT: case WASM_OP_F64LE: case WASM_OP_F64GE: case WASM_OP_I32CLZ: case WASM_OP_I32CTZ: case WASM_OP_I32POPCNT: case WASM_OP_I32ADD: case WASM_OP_I32SUB: case WASM_OP_I32MUL: case WASM_OP_I32DIVS: case WASM_OP_I32DIVU: case WASM_OP_I32REMS: case WASM_OP_I32REMU: case WASM_OP_I32AND: case WASM_OP_I32OR: case WASM_OP_I32XOR: case WASM_OP_I32SHL: case WASM_OP_I32SHRS: case WASM_OP_I32SHRU: case WASM_OP_I32ROTL: case WASM_OP_I32ROTR: case WASM_OP_I64CLZ: case WASM_OP_I64CTZ: case WASM_OP_I64POPCNT: case WASM_OP_I64ADD: case WASM_OP_I64SUB: case WASM_OP_I64MUL: case WASM_OP_I64DIVS: case WASM_OP_I64DIVU: case WASM_OP_I64REMS: case WASM_OP_I64REMU: case WASM_OP_I64AND: case WASM_OP_I64OR: case WASM_OP_I64XOR: case WASM_OP_I64SHL: case WASM_OP_I64SHRS: case WASM_OP_I64SHRU: case WASM_OP_I64ROTL: case WASM_OP_I64ROTR: case WASM_OP_F32ABS: case WASM_OP_F32NEG: case WASM_OP_F32CEIL: case WASM_OP_F32FLOOR: case WASM_OP_F32TRUNC: case WASM_OP_F32NEAREST: case WASM_OP_F32SQRT: case WASM_OP_F32ADD: case WASM_OP_F32SUB: case WASM_OP_F32MUL: case WASM_OP_F32DIV: case WASM_OP_F32MIN: case WASM_OP_F32MAX: case WASM_OP_F32COPYSIGN: case WASM_OP_F64ABS: case WASM_OP_F64NEG: case WASM_OP_F64CEIL: case WASM_OP_F64FLOOR: case WASM_OP_F64TRUNC: case WASM_OP_F64NEAREST: case WASM_OP_F64SQRT: case WASM_OP_F64ADD: case WASM_OP_F64SUB: case WASM_OP_F64MUL: case WASM_OP_F64DIV: case WASM_OP_F64MIN: case WASM_OP_F64MAX: case WASM_OP_F64COPYSIGN: case WASM_OP_I32WRAPI64: case WASM_OP_I32TRUNCSF32: case WASM_OP_I32TRUNCUF32: case WASM_OP_I32TRUNCSF64: case WASM_OP_I32TRUNCUF64: case WASM_OP_I64EXTENDSI32: case WASM_OP_I64EXTENDUI32: case WASM_OP_I64TRUNCSF32: case WASM_OP_I64TRUNCUF32: case WASM_OP_I64TRUNCSF64: case WASM_OP_I64TRUNCUF64: case WASM_OP_F32CONVERTSI32: case WASM_OP_F32CONVERTUI32: case WASM_OP_F32CONVERTSI64: case WASM_OP_F32CONVERTUI64: case WASM_OP_F32DEMOTEF64: case WASM_OP_F64CONVERTSI32: case WASM_OP_F64CONVERTUI32: case WASM_OP_F64CONVERTSI64: case WASM_OP_F64CONVERTUI64: case WASM_OP_F64PROMOTEF32: case WASM_OP_I32REINTERPRETF32: case WASM_OP_I64REINTERPRETF64: case WASM_OP_F32REINTERPRETI32: case WASM_OP_F64REINTERPRETI64: case WASM_OP_END: { snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt); } break; case WASM_OP_BLOCK: case WASM_OP_LOOP: case WASM_OP_IF: { st32 val = 0; size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; switch (0x80 - val) { case R_BIN_WASM_VALUETYPE_EMPTY: snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt); break; case R_BIN_WASM_VALUETYPE_i32: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i32)", opdef->txt); break; case R_BIN_WASM_VALUETYPE_i64: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i64)", opdef->txt); break; case R_BIN_WASM_VALUETYPE_f32: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f32)", opdef->txt); break; case R_BIN_WASM_VALUETYPE_f64: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f64)", opdef->txt); break; default: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result ?)", opdef->txt); break; } op->len += n; } break; case WASM_OP_BR: case WASM_OP_BRIF: case WASM_OP_CALL: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val); op->len += n; } break; case WASM_OP_BRTABLE: { ut32 count = 0, *table = NULL, def = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &count); if (!(n > 0 && n < buf_len)) goto err; if (!(table = calloc (count, sizeof (ut32)))) goto err; int i = 0; op->len += n; for (i = 0; i < count; i++) { n = read_u32_leb128 (buf + op->len, buf + buf_len, &table[i]); if (!(op->len + n <= buf_len)) goto beach; op->len += n; } n = read_u32_leb128 (buf + op->len, buf + buf_len, &def); if (!(n > 0 && n + op->len < buf_len)) goto beach; op->len += n; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d ", opdef->txt, count); for (i = 0; i < count && strlen (op->txt) < R_ASM_BUFSIZE; i++) { snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, "%d ", table[i]); } snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, "%d", def); free (table); break; beach: free (table); goto err; } break; case WASM_OP_CALLINDIRECT: { ut32 val = 0, reserved = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; op->len += n; n = read_u32_leb128 (buf + op->len, buf + buf_len, &reserved); if (!(n == 1 && op->len + n <= buf_len)) goto err; reserved &= 0x1; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, val, reserved); op->len += n; } break; case WASM_OP_GETLOCAL: case WASM_OP_SETLOCAL: case WASM_OP_TEELOCAL: case WASM_OP_GETGLOBAL: case WASM_OP_SETGLOBAL: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val); op->len += n; } break; case WASM_OP_I32LOAD: case WASM_OP_I64LOAD: case WASM_OP_F32LOAD: case WASM_OP_F64LOAD: case WASM_OP_I32LOAD8S: case WASM_OP_I32LOAD8U: case WASM_OP_I32LOAD16S: case WASM_OP_I32LOAD16U: case WASM_OP_I64LOAD8S: case WASM_OP_I64LOAD8U: case WASM_OP_I64LOAD16S: case WASM_OP_I64LOAD16U: case WASM_OP_I64LOAD32S: case WASM_OP_I64LOAD32U: case WASM_OP_I32STORE: case WASM_OP_I64STORE: case WASM_OP_F32STORE: case WASM_OP_F64STORE: case WASM_OP_I32STORE8: case WASM_OP_I32STORE16: case WASM_OP_I64STORE8: case WASM_OP_I64STORE16: case WASM_OP_I64STORE32: { ut32 flag = 0, offset = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &flag); if (!(n > 0 && n < buf_len)) goto err; op->len += n; n = read_u32_leb128 (buf + op->len, buf + buf_len, &offset); if (!(n > 0 && op->len + n <= buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, flag, offset); op->len += n; } break; case WASM_OP_CURRENTMEMORY: case WASM_OP_GROWMEMORY: { ut32 reserved = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &reserved); if (!(n == 1 && n < buf_len)) goto err; reserved &= 0x1; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, reserved); op->len += n; } break; case WASM_OP_I32CONST: { st32 val = 0; size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT32d, opdef->txt, val); op->len += n; } break; case WASM_OP_I64CONST: { st64 val = 0; size_t n = read_i64_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT64d, opdef->txt, val); op->len += n; } break; case WASM_OP_F32CONST: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; long double d = (long double)val; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d); op->len += n; } break; case WASM_OP_F64CONST: { ut64 val = 0; size_t n = read_u64_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; long double d = (long double)val; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d); op->len += n; } break; default: goto err; } return op->len; err: op->len = 1; snprintf (op->txt, R_ASM_BUFSIZE, "invalid"); return op->len; }
nan
null
10,751
197820120957265740211440989102069255485
331
Fix crash in wasm disassembler
null
poppler
b1026b5978c385328f2a15a2185c599a563edf91
1
int CCITTFaxStream::lookChar() { int code1, code2, code3; int b1i, blackPixels, i, bits; GBool gotEOL; if (buf != EOF) { return buf; } // read the next row if (outputBits == 0) { // if at eof just return EOF if (eof) { return EOF; } err = gFalse; // 2-D encoding 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; blackPixels = 0; // invariant: // refLine[b1i-1] <= codingLine[a0i] < refLine[b1i] < refLine[b1i+1] // <= columns // exception at left edge: // codingLine[a0i = 0] = refLine[b1i = 0] = 0 is possible // exception at right edge: // refLine[b1i] = refLine[b1i+1] = columns is possible 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; } } // 1-D encoding } 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; } } // check for end-of-line marker, skipping over any extra zero bits // (if EncodedByteAlign is true and EndOfLine is false, there can // be "false" EOL markers -- i.e., if the last n unused bits in // row i are set to zero, and the first 11-n bits in row i+1 // happen to be zero -- so we don't look for EOL markers in this // case) 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; } } // byte-align the row // (Adobe apparently doesn't do byte alignment after EOL markers // -- I've seen CCITT image data streams in two different formats, // both with the byteAlign flag set: // 1. xx:x0:01:yy:yy // 2. xx:00:1y:yy:yy // where xx is the previous line, yy is the next line, and colons // separate bytes.) if (byteAlign && !gotEOL) { inputBits &= ~7; } // check for end of stream if (lookBits(1) == EOF) { eof = gTrue; } // get 2D encoding tag if (!eof && encoding > 0) { nextLine2D = !lookBits(1); eatBits(1); } // check for end-of-block marker if (endOfBlock && !endOfLine && byteAlign) { // in this case, we didn't check for an EOL code above, so we // need to check here 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; } // look for an end-of-line marker after an error -- we only do // this if we know the stream contains end-of-line markers because // the "just plow on" technique tends to work better otherwise } 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); } } // set up for output if (codingLine[0] > 0) { outputBits = codingLine[a0i = 0]; } else { outputBits = codingLine[a0i = 1]; } ++row; } // get a byte 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; }
nan
null
10,752
280129395979896768363568972208099873201
444
Initialize refLine totally Fixes uninitialized memory read in 1004.pdf.asan.7.3
null
radare2
224e6bc13fa353dd3b7f7a2334588f1c4229e58d
1
static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_byte = data[0]; ut64 offset = addr - java_get_method_start (); ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1; if (op_byte == 0xaa) { // handle a table switch condition if (pos + 8 > len) { return op->size; } int min_val = (ut32)(UINT (data, pos + 4)), max_val = (ut32)(UINT (data, pos + 8)); ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0; op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc); RAnalCaseOp *caseop = NULL; pos += 12; if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) { //caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset); for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) { //ut32 value = (ut32)(UINT (data, pos)); if (pos + 4 >= len) { // switch is too big cant read further break; } int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos)); caseop = r_anal_switch_op_add_case (op->switch_op, addr + pos, cur_case + min_val, addr + offset); if (caseop) { caseop->bb_ref_to = addr+offset; caseop->bb_ref_from = addr; // TODO figure this one out } } } else { eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr); } } op->size = pos; return op->size; }
nan
null
10,753
287953916860564690516414183905035703312
40
Fix #10296 - Heap out of bounds read in java_switch_op()
null
radare2
66191f780863ea8c66ace4040d0d04a8842e8432
1
static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) { // Skip whitespace while (begin && isspace ((ut8)str[*begin])) { ++(*begin); } if (!str[*begin]) { // null byte *end = *begin; return TT_EOF; } else if (isalpha ((ut8)str[*begin])) { // word token *end = *begin; while (end && isalnum ((ut8)str[*end])) { ++(*end); } return TT_WORD; } else if (isdigit ((ut8)str[*begin])) { // number token *end = *begin; while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex. ++(*end); } return TT_NUMBER; } else { // special character: [, ], +, *, ... *end = *begin + 1; return TT_SPECIAL; } }
nan
null
10,754
263590908712476924865670924399220950000
26
Fix #12239 - crash in the x86.nz assembler ##asm (#12252)
null
libav
58b2e0f0f2fc96c1158e04f8aba95cbe6157a1a3
1
static av_cold int vqa_decode_init(AVCodecContext *avctx) { VqaContext *s = avctx->priv_data; int i, j, codebook_index; s->avctx = avctx; avctx->pix_fmt = PIX_FMT_PAL8; /* make sure the extradata made it */ if (s->avctx->extradata_size != VQA_HEADER_SIZE) { av_log(s->avctx, AV_LOG_ERROR, " VQA video: expected extradata size of %d\n", VQA_HEADER_SIZE); return -1; } /* load up the VQA parameters from the header */ s->vqa_version = s->avctx->extradata[0]; s->width = AV_RL16(&s->avctx->extradata[6]); s->height = AV_RL16(&s->avctx->extradata[8]); if(av_image_check_size(s->width, s->height, 0, avctx)){ s->width= s->height= 0; return -1; } s->vector_width = s->avctx->extradata[10]; s->vector_height = s->avctx->extradata[11]; s->partial_count = s->partial_countdown = s->avctx->extradata[13]; /* the vector dimensions have to meet very stringent requirements */ if ((s->vector_width != 4) || ((s->vector_height != 2) && (s->vector_height != 4))) { /* return without further initialization */ return -1; } /* allocate codebooks */ s->codebook_size = MAX_CODEBOOK_SIZE; s->codebook = av_malloc(s->codebook_size); if (!s->codebook) goto fail; s->next_codebook_buffer = av_malloc(s->codebook_size); if (!s->next_codebook_buffer) goto fail; /* allocate decode buffer */ s->decode_buffer_size = (s->width / s->vector_width) * (s->height / s->vector_height) * 2; s->decode_buffer = av_malloc(s->decode_buffer_size); if (!s->decode_buffer) goto fail; /* initialize the solid-color vectors */ if (s->vector_height == 4) { codebook_index = 0xFF00 * 16; for (i = 0; i < 256; i++) for (j = 0; j < 16; j++) s->codebook[codebook_index++] = i; } else { codebook_index = 0xF00 * 8; for (i = 0; i < 256; i++) for (j = 0; j < 8; j++) s->codebook[codebook_index++] = i; } s->next_codebook_buffer_index = 0; s->frame.data[0] = NULL; return 0; fail: av_freep(&s->codebook); av_freep(&s->next_codebook_buffer); av_freep(&s->decode_buffer); return AVERROR(ENOMEM); }
nan
null
10,755
165589397962084276231359256169437536630
72
vqavideo: return error if image size is not a multiple of block size The decoder assumes in various places that the image size is a multiple of the block size, and there is no obvious way to support odd sizes. Bailing out early if the header specifies a bad size avoids various errors later on. Fixes CVE-2012-0947. Signed-off-by: Mans Rullgard <mans@mansr.com>
null
WavPack
070ef6f138956d9ea9612e69586152339dbefe51
1
int WavpackSetConfiguration64 (WavpackContext *wpc, WavpackConfig *config, int64_t total_samples, const unsigned char *chan_ids) { uint32_t flags, bps = 0; uint32_t chan_mask = config->channel_mask; int num_chans = config->num_channels; int i; wpc->stream_version = (config->flags & CONFIG_COMPATIBLE_WRITE) ? CUR_STREAM_VERS : MAX_STREAM_VERS; if ((config->qmode & QMODE_DSD_AUDIO) && config->bytes_per_sample == 1 && config->bits_per_sample == 8) { #ifdef ENABLE_DSD wpc->dsd_multiplier = 1; flags = DSD_FLAG; for (i = 14; i >= 0; --i) if (config->sample_rate % sample_rates [i] == 0) { int divisor = config->sample_rate / sample_rates [i]; if (divisor && (divisor & (divisor - 1)) == 0) { config->sample_rate /= divisor; wpc->dsd_multiplier = divisor; break; } } // most options that don't apply to DSD we can simply ignore for now, but NOT hybrid mode! if (config->flags & CONFIG_HYBRID_FLAG) { strcpy (wpc->error_message, "hybrid mode not available for DSD!"); return FALSE; } // with DSD, very few PCM options work (or make sense), so only allow those that do config->flags &= (CONFIG_HIGH_FLAG | CONFIG_MD5_CHECKSUM | CONFIG_PAIR_UNDEF_CHANS); config->float_norm_exp = config->xmode = 0; #else strcpy (wpc->error_message, "libwavpack not configured for DSD!"); return FALSE; #endif } else flags = config->bytes_per_sample - 1; wpc->total_samples = total_samples; wpc->config.sample_rate = config->sample_rate; wpc->config.num_channels = config->num_channels; wpc->config.channel_mask = config->channel_mask; wpc->config.bits_per_sample = config->bits_per_sample; wpc->config.bytes_per_sample = config->bytes_per_sample; wpc->config.block_samples = config->block_samples; wpc->config.flags = config->flags; wpc->config.qmode = config->qmode; if (config->flags & CONFIG_VERY_HIGH_FLAG) wpc->config.flags |= CONFIG_HIGH_FLAG; for (i = 0; i < 15; ++i) if (wpc->config.sample_rate == sample_rates [i]) break; flags |= i << SRATE_LSB; // all of this stuff only applies to PCM if (!(flags & DSD_FLAG)) { if (config->float_norm_exp) { wpc->config.float_norm_exp = config->float_norm_exp; wpc->config.flags |= CONFIG_FLOAT_DATA; flags |= FLOAT_DATA; } else flags |= ((config->bytes_per_sample * 8) - config->bits_per_sample) << SHIFT_LSB; if (config->flags & CONFIG_HYBRID_FLAG) { flags |= HYBRID_FLAG | HYBRID_BITRATE | HYBRID_BALANCE; if (!(wpc->config.flags & CONFIG_SHAPE_OVERRIDE)) { wpc->config.flags |= CONFIG_HYBRID_SHAPE | CONFIG_AUTO_SHAPING; flags |= HYBRID_SHAPE | NEW_SHAPING; } else if (wpc->config.flags & CONFIG_HYBRID_SHAPE) { wpc->config.shaping_weight = config->shaping_weight; flags |= HYBRID_SHAPE | NEW_SHAPING; } if (wpc->config.flags & (CONFIG_CROSS_DECORR | CONFIG_OPTIMIZE_WVC)) flags |= CROSS_DECORR; if (config->flags & CONFIG_BITRATE_KBPS) { bps = (uint32_t) floor (config->bitrate * 256000.0 / config->sample_rate / config->num_channels + 0.5); if (bps > (64 << 8)) bps = 64 << 8; } else bps = (uint32_t) floor (config->bitrate * 256.0 + 0.5); } else flags |= CROSS_DECORR; if (!(config->flags & CONFIG_JOINT_OVERRIDE) || (config->flags & CONFIG_JOINT_STEREO)) flags |= JOINT_STEREO; if (config->flags & CONFIG_CREATE_WVC) wpc->wvc_flag = TRUE; } // if a channel-identities string was specified, process that here, otherwise all channels // not present in the channel mask are considered "unassigned" if (chan_ids) { int lastchan = 0, mask_copy = chan_mask; if ((int) strlen ((char *) chan_ids) > num_chans) { // can't be more than num channels! strcpy (wpc->error_message, "chan_ids longer than num channels!"); return FALSE; } // skip past channels that are specified in the channel mask (no reason to store those) while (*chan_ids) if (*chan_ids <= 32 && *chan_ids > lastchan && (mask_copy & (1 << (*chan_ids-1)))) { mask_copy &= ~(1 << (*chan_ids-1)); lastchan = *chan_ids++; } else break; // now scan the string for an actually defined channel (and don't store if there aren't any) for (i = 0; chan_ids [i]; i++) if (chan_ids [i] != 0xff) { wpc->channel_identities = (unsigned char *) strdup ((char *) chan_ids); break; } } // This loop goes through all the channels and creates the Wavpack "streams" for them to go in. // A stream can hold either one or two channels, so we have several rules to determine how many // channels will go in each stream. for (wpc->current_stream = 0; num_chans; wpc->current_stream++) { WavpackStream *wps = malloc (sizeof (WavpackStream)); unsigned char left_chan_id = 0, right_chan_id = 0; int pos, chans = 1; // allocate the stream and initialize the pointer to it wpc->streams = realloc (wpc->streams, (wpc->current_stream + 1) * sizeof (wpc->streams [0])); wpc->streams [wpc->current_stream] = wps; CLEAR (*wps); // if there are any bits [still] set in the channel_mask, get the next one or two IDs from there if (chan_mask) for (pos = 0; pos < 32; ++pos) if (chan_mask & (1 << pos)) { if (left_chan_id) { right_chan_id = pos + 1; break; } else { chan_mask &= ~(1 << pos); left_chan_id = pos + 1; } } // next check for any channels identified in the channel-identities string while (!right_chan_id && chan_ids && *chan_ids) if (left_chan_id) right_chan_id = *chan_ids; else left_chan_id = *chan_ids++; // assume anything we did not get is "unassigned" if (!left_chan_id) left_chan_id = right_chan_id = 0xff; else if (!right_chan_id) right_chan_id = 0xff; // if we have 2 channels, this is where we decide if we can combine them into one stream: // 1. they are "unassigned" and we've been told to combine unassigned pairs, or // 2. they appear together in the valid "pairings" list if (num_chans >= 2) { if ((config->flags & CONFIG_PAIR_UNDEF_CHANS) && left_chan_id == 0xff && right_chan_id == 0xff) chans = 2; else for (i = 0; i < NUM_STEREO_PAIRS; ++i) if ((left_chan_id == stereo_pairs [i].a && right_chan_id == stereo_pairs [i].b) || (left_chan_id == stereo_pairs [i].b && right_chan_id == stereo_pairs [i].a)) { if (right_chan_id <= 32 && (chan_mask & (1 << (right_chan_id-1)))) chan_mask &= ~(1 << (right_chan_id-1)); else if (chan_ids && *chan_ids == right_chan_id) chan_ids++; chans = 2; break; } } num_chans -= chans; if (num_chans && wpc->current_stream == NEW_MAX_STREAMS - 1) break; memcpy (wps->wphdr.ckID, "wvpk", 4); wps->wphdr.ckSize = sizeof (WavpackHeader) - 8; SET_TOTAL_SAMPLES (wps->wphdr, wpc->total_samples); wps->wphdr.version = wpc->stream_version; wps->wphdr.flags = flags; wps->bits = bps; if (!wpc->current_stream) wps->wphdr.flags |= INITIAL_BLOCK; if (!num_chans) wps->wphdr.flags |= FINAL_BLOCK; if (chans == 1) { wps->wphdr.flags &= ~(JOINT_STEREO | CROSS_DECORR | HYBRID_BALANCE); wps->wphdr.flags |= MONO_FLAG; } } wpc->num_streams = wpc->current_stream; wpc->current_stream = 0; if (num_chans) { strcpy (wpc->error_message, "too many channels!"); return FALSE; } if (config->flags & CONFIG_EXTRA_MODE) wpc->config.xmode = config->xmode ? config->xmode : 1; return TRUE; }
nan
null
10,756
37881151474472779126549397043449514511
234
issue #53: error out on zero sample rate
null
FFmpeg
8df6884832ec413cf032dfaa45c23b1c7876670c
1
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options) { int ret = 0; int codec_init_ok = 0; AVDictionary *tmp = NULL; const AVPixFmtDescriptor *pixdesc; if (avcodec_is_open(avctx)) return 0; if ((!codec && !avctx->codec)) { av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n"); return AVERROR(EINVAL); } if ((codec && avctx->codec && codec != avctx->codec)) { av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, " "but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name); return AVERROR(EINVAL); } if (!codec) codec = avctx->codec; if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE) return AVERROR(EINVAL); if (options) av_dict_copy(&tmp, *options, 0); ff_lock_avcodec(avctx, codec); avctx->internal = av_mallocz(sizeof(*avctx->internal)); if (!avctx->internal) { ret = AVERROR(ENOMEM); goto end; } avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool)); if (!avctx->internal->pool) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->to_free = av_frame_alloc(); if (!avctx->internal->to_free) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->compat_decode_frame = av_frame_alloc(); if (!avctx->internal->compat_decode_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_frame = av_frame_alloc(); if (!avctx->internal->buffer_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_pkt = av_packet_alloc(); if (!avctx->internal->buffer_pkt) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->ds.in_pkt = av_packet_alloc(); if (!avctx->internal->ds.in_pkt) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->last_pkt_props = av_packet_alloc(); if (!avctx->internal->last_pkt_props) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->skip_samples_multiplier = 1; if (codec->priv_data_size > 0) { if (!avctx->priv_data) { avctx->priv_data = av_mallocz(codec->priv_data_size); if (!avctx->priv_data) { ret = AVERROR(ENOMEM); goto end; } if (codec->priv_class) { *(const AVClass **)avctx->priv_data = codec->priv_class; av_opt_set_defaults(avctx->priv_data); } } if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0) goto free_and_end; } else { avctx->priv_data = NULL; } if ((ret = av_opt_set_dict(avctx, &tmp)) < 0) goto free_and_end; if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) { av_log(avctx, AV_LOG_ERROR, "Codec (%s) not on whitelist \'%s\'\n", codec->name, avctx->codec_whitelist); ret = AVERROR(EINVAL); goto free_and_end; } // only call ff_set_dimensions() for non H.264/VP6F/DXV codecs so as not to overwrite previously setup dimensions if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) { if (avctx->coded_width && avctx->coded_height) ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height); else if (avctx->width && avctx->height) ret = ff_set_dimensions(avctx, avctx->width, avctx->height); if (ret < 0) goto free_and_end; } if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height) && ( av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0 || av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) { av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n"); ff_set_dimensions(avctx, 0, 0); } if (avctx->width > 0 && avctx->height > 0) { if (av_image_check_sar(avctx->width, avctx->height, avctx->sample_aspect_ratio) < 0) { av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n", avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den); avctx->sample_aspect_ratio = (AVRational){ 0, 1 }; } } /* if the decoder init function was already called previously, * free the already allocated subtitle_header before overwriting it */ if (av_codec_is_decoder(codec)) av_freep(&avctx->subtitle_header); if (avctx->channels > FF_SANE_NB_CHANNELS) { av_log(avctx, AV_LOG_ERROR, "Too many channels: %d\n", avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } avctx->codec = codec; if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) && avctx->codec_id == AV_CODEC_ID_NONE) { avctx->codec_type = codec->type; avctx->codec_id = codec->id; } if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) { av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n"); ret = AVERROR(EINVAL); goto free_and_end; } avctx->frame_number = 0; avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id); if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder"; AVCodec *codec2; av_log(avctx, AV_LOG_ERROR, "The %s '%s' is experimental but experimental codecs are not enabled, " "add '-strict %d' if you want to use it.\n", codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL); codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id); if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL)) av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n", codec_string, codec2->name); ret = AVERROR_EXPERIMENTAL; goto free_and_end; } if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && (!avctx->time_base.num || !avctx->time_base.den)) { avctx->time_base.num = 1; avctx->time_base.den = avctx->sample_rate; } if (!HAVE_THREADS) av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n"); if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) { ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL); ff_lock_avcodec(avctx, codec); if (ret < 0) goto free_and_end; } if (av_codec_is_decoder(avctx->codec)) { ret = ff_decode_bsfs_init(avctx); if (ret < 0) goto free_and_end; } if (HAVE_THREADS && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) { ret = ff_thread_init(avctx); if (ret < 0) { goto free_and_end; } } if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS)) avctx->thread_count = 1; if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) { av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n", avctx->codec->max_lowres); avctx->lowres = avctx->codec->max_lowres; } if (av_codec_is_encoder(avctx->codec)) { int i; #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS avctx->coded_frame = av_frame_alloc(); if (!avctx->coded_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } FF_ENABLE_DEPRECATION_WARNINGS #endif if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) { av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n"); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->sample_fmts) { for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) { if (avctx->sample_fmt == avctx->codec->sample_fmts[i]) break; if (avctx->channels == 1 && av_get_planar_sample_fmt(avctx->sample_fmt) == av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) { avctx->sample_fmt = avctx->codec->sample_fmts[i]; break; } } if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) { char buf[128]; snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt); av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n", (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->codec->pix_fmts) { for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++) if (avctx->pix_fmt == avctx->codec->pix_fmts[i]) break; if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG) && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) { char buf[128]; snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt); av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n", (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P) avctx->color_range = AVCOL_RANGE_JPEG; } if (avctx->codec->supported_samplerates) { for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++) if (avctx->sample_rate == avctx->codec->supported_samplerates[i]) break; if (avctx->codec->supported_samplerates[i] == 0) { av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->sample_rate < 0) { av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->channel_layouts) { if (!avctx->channel_layout) { av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n"); } else { for (i = 0; avctx->codec->channel_layouts[i] != 0; i++) if (avctx->channel_layout == avctx->codec->channel_layouts[i]) break; if (avctx->codec->channel_layouts[i] == 0) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf); ret = AVERROR(EINVAL); goto free_and_end; } } } if (avctx->channel_layout && avctx->channels) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, "Channel layout '%s' with %d channels does not match number of specified channels %d\n", buf, channels, avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } } else if (avctx->channel_layout) { avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout); } if (avctx->channels < 0) { av_log(avctx, AV_LOG_ERROR, "Specified number of channels %d is not supported\n", avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) { pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt); if ( avctx->bits_per_raw_sample < 0 || (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) { av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n", avctx->bits_per_raw_sample, pixdesc->comp[0].depth); avctx->bits_per_raw_sample = pixdesc->comp[0].depth; } if (avctx->width <= 0 || avctx->height <= 0) { av_log(avctx, AV_LOG_ERROR, "dimensions not set\n"); ret = AVERROR(EINVAL); goto free_and_end; } } if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO) && avctx->bit_rate>0 && avctx->bit_rate<1000) { av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", avctx->bit_rate, avctx->bit_rate); } if (!avctx->rc_initial_buffer_occupancy) avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4; if (avctx->ticks_per_frame && avctx->time_base.num && avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) { av_log(avctx, AV_LOG_ERROR, "ticks_per_frame %d too large for the timebase %d/%d.", avctx->ticks_per_frame, avctx->time_base.num, avctx->time_base.den); goto free_and_end; } if (avctx->hw_frames_ctx) { AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data; if (frames_ctx->format != avctx->pix_fmt) { av_log(avctx, AV_LOG_ERROR, "Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n"); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE && avctx->sw_pix_fmt != frames_ctx->sw_format) { av_log(avctx, AV_LOG_ERROR, "Mismatching AVCodecContext.sw_pix_fmt (%s) " "and AVHWFramesContext.sw_format (%s)\n", av_get_pix_fmt_name(avctx->sw_pix_fmt), av_get_pix_fmt_name(frames_ctx->sw_format)); ret = AVERROR(EINVAL); goto free_and_end; } avctx->sw_pix_fmt = frames_ctx->sw_format; } } avctx->pts_correction_num_faulty_pts = avctx->pts_correction_num_faulty_dts = 0; avctx->pts_correction_last_pts = avctx->pts_correction_last_dts = INT64_MIN; if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO) av_log(avctx, AV_LOG_WARNING, "gray decoding requested but not enabled at configuration time\n"); if ( avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME) || avctx->internal->frame_thread_encoder)) { ret = avctx->codec->init(avctx); if (ret < 0) { goto free_and_end; } codec_init_ok = 1; } ret=0; if (av_codec_is_decoder(avctx->codec)) { if (!avctx->bit_rate) avctx->bit_rate = get_bit_rate(avctx); /* validate channel layout from the decoder */ if (avctx->channel_layout) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (!avctx->channels) avctx->channels = channels; else if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_WARNING, "Channel layout '%s' with %d channels does not match specified number of channels %d: " "ignoring specified channel layout\n", buf, channels, avctx->channels); avctx->channel_layout = 0; } } if (avctx->channels && avctx->channels < 0 || avctx->channels > FF_SANE_NB_CHANNELS) { ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->bits_per_coded_sample < 0) { ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->sub_charenc) { if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) { av_log(avctx, AV_LOG_ERROR, "Character encoding is only " "supported with subtitles codecs\n"); ret = AVERROR(EINVAL); goto free_and_end; } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) { av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, " "subtitles character encoding will be ignored\n", avctx->codec_descriptor->name); avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING; } else { /* input character encoding is set for a text based subtitle * codec at this point */ if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC) avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER; if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) { #if CONFIG_ICONV iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc); if (cd == (iconv_t)-1) { ret = AVERROR(errno); av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context " "with input character encoding \"%s\"\n", avctx->sub_charenc); goto free_and_end; } iconv_close(cd); #else av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles " "conversion needs a libavcodec built with iconv support " "for this codec\n"); ret = AVERROR(ENOSYS); goto free_and_end; #endif } } } #if FF_API_AVCTX_TIMEBASE if (avctx->framerate.num > 0 && avctx->framerate.den > 0) avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1})); #endif } if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) { av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class); } end: ff_unlock_avcodec(codec); if (options) { av_dict_free(options); *options = tmp; } return ret; free_and_end: if (avctx->codec && (codec_init_ok || (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))) avctx->codec->close(avctx); if (codec->priv_class && codec->priv_data_size) av_opt_free(avctx->priv_data); av_opt_free(avctx); #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS av_frame_free(&avctx->coded_frame); FF_ENABLE_DEPRECATION_WARNINGS #endif av_dict_free(&tmp); av_freep(&avctx->priv_data); if (avctx->internal) { av_frame_free(&avctx->internal->to_free); av_frame_free(&avctx->internal->compat_decode_frame); av_frame_free(&avctx->internal->buffer_frame); av_packet_free(&avctx->internal->buffer_pkt); av_packet_free(&avctx->internal->last_pkt_props); av_packet_free(&avctx->internal->ds.in_pkt); ff_decode_bsfs_uninit(avctx); av_freep(&avctx->internal->pool); } av_freep(&avctx->internal); avctx->codec = NULL; goto end; }
nan
null
10,757
186955190953485436212019393923515027732
518
avcodec/utils: Check close before calling it Fixes: NULL pointer dereference Fixes: 15733/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_IDF_fuzzer-5658616977162240 Reviewed-by: Paul B Mahol <onemda@gmail.com> Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
faad2
942c3e0aee748ea6fe97cb2c1aa5893225316174
1
void faad_resetbits(bitfile *ld, int bits) { uint32_t tmp; int words = bits >> 5; int remainder = bits & 0x1F; ld->bytes_left = ld->buffer_size - words*4; if (ld->bytes_left >= 4) { tmp = getdword(&ld->start[words]); ld->bytes_left -= 4; } else { tmp = getdword_n(&ld->start[words], ld->bytes_left); ld->bytes_left = 0; } ld->bufa = tmp; if (ld->bytes_left >= 4) { tmp = getdword(&ld->start[words+1]); ld->bytes_left -= 4; } else { tmp = getdword_n(&ld->start[words+1], ld->bytes_left); ld->bytes_left = 0; } ld->bufb = tmp; ld->bits_left = 32 - remainder; ld->tail = &ld->start[words+2]; /* recheck for reading too many bytes */ ld->error = 0; // if (ld->bytes_left == 0) // ld->no_more_reading = 1; // if (ld->bytes_left < 0) // ld->error = 1; }
nan
null
10,758
41758919436567695093878274995728552969
38
Fix a couple buffer overflows https://hackerone.com/reports/502816 https://hackerone.com/reports/507858 https://github.com/videolan/vlc/blob/master/contrib/src/faad2/faad2-fix-overflows.patch
null
poppler
8b6dc55e530b2f5ede6b9dfb64aafdd1d5836492
1
SplashPath *Splash::makeDashedPath(SplashPath *path) { SplashPath *dPath; SplashCoord lineDashTotal; SplashCoord lineDashStartPhase, lineDashDist, segLen; SplashCoord x0, y0, x1, y1, xa, ya; GBool lineDashStartOn, lineDashOn, newPath; int lineDashStartIdx, lineDashIdx; int i, j, k; lineDashTotal = 0; for (i = 0; i < state->lineDashLength; ++i) { lineDashTotal += state->lineDash[i]; } // Acrobat simply draws nothing if the dash array is [0] if (lineDashTotal == 0) { return new SplashPath(); } lineDashStartPhase = state->lineDashPhase; i = splashFloor(lineDashStartPhase / lineDashTotal); lineDashStartPhase -= (SplashCoord)i * lineDashTotal; lineDashStartOn = gTrue; lineDashStartIdx = 0; if (lineDashStartPhase > 0) { while (lineDashStartPhase >= state->lineDash[lineDashStartIdx]) { lineDashStartOn = !lineDashStartOn; lineDashStartPhase -= state->lineDash[lineDashStartIdx]; ++lineDashStartIdx; } } dPath = new SplashPath(); // process each subpath i = 0; while (i < path->length) { // find the end of the subpath for (j = i; j < path->length - 1 && !(path->flags[j] & splashPathLast); ++j) ; // initialize the dash parameters lineDashOn = lineDashStartOn; lineDashIdx = lineDashStartIdx; lineDashDist = state->lineDash[lineDashIdx] - lineDashStartPhase; // process each segment of the subpath newPath = gTrue; for (k = i; k < j; ++k) { // grab the segment x0 = path->pts[k].x; y0 = path->pts[k].y; x1 = path->pts[k+1].x; y1 = path->pts[k+1].y; segLen = splashDist(x0, y0, x1, y1); // process the segment while (segLen > 0) { if (lineDashDist >= segLen) { if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(x1, y1); } lineDashDist -= segLen; segLen = 0; } else { xa = x0 + (lineDashDist / segLen) * (x1 - x0); ya = y0 + (lineDashDist / segLen) * (y1 - y0); if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(xa, ya); } x0 = xa; y0 = ya; segLen -= lineDashDist; lineDashDist = 0; } // get the next entry in the dash array if (lineDashDist <= 0) { lineDashOn = !lineDashOn; if (++lineDashIdx == state->lineDashLength) { lineDashIdx = 0; } lineDashDist = state->lineDash[lineDashIdx]; newPath = gTrue; } } } i = j + 1; } if (dPath->length == 0) { GBool allSame = gTrue; for (int i = 0; allSame && i < path->length - 1; ++i) { allSame = path->pts[i].x == path->pts[i + 1].x && path->pts[i].y == path->pts[i + 1].y; } if (allSame) { x0 = path->pts[0].x; y0 = path->pts[0].y; dPath->moveTo(x0, y0); dPath->lineTo(x0, y0); } } return dPath; }
nan
null
10,760
112288227865298477019344533702845771247
116
Fix invalid memory access in 1150.pdf.asan.8.69
null
capstone
87a25bb543c8e4c09b48d4b4a6c7db31ce58df06
1
x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access) { unsigned int first = 0; unsigned int last = ARR_SIZE(insn_regs_intel) - 1; unsigned int mid = ARR_SIZE(insn_regs_intel) / 2; if (!intel_regs_sorted) { memcpy(insn_regs_intel_sorted, insn_regs_intel, sizeof(insn_regs_intel_sorted)); qsort(insn_regs_intel_sorted, ARR_SIZE(insn_regs_intel_sorted), sizeof(struct insn_reg), regs_cmp); intel_regs_sorted = true; } while (first <= last) { if (insn_regs_intel_sorted[mid].insn < id) { first = mid + 1; } else if (insn_regs_intel_sorted[mid].insn == id) { if (access) { *access = insn_regs_intel_sorted[mid].access; } return insn_regs_intel_sorted[mid].reg; } else { if (mid == 0) break; last = mid - 1; } mid = (first + last) / 2; } // not found return 0; }
nan
null
10,761
314014179055219463021422080478462501987
34
x86: fast path checking for X86_insn_reg_intel()
null
FFmpeg
ed22dc22216f74c75ee7901f82649e1ff725ba50
1
static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { //info->num_ind_sub++; avpriv_request_sample(track->par, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; }
nan
null
10,762
94813621897229415812069291681101452703
133
avformat/movenc: Check that frame_types other than EAC3_FRAME_TYPE_INDEPENDENT have a supported substream id Fixes: out of array access Fixes: ffmpeg_bof_1.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
virglrenderer
6eb13f7a2dcf391ec9e19b4c2a79e68305f63c22
1
static void vrend_renderer_init_blit_ctx(struct vrend_blitter_ctx *blit_ctx) { struct virgl_gl_ctx_param ctx_params; int i; if (blit_ctx->initialised) { vrend_clicbs->make_current(0, blit_ctx->gl_context); return; } ctx_params.shared = true; ctx_params.major_ver = VREND_GL_VER_MAJOR; ctx_params.minor_ver = VREND_GL_VER_MINOR; blit_ctx->gl_context = vrend_clicbs->create_gl_context(0, &ctx_params); vrend_clicbs->make_current(0, blit_ctx->gl_context); glGenVertexArrays(1, &blit_ctx->vaoid); glGenFramebuffers(1, &blit_ctx->fb_id); glGenBuffers(1, &blit_ctx->vbo_id); blit_build_vs_passthrough(blit_ctx); for (i = 0; i < 4; i++) blit_ctx->vertices[i][0][3] = 1; /*v.w*/ glBindVertexArray(blit_ctx->vaoid); glBindBuffer(GL_ARRAY_BUFFER, blit_ctx->vbo_id); }
nan
null
10,763
81858904308721851551049096963995820299
26
vrend: fix memory leak in int blit context The 'blit_ctx->initialised' is not setted to true. Every time init blit context, it will create a new 'blit_ctx->gl_context' thus causing a memory leak. This patch avoid this. Signed-off-by: Li Qiang <liq3ea@gmail.com> Signed-off-by: Dave Airlie <airlied@redhat.com>
null
radare2
ad55822430a03fe075221b543efb434567e9e431
1
static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int MI, int MA, int paddr, int ins_size, int insns_size, char *class_name, int regsz, int debug_info_off) { struct r_bin_t *rbin = binfile->rbin; const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL); const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off; ut64 line_start; ut64 parameters_size; ut64 param_type_idx; ut16 argReg = regsz - ins_size; ut64 source_file_idx = c->source_file; RList *params, *debug_positions, *emitted_debug_locals = NULL; bool keep = true; if (argReg >= regsz) { //return; // this return breaks tests } p4 = r_uleb128 (p4, p4_end - p4, &line_start); p4 = r_uleb128 (p4, p4_end - p4, &parameters_size); // TODO: check when we should use source_file // The state machine consists of five registers ut32 address = 0; ut32 line = line_start; if (!(debug_positions = r_list_newf ((RListFree)free))) { return; } if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) { r_list_free (debug_positions); return; } struct dex_debug_local_t debug_locals[regsz]; memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz); if (!(MA & 0x0008)) { debug_locals[argReg].name = "this"; debug_locals[argReg].descriptor = r_str_newf("%s;", class_name); debug_locals[argReg].startAddress = 0; debug_locals[argReg].signature = NULL; debug_locals[argReg].live = true; argReg++; } if (!(params = dex_method_signature2 (bin, MI))) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); return; } RListIter *iter = r_list_iterator (params); char *name; char *type; int reg; r_list_foreach (params, iter, type) { if ((argReg >= regsz) || !type || parameters_size <= 0) { r_list_free (debug_positions); r_list_free (params); r_list_free (emitted_debug_locals); return; } p4 = r_uleb128 (p4, p4_end - p4, &param_type_idx); // read uleb128p1 param_type_idx -= 1; name = getstr (bin, param_type_idx); reg = argReg; switch (type[0]) { case 'D': case 'J': argReg += 2; break; default: argReg += 1; break; } if (name) { debug_locals[reg].name = name; debug_locals[reg].descriptor = type; debug_locals[reg].signature = NULL; debug_locals[reg].startAddress = address; debug_locals[reg].live = true; } --parameters_size; } ut8 opcode = *(p4++) & 0xff; while (keep) { switch (opcode) { case 0x0: // DBG_END_SEQUENCE keep = false; break; case 0x1: // DBG_ADVANCE_PC { ut64 addr_diff; p4 = r_uleb128 (p4, p4_end - p4, &addr_diff); address += addr_diff; } break; case 0x2: // DBG_ADVANCE_LINE { st64 line_diff = r_sleb128 (&p4, p4_end); line += line_diff; } break; case 0x3: // DBG_START_LOCAL { ut64 register_num; ut64 name_idx; ut64 type_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = NULL; debug_locals[register_num].live = true; //eprintf("DBG_START_LOCAL %x %x %x\n", register_num, name_idx, type_idx); } break; case 0x4: //DBG_START_LOCAL_EXTENDED { ut64 register_num; ut64 name_idx; ut64 type_idx; ut64 sig_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &sig_idx); sig_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = getstr (bin, sig_idx); debug_locals[register_num].live = true; } break; case 0x5: // DBG_END_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].live = false; } break; case 0x6: // DBG_RESTART_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (!debug_locals[register_num].live) { debug_locals[register_num].startAddress = address; debug_locals[register_num].live = true; } } break; case 0x7: //DBG_SET_PROLOGUE_END break; case 0x8: //DBG_SET_PROLOGUE_BEGIN break; case 0x9: { p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx); source_file_idx--; } break; default: { int adjusted_opcode = opcode - 0x0a; address += (adjusted_opcode / 15); line += -4 + (adjusted_opcode % 15); struct dex_debug_position_t *position = malloc (sizeof (struct dex_debug_position_t)); if (!position) { keep = false; break; } position->source_file_idx = source_file_idx; position->address = address; position->line = line; r_list_append (debug_positions, position); } break; } opcode = *(p4++) & 0xff; } if (!binfile->sdb_addrinfo) { binfile->sdb_addrinfo = sdb_new0 (); } char *fileline; char offset[64]; char *offset_ptr; RListIter *iter1; struct dex_debug_position_t *pos; r_list_foreach (debug_positions, iter1, pos) { fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line); offset_ptr = sdb_itoa (pos->address + paddr, offset, 16); sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0); sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0); } if (!dexdump) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); return; } RListIter *iter2; struct dex_debug_position_t *position; rbin->cb_printf (" positions :\n"); r_list_foreach (debug_positions, iter2, position) { rbin->cb_printf (" 0x%04llx line=%llu\n", position->address, position->line); } rbin->cb_printf (" locals :\n"); RListIter *iter3; struct dex_debug_local_t *local; r_list_foreach (emitted_debug_locals, iter3, local) { if (local->signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor, local->signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor); } } for (reg = 0; reg < regsz; reg++) { if (debug_locals[reg].live) { if (debug_locals[reg].signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s " "%s\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor, debug_locals[reg].signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s" "\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor); } } } r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); }
nan
null
10,764
248508498085489946556072611335408241404
328
Fix #6836 - oob write in dex
null
qemu
0be839a2701369f669532ea5884c15bead1c6e08
1
static inline void *host_from_stream_offset(QEMUFile *f, ram_addr_t offset, int flags) { static RAMBlock *block = NULL; char id[256]; uint8_t len; if (flags & RAM_SAVE_FLAG_CONTINUE) { if (!block) { error_report("Ack, bad migration stream!"); return NULL; } return memory_region_get_ram_ptr(block->mr) + offset; } len = qemu_get_byte(f); qemu_get_buffer(f, (uint8_t *)id, len); id[len] = 0; QTAILQ_FOREACH(block, &ram_list.blocks, next) { if (!strncmp(id, block->idstr, sizeof(id))) return memory_region_get_ram_ptr(block->mr) + offset; } error_report("Can't find block %s!", id); return NULL; }
nan
null
10,765
210208517146366447768659074729777842860
29
migration: fix parameter validation on ram load During migration, the values read from migration stream during ram load are not validated. Especially offset in host_from_stream_offset() and also the length of the writes in the callers of said function. To fix this, we need to make sure that the [offset, offset + length] range fits into one of the allocated memory regions. Validating addr < len should be sufficient since data seems to always be managed in TARGET_PAGE_SIZE chunks. Fixes: CVE-2014-7840 Note: follow-up patches add extra checks on each block->host access. Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Reviewed-by: Paolo Bonzini <pbonzini@redhat.com> Reviewed-by: Dr. David Alan Gilbert <dgilbert@redhat.com> Signed-off-by: Amit Shah <amit.shah@redhat.com>
null
qemu
362786f14a753d8a5256ef97d7c10ed576d6572b
1
void net_checksum_calculate(uint8_t *data, int length) { int hlen, plen, proto, csum_offset; uint16_t csum; if ((data[14] & 0xf0) != 0x40) return; /* not IPv4 */ hlen = (data[14] & 0x0f) * 4; plen = (data[16] << 8 | data[17]) - hlen; proto = data[23]; switch (proto) { case PROTO_TCP: csum_offset = 16; break; case PROTO_UDP: csum_offset = 6; break; default: return; } if (plen < csum_offset+2) return; data[14+hlen+csum_offset] = 0; data[14+hlen+csum_offset+1] = 0; csum = net_checksum_tcpudp(plen, proto, data+14+12, data+14+hlen); data[14+hlen+csum_offset] = csum >> 8; data[14+hlen+csum_offset+1] = csum & 0xff; }
nan
null
10,766
8961402814564433930371616899912001672
31
net: check packet payload length While computing IP checksum, 'net_checksum_calculate' reads payload length from the packet. It could exceed the given 'data' buffer size. Add a check to avoid it. Reported-by: Liu Ling <liuling-it@360.cn> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Signed-off-by: Jason Wang <jasowang@redhat.com>
null
qemu
ead7a57df37d2187813a121308213f41591bd811
1
static int ssd0323_load(QEMUFile *f, void *opaque, int version_id) { SSISlave *ss = SSI_SLAVE(opaque); ssd0323_state *s = (ssd0323_state *)opaque; int i; if (version_id != 1) return -EINVAL; s->cmd_len = qemu_get_be32(f); s->cmd = qemu_get_be32(f); for (i = 0; i < 8; i++) s->cmd_data[i] = qemu_get_be32(f); s->row = qemu_get_be32(f); s->row_start = qemu_get_be32(f); s->row_end = qemu_get_be32(f); s->col = qemu_get_be32(f); s->col_start = qemu_get_be32(f); s->col_end = qemu_get_be32(f); s->redraw = qemu_get_be32(f); s->remap = qemu_get_be32(f); s->mode = qemu_get_be32(f); qemu_get_buffer(f, s->framebuffer, sizeof(s->framebuffer)); ss->cs = qemu_get_be32(f); return 0; }
nan
null
10,767
195120517621946688591370359348465358952
28
ssd0323: fix buffer overun on invalid state load CVE-2013-4538 s->cmd_len used as index in ssd0323_transfer() to store 32-bit field. Possible this field might then be supplied by guest to overwrite a return addr somewhere. Same for row/col fields, which are indicies into framebuffer array. To fix validate after load. Additionally, validate that the row/col_start/end are within bounds; otherwise the guest can provoke an overrun by either setting the _end field so large that the row++ increments just walk off the end of the array, or by setting the _start value to something bogus and then letting the "we hit end of row" logic reset row to row_start. For completeness, validate mode as well. Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Reviewed-by: Peter Maydell <peter.maydell@linaro.org> Signed-off-by: Juan Quintela <quintela@redhat.com>
null
capstone
6fe86eef621b9849f51a5e1e5d73258a93440403
1
void * CAPSTONE_API cs_winkernel_malloc(size_t size) { // Disallow zero length allocation because they waste pool header space and, // in many cases, indicate a potential validation issue in the calling code. NT_ASSERT(size); // FP; a use of NonPagedPool is required for Windows 7 support #pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory CS_WINKERNEL_MEMBLOCK *block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag( NonPagedPool, size + sizeof(CS_WINKERNEL_MEMBLOCK), CS_WINKERNEL_POOL_TAG); if (!block) { return NULL; } block->size = size; return block->data; }
nan
null
10,768
132932202241765970842332002543975713877
17
provide a validity check to prevent against Integer overflow conditions (#870) * provide a validity check to prevent against Integer overflow conditions * fix some style issues.
null
netdata
92327c9ec211bd1616315abcb255861b130b97ca
1
inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) { debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url); int ret = 400; BUFFER *dimensions = NULL; buffer_flush(w->response.data); char *google_version = "0.6", *google_reqId = "0", *google_sig = "0", *google_out = "json", *responseHandler = NULL, *outFileName = NULL; time_t last_timestamp_in_data = 0, google_timestamp = 0; char *chart = NULL , *before_str = NULL , *after_str = NULL , *group_time_str = NULL , *points_str = NULL; int group = RRDR_GROUPING_AVERAGE; uint32_t format = DATASOURCE_JSON; uint32_t options = 0x00000000; while(url) { char *value = mystrsep(&url, "?&"); if(!value || !*value) continue; char *name = mystrsep(&value, "="); if(!name || !*name) continue; if(!value || !*value) continue; debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value); // name and value are now the parameters // they are not null and not empty if(!strcmp(name, "chart")) chart = value; else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) { if(!dimensions) dimensions = buffer_create(100); buffer_strcat(dimensions, "|"); buffer_strcat(dimensions, value); } else if(!strcmp(name, "after")) after_str = value; else if(!strcmp(name, "before")) before_str = value; else if(!strcmp(name, "points")) points_str = value; else if(!strcmp(name, "gtime")) group_time_str = value; else if(!strcmp(name, "group")) { group = web_client_api_request_v1_data_group(value, RRDR_GROUPING_AVERAGE); } else if(!strcmp(name, "format")) { format = web_client_api_request_v1_data_format(value); } else if(!strcmp(name, "options")) { options |= web_client_api_request_v1_data_options(value); } else if(!strcmp(name, "callback")) { responseHandler = value; } else if(!strcmp(name, "filename")) { outFileName = value; } else if(!strcmp(name, "tqx")) { // parse Google Visualization API options // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source char *tqx_name, *tqx_value; while(value) { tqx_value = mystrsep(&value, ";"); if(!tqx_value || !*tqx_value) continue; tqx_name = mystrsep(&tqx_value, ":"); if(!tqx_name || !*tqx_name) continue; if(!tqx_value || !*tqx_value) continue; if(!strcmp(tqx_name, "version")) google_version = tqx_value; else if(!strcmp(tqx_name, "reqId")) google_reqId = tqx_value; else if(!strcmp(tqx_name, "sig")) { google_sig = tqx_value; google_timestamp = strtoul(google_sig, NULL, 0); } else if(!strcmp(tqx_name, "out")) { google_out = tqx_value; format = web_client_api_request_v1_data_google_format(google_out); } else if(!strcmp(tqx_name, "responseHandler")) responseHandler = tqx_value; else if(!strcmp(tqx_name, "outFileName")) outFileName = tqx_value; } } } if(!chart || !*chart) { buffer_sprintf(w->response.data, "No chart id is given at the request."); goto cleanup; } RRDSET *st = rrdset_find(host, chart); if(!st) st = rrdset_find_byname(host, chart); if(!st) { buffer_strcat(w->response.data, "Chart is not found: "); buffer_strcat_htmlescape(w->response.data, chart); ret = 404; goto cleanup; } st->last_accessed_time = now_realtime_sec(); long long before = (before_str && *before_str)?str2l(before_str):0; long long after = (after_str && *after_str) ?str2l(after_str):0; int points = (points_str && *points_str)?str2i(points_str):0; long group_time = (group_time_str && *group_time_str)?str2l(group_time_str):0; debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'" , w->id , chart , (dimensions)?buffer_tostring(dimensions):"" , after , before , points , group , format , options ); if(outFileName && *outFileName) { buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName); debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName); } if(format == DATASOURCE_DATATABLE_JSONP) { if(responseHandler == NULL) responseHandler = "google.visualization.Query.setResponse"; debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'", w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName ); buffer_sprintf(w->response.data, "%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:", responseHandler, google_version, google_reqId, st->last_updated.tv_sec); } else if(format == DATASOURCE_JSONP) { if(responseHandler == NULL) responseHandler = "callback"; buffer_strcat(w->response.data, responseHandler); buffer_strcat(w->response.data, "("); } ret = rrdset2anything_api_v1(st, w->response.data, dimensions, format, points, after, before, group, group_time , options, &last_timestamp_in_data); if(format == DATASOURCE_DATATABLE_JSONP) { if(google_timestamp < last_timestamp_in_data) buffer_strcat(w->response.data, "});"); else { // the client already has the latest data buffer_flush(w->response.data); buffer_sprintf(w->response.data, "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});", responseHandler, google_version, google_reqId); } } else if(format == DATASOURCE_JSONP) buffer_strcat(w->response.data, ");"); cleanup: buffer_free(dimensions); return ret; }
nan
null
10,769
53029324079806849076547721998049436121
177
fixed vulnerabilities identified by red4sec.com (#4521)
null
Espruino
c36d30529118aa049797db43f111ddad468aad29
1
NO_INLINE JsVar *jspeFactor() { if (lex->tk==LEX_ID) { JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex)); JSP_ASSERT_MATCH(LEX_ID); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_TEMPLATE_LITERAL) jsExceptionHere(JSET_SYNTAXERROR, "Tagged template literals not supported"); else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) { JsVar *funcVar = jspeArrowFunction(0,a); jsvUnLock(a); a=funcVar; } #endif return a; } else if (lex->tk==LEX_INT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_INT); return v; } else if (lex->tk==LEX_FLOAT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_FLOAT); return v; } else if (lex->tk=='(') { JSP_ASSERT_MATCH('('); if (!jspCheckStackPosition()) return 0; #ifdef SAVE_ON_FLASH // Just parse a normal expression (which can include commas) JsVar *a = jspeExpression(); if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a); return a; #else return jspeExpressionOrArrowFunction(); #endif } else if (lex->tk==LEX_R_TRUE) { JSP_ASSERT_MATCH(LEX_R_TRUE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0; } else if (lex->tk==LEX_R_FALSE) { JSP_ASSERT_MATCH(LEX_R_FALSE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0; } else if (lex->tk==LEX_R_NULL) { JSP_ASSERT_MATCH(LEX_R_NULL); return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0; } else if (lex->tk==LEX_R_UNDEFINED) { JSP_ASSERT_MATCH(LEX_R_UNDEFINED); return 0; } else if (lex->tk==LEX_STR) { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) a = jslGetTokenValueAsVar(lex); JSP_ASSERT_MATCH(LEX_STR); return a; #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_TEMPLATE_LITERAL) { return jspeTemplateLiteral(); #endif } else if (lex->tk==LEX_REGEX) { JsVar *a = 0; #ifdef SAVE_ON_FLASH jsExceptionHere(JSET_SYNTAXERROR, "RegEx are not supported in this version of Espruino\n"); #else JsVar *regex = jslGetTokenValueAsVar(lex); size_t regexEnd = 0, regexLen = 0; JsvStringIterator it; jsvStringIteratorNew(&it, regex, 0); while (jsvStringIteratorHasChar(&it)) { regexLen++; if (jsvStringIteratorGetChar(&it)=='/') regexEnd = regexLen; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); JsVar *flags = 0; if (regexEnd < regexLen) flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH); JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2); a = jswrap_regexp_constructor(regexSource, flags); jsvUnLock3(regex, flags, regexSource); #endif JSP_ASSERT_MATCH(LEX_REGEX); return a; } else if (lex->tk=='{') { if (!jspCheckStackPosition()) return 0; return jspeFactorObject(); } else if (lex->tk=='[') { if (!jspCheckStackPosition()) return 0; return jspeFactorArray(); } else if (lex->tk==LEX_R_FUNCTION) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_FUNCTION); return jspeFunctionDefinition(true); #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_R_CLASS) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_CLASS); return jspeClassDefinition(true); } else if (lex->tk==LEX_R_SUPER) { JSP_ASSERT_MATCH(LEX_R_SUPER); /* This is kind of nasty, since super appears to do three different things. * In the constructor it references the extended class's constructor * in a method it references the constructor's prototype. * in a static method it references the extended class's constructor (but this is different) */ if (jsvIsObject(execInfo.thisVar)) { // 'this' is an object - must be calling a normal method JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__ jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } if (lex->tk=='(') return proto2; // eg. used in a constructor // But if we're doing something else - eg '.' or '[' then it needs to reference the prototype JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0; jsvUnLock(proto2); return proto3; } else if (jsvIsFunction(execInfo.thisVar)) { // 'this' is a function - must be calling a static method JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0); JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } return proto2; } jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; #endif } else if (lex->tk==LEX_R_THIS) { JSP_ASSERT_MATCH(LEX_R_THIS); return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root ); } else if (lex->tk==LEX_R_DELETE) { if (!jspCheckStackPosition()) return 0; return jspeFactorDelete(); } else if (lex->tk==LEX_R_TYPEOF) { if (!jspCheckStackPosition()) return 0; return jspeFactorTypeOf(); } else if (lex->tk==LEX_R_VOID) { JSP_ASSERT_MATCH(LEX_R_VOID); jsvUnLock(jspeUnaryExpression()); return 0; } JSP_MATCH(LEX_EOF); jsExceptionHere(JSET_SYNTAXERROR, "Unexpected end of Input\n"); return 0; }
nan
null
10,771
59713758321053350398183664620391621188
158
Fix stack overflow if void void void... is repeated many times (fix #1434)
null
poppler
39d140bfc0b8239bdd96d6a55842034ae5c05473
1
void FoFiType1::parse() { char *line, *line1, *p, *p2; char buf[256]; char c; int n, code, i, j; char *tokptr; for (i = 1, line = (char *)file; i <= 100 && line && (!name || !encoding); ++i) { // get font name if (!name && !strncmp(line, "/FontName", 9)) { strncpy(buf, line, 255); buf[255] = '\0'; if ((p = strchr(buf+9, '/')) && (p = strtok_r(p+1, " \t\n\r", &tokptr))) { name = copyString(p); } line = getNextLine(line); // get encoding } else if (!encoding && !strncmp(line, "/Encoding StandardEncoding def", 30)) { encoding = fofiType1StandardEncoding; } else if (!encoding && !strncmp(line, "/Encoding 256 array", 19)) { encoding = (char **)gmallocn(256, sizeof(char *)); for (j = 0; j < 256; ++j) { encoding[j] = NULL; } for (j = 0, line = getNextLine(line); j < 300 && line && (line1 = getNextLine(line)); ++j, line = line1) { if ((n = line1 - line) > 255) { error(-1, "FoFiType1::parse a line has more than 255 characters, we don't support this"); n = 255; } strncpy(buf, line, n); buf[n] = '\0'; for (p = buf; *p == ' ' || *p == '\t'; ++p) ; if (!strncmp(p, "dup", 3)) { for (p += 3; *p == ' ' || *p == '\t'; ++p) ; for (p2 = p; *p2 >= '0' && *p2 <= '9'; ++p2) ; if (*p2) { c = *p2; // store it so we can recover it after atoi *p2 = '\0'; // terminate p so atoi works code = atoi(p); *p2 = c; if (code == 8 && *p2 == '#') { code = 0; for (++p2; *p2 >= '0' && *p2 <= '7'; ++p2) { code = code * 8 + (*p2 - '0'); } } if (code < 256) { for (p = p2; *p == ' ' || *p == '\t'; ++p) ; if (*p == '/') { ++p; for (p2 = p; *p2 && *p2 != ' ' && *p2 != '\t'; ++p2) ; c = *p2; // store it so we can recover it after copyString *p2 = '\0'; // terminate p so copyString works encoding[code] = copyString(p); *p2 = c; p = p2; for (; *p == ' ' || *p == '\t'; ++p); // eat spaces between string and put if (!strncmp(p, "put", 3)) { // eat put and spaces and newlines after put for (p += 3; *p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'; ++p); if (*p) { // there is still something after the definition // there might be another definition in this line // so move line1 to the end of our parsing // so we start in the potential next definition in the next loop line1 = &line[p - buf]; } } else { error(-1, "FoFiType1::parse no put after dup"); } } } } } else { if (strtok_r(buf, " \t", &tokptr) && (p = strtok_r(NULL, " \t\n\r", &tokptr)) && !strcmp(p, "def")) { break; } } } //~ check for getinterval/putinterval junk } else { line = getNextLine(line); } } parsed = gTrue; }
nan
null
10,772
212676828599960984901048065221040785644
99
Fix crash in broken pdf (code < 0) Found thanks to PDF provided by Joel Voss of Leviathan Security Group
null
qemu
bf25983345ca44aec3dd92c57142be45452bd38a
1
static bool blit_is_unsafe(struct CirrusVGAState *s) { /* should be the case, see cirrus_bitblt_start */ assert(s->cirrus_blt_width > 0); assert(s->cirrus_blt_height > 0); if (blit_region_is_unsafe(s, s->cirrus_blt_dstpitch, s->cirrus_blt_dstaddr & s->cirrus_addr_mask)) { return true; } if (blit_region_is_unsafe(s, s->cirrus_blt_srcpitch, s->cirrus_blt_srcaddr & s->cirrus_addr_mask)) { return true; } return false; }
nan
null
10,773
24989570285750456737373988370073209685
17
cirrus: don't overflow CirrusVGAState->cirrus_bltbuf This is CVE-2014-8106. Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>
null
poppler
957aa252912cde85d76c41e9710b33425a82b696
1
void Splash::scaleMaskYdXu(SplashImageMaskSource src, void *srcData, int srcWidth, int srcHeight, int scaledWidth, int scaledHeight, SplashBitmap *dest) { Guchar *lineBuf; Guint *pixBuf; Guint pix; Guchar *destPtr; int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, d; int i, j; // Bresenham parameters for y scale yp = srcHeight / scaledHeight; yq = srcHeight % scaledHeight; // Bresenham parameters for x scale xp = scaledWidth / srcWidth; xq = scaledWidth % srcWidth; // allocate buffers lineBuf = (Guchar *)gmalloc(srcWidth); pixBuf = (Guint *)gmallocn(srcWidth, sizeof(int)); // init y scale Bresenham yt = 0; destPtr = dest->data; for (y = 0; y < scaledHeight; ++y) { // y scale Bresenham if ((yt += yq) >= scaledHeight) { yt -= scaledHeight; yStep = yp + 1; } else { yStep = yp; } // read rows from image memset(pixBuf, 0, srcWidth * sizeof(int)); for (i = 0; i < yStep; ++i) { (*src)(srcData, lineBuf); for (j = 0; j < srcWidth; ++j) { pixBuf[j] += lineBuf[j]; } } // init x scale Bresenham xt = 0; d = (255 << 23) / yStep; for (x = 0; x < srcWidth; ++x) { // x scale Bresenham if ((xt += xq) >= srcWidth) { xt -= srcWidth; xStep = xp + 1; } else { xStep = xp; } // compute the final pixel pix = pixBuf[x]; // (255 * pix) / yStep pix = (pix * d) >> 23; // store the pixel for (i = 0; i < xStep; ++i) { *destPtr++ = (Guchar)pix; } } } gfree(pixBuf); gfree(lineBuf); }
nan
null
10,774
313979367089057107868118864231974170875
75
Fix invalid memory accesses in 1091.pdf.asan.72.42
null
file
6f737ddfadb596d7d4a993f7ed2141ffd664a81c
1
private int mget(struct magic_set *ms, const unsigned char *s, struct magic *m, size_t nbytes, size_t o, unsigned int cont_level, int mode, int text, int flip, int recursion_level, int *printed_something, int *need_separator, int *returnval) { uint32_t soffset, offset = ms->offset; uint32_t lhs; int rv, oneed_separator, in_type; char *sbuf, *rbuf; union VALUETYPE *p = &ms->ms_value; struct mlist ml; if (recursion_level >= 20) { file_error(ms, 0, "recursion nesting exceeded"); return -1; } if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o), (uint32_t)nbytes, m) == -1) return -1; if ((ms->flags & MAGIC_DEBUG) != 0) { fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%" SIZE_T_FORMAT "u, " "nbytes=%" SIZE_T_FORMAT "u)\n", m->type, m->flag, offset, o, nbytes); mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } if (m->flag & INDIR) { int off = m->in_offset; if (m->in_op & FILE_OPINDIRECT) { const union VALUETYPE *q = CAST(const union VALUETYPE *, ((const void *)(s + offset + off))); switch (cvt_flip(m->in_type, flip)) { case FILE_BYTE: off = q->b; break; case FILE_SHORT: off = q->h; break; case FILE_BESHORT: off = (short)((q->hs[0]<<8)|(q->hs[1])); break; case FILE_LESHORT: off = (short)((q->hs[1]<<8)|(q->hs[0])); break; case FILE_LONG: off = q->l; break; case FILE_BELONG: case FILE_BEID3: off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)| (q->hl[2]<<8)|(q->hl[3])); break; case FILE_LEID3: case FILE_LELONG: off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)| (q->hl[1]<<8)|(q->hl[0])); break; case FILE_MELONG: off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)| (q->hl[3]<<8)|(q->hl[2])); break; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect offs=%u\n", off); } switch (in_type = cvt_flip(m->in_type, flip)) { case FILE_BYTE: if (OFFSET_OOB(nbytes, offset, 1)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->b & off; break; case FILE_OPOR: offset = p->b | off; break; case FILE_OPXOR: offset = p->b ^ off; break; case FILE_OPADD: offset = p->b + off; break; case FILE_OPMINUS: offset = p->b - off; break; case FILE_OPMULTIPLY: offset = p->b * off; break; case FILE_OPDIVIDE: offset = p->b / off; break; case FILE_OPMODULO: offset = p->b % off; break; } } else offset = p->b; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; lhs = (p->hs[0] << 8) | p->hs[1]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; lhs = (p->hs[1] << 8) | p->hs[0]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_SHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->h & off; break; case FILE_OPOR: offset = p->h | off; break; case FILE_OPXOR: offset = p->h ^ off; break; case FILE_OPADD: offset = p->h + off; break; case FILE_OPMINUS: offset = p->h - off; break; case FILE_OPMULTIPLY: offset = p->h * off; break; case FILE_OPDIVIDE: offset = p->h / off; break; case FILE_OPMODULO: offset = p->h % off; break; } } else offset = p->h; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BELONG: case FILE_BEID3: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[0] << 24) | (p->hl[1] << 16) | (p->hl[2] << 8) | p->hl[3]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LELONG: case FILE_LEID3: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[3] << 24) | (p->hl[2] << 16) | (p->hl[1] << 8) | p->hl[0]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_MELONG: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[1] << 24) | (p->hl[0] << 16) | (p->hl[3] << 8) | p->hl[2]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LONG: if (OFFSET_OOB(nbytes, offset, 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->l & off; break; case FILE_OPOR: offset = p->l | off; break; case FILE_OPXOR: offset = p->l ^ off; break; case FILE_OPADD: offset = p->l + off; break; case FILE_OPMINUS: offset = p->l - off; break; case FILE_OPMULTIPLY: offset = p->l * off; break; case FILE_OPDIVIDE: offset = p->l / off; break; case FILE_OPMODULO: offset = p->l % off; break; } } else offset = p->l; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; default: break; } switch (in_type) { case FILE_LEID3: case FILE_BEID3: offset = ((((offset >> 0) & 0x7f) << 0) | (((offset >> 8) & 0x7f) << 7) | (((offset >> 16) & 0x7f) << 14) | (((offset >> 24) & 0x7f) << 21)) + 10; break; default: break; } if (m->flag & INDIROFFADD) { offset += ms->c.li[cont_level-1].off; if (offset == 0) { if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect *zero* offset\n"); return 0; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect +offs=%u\n", offset); } if (mcopy(ms, p, m->type, 0, s, offset, nbytes, m) == -1) return -1; ms->offset = offset; if ((ms->flags & MAGIC_DEBUG) != 0) { mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } } /* Verify we have enough data to match magic type */ switch (m->type) { case FILE_BYTE: if (OFFSET_OOB(nbytes, offset, 1)) return 0; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: if (OFFSET_OOB(nbytes, offset, 4)) return 0; break; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: if (OFFSET_OOB(nbytes, offset, 8)) return 0; break; case FILE_STRING: case FILE_PSTRING: case FILE_SEARCH: if (OFFSET_OOB(nbytes, offset, m->vallen)) return 0; break; case FILE_REGEX: if (nbytes < offset) return 0; break; case FILE_INDIRECT: if (offset == 0) return 0; if (nbytes < offset) return 0; sbuf = ms->o.buf; soffset = ms->offset; ms->o.buf = NULL; ms->offset = 0; rv = file_softmagic(ms, s + offset, nbytes - offset, recursion_level, BINTEST, text); if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv); rbuf = ms->o.buf; ms->o.buf = sbuf; ms->offset = soffset; if (rv == 1) { if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 && file_printf(ms, F(ms, m, "%u"), offset) == -1) { free(rbuf); return -1; } if (file_printf(ms, "%s", rbuf) == -1) { free(rbuf); return -1; } } free(rbuf); return rv; case FILE_USE: if (nbytes < offset) return 0; sbuf = m->value.s; if (*sbuf == '^') { sbuf++; flip = !flip; } if (file_magicfind(ms, sbuf, &ml) == -1) { file_error(ms, 0, "cannot find entry `%s'", sbuf); return -1; } oneed_separator = *need_separator; if (m->flag & NOSPACE) *need_separator = 0; rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o, mode, text, flip, recursion_level, printed_something, need_separator, returnval); if (rv != 1) *need_separator = oneed_separator; return rv; case FILE_NAME: if (file_printf(ms, "%s", m->desc) == -1) return -1; return 1; case FILE_DEFAULT: /* nothing to check */ case FILE_CLEAR: default: break; } if (!mconvert(ms, m, flip)) return 0;
nan
null
10,775
260682246970550741517960570774119868833
520
- reduce recursion level from 20 to 10 and make a symbolic constant for it. - pull out the guts of saving and restoring the output buffer into functions and take care not to overwrite the error message if an error happened.
null
samba
d724f835acb9f4886c0001af32cd325dbbf1f895
1
static NTSTATUS do_connect(TALLOC_CTX *ctx, const char *server, const char *share, const struct user_auth_info *auth_info, bool show_sessetup, bool force_encrypt, int max_protocol, int port, int name_type, struct cli_state **pcli) { struct cli_state *c = NULL; char *servicename; char *sharename; char *newserver, *newshare; const char *username; const char *password; const char *domain; NTSTATUS status; int flags = 0; /* make a copy so we don't modify the global string 'service' */ servicename = talloc_strdup(ctx,share); if (!servicename) { return NT_STATUS_NO_MEMORY; } sharename = servicename; if (*sharename == '\\') { sharename += 2; if (server == NULL) { server = sharename; } sharename = strchr_m(sharename,'\\'); if (!sharename) { return NT_STATUS_NO_MEMORY; } *sharename = 0; sharename++; } if (server == NULL) { return NT_STATUS_INVALID_PARAMETER; } if (get_cmdline_auth_info_use_kerberos(auth_info)) { flags |= CLI_FULL_CONNECTION_USE_KERBEROS; } if (get_cmdline_auth_info_fallback_after_kerberos(auth_info)) { flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS; } if (get_cmdline_auth_info_use_ccache(auth_info)) { flags |= CLI_FULL_CONNECTION_USE_CCACHE; } if (get_cmdline_auth_info_use_pw_nt_hash(auth_info)) { flags |= CLI_FULL_CONNECTION_USE_NT_HASH; } status = cli_connect_nb( server, NULL, port, name_type, NULL, get_cmdline_auth_info_signing_state(auth_info), flags, &c); if (!NT_STATUS_IS_OK(status)) { d_printf("Connection to %s failed (Error %s)\n", server, nt_errstr(status)); return status; } if (max_protocol == 0) { max_protocol = PROTOCOL_NT1; } DEBUG(4,(" session request ok\n")); status = smbXcli_negprot(c->conn, c->timeout, lp_client_min_protocol(), max_protocol); if (!NT_STATUS_IS_OK(status)) { d_printf("protocol negotiation failed: %s\n", nt_errstr(status)); cli_shutdown(c); return status; } if (smbXcli_conn_protocol(c->conn) >= PROTOCOL_SMB2_02) { /* Ensure we ask for some initial credits. */ smb2cli_conn_set_max_credits(c->conn, DEFAULT_SMB2_MAX_CREDITS); } username = get_cmdline_auth_info_username(auth_info); password = get_cmdline_auth_info_password(auth_info); domain = get_cmdline_auth_info_domain(auth_info); if ((domain == NULL) || (domain[0] == '\0')) { domain = lp_workgroup(); } status = cli_session_setup(c, username, password, strlen(password), password, strlen(password), domain); if (!NT_STATUS_IS_OK(status)) { /* If a password was not supplied then * try again with a null username. */ if (password[0] || !username[0] || get_cmdline_auth_info_use_kerberos(auth_info) || !NT_STATUS_IS_OK(status = cli_session_setup(c, "", "", 0, "", 0, lp_workgroup()))) { d_printf("session setup failed: %s\n", nt_errstr(status)); if (NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) d_printf("did you forget to run kinit?\n"); cli_shutdown(c); return status; } d_printf("Anonymous login successful\n"); } if (!NT_STATUS_IS_OK(status)) { DEBUG(10,("cli_init_creds() failed: %s\n", nt_errstr(status))); cli_shutdown(c); return status; } if ( show_sessetup ) { if (*c->server_domain) { DEBUG(0,("Domain=[%s] OS=[%s] Server=[%s]\n", c->server_domain,c->server_os,c->server_type)); } else if (*c->server_os || *c->server_type) { DEBUG(0,("OS=[%s] Server=[%s]\n", c->server_os,c->server_type)); } } DEBUG(4,(" session setup ok\n")); /* here's the fun part....to support 'msdfs proxy' shares (on Samba or windows) we have to issues a TRANS_GET_DFS_REFERRAL here before trying to connect to the original share. cli_check_msdfs_proxy() will fail if it is a normal share. */ if (smbXcli_conn_dfs_supported(c->conn) && cli_check_msdfs_proxy(ctx, c, sharename, &newserver, &newshare, force_encrypt, username, password, domain)) { cli_shutdown(c); return do_connect(ctx, newserver, newshare, auth_info, false, force_encrypt, max_protocol, port, name_type, pcli); } /* must be a normal share */ status = cli_tree_connect(c, sharename, "?????", password, strlen(password)+1); if (!NT_STATUS_IS_OK(status)) { d_printf("tree connect failed: %s\n", nt_errstr(status)); cli_shutdown(c); return status; } if (force_encrypt) { status = cli_cm_force_encryption(c, username, password, domain, sharename); if (!NT_STATUS_IS_OK(status)) { cli_shutdown(c); return status; } } DEBUG(4,(" tconx ok\n")); *pcli = c; return NT_STATUS_OK; }
nan
null
10,776
102913365890764226141788031959623436726
182
CVE-2015-5296: s3:libsmb: force signing when requiring encryption in do_connect() BUG: https://bugzilla.samba.org/show_bug.cgi?id=11536 Signed-off-by: Stefan Metzmacher <metze@samba.org> Reviewed-by: Jeremy Allison <jra@samba.org>
null
linux
8605330aac5a5785630aec8f64378a54891937cc
1
void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb->len && (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS)) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } }
nan
null
10,777
161777901395312220267840794754847803436
45
tcp: fix SCM_TIMESTAMPING_OPT_STATS for normal skbs __sock_recv_timestamp can be called for both normal skbs (for receive timestamps) and for skbs on the error queue (for transmit timestamps). Commit 1c885808e456 (tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING) assumes any skb passed to __sock_recv_timestamp are from the error queue, containing OPT_STATS in the content of the skb. This results in accessing invalid memory or generating junk data. To fix this, set skb->pkt_type to PACKET_OUTGOING for packets on the error queue. This is safe because on the receive path on local sockets skb->pkt_type is never set to PACKET_OUTGOING. With that, copy OPT_STATS from a packet, only if its pkt_type is PACKET_OUTGOING. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <zzoru007@gmail.com> Signed-off-by: Soheil Hassas Yeganeh <soheil@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Signed-off-by: Willem de Bruijn <willemb@google.com> Signed-off-by: David S. Miller <davem@davemloft.net>
null
linux
8605330aac5a5785630aec8f64378a54891937cc
1
*/ int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb) { if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >= (unsigned int)sk->sk_rcvbuf) return -ENOMEM; skb_orphan(skb); skb->sk = sk; skb->destructor = sock_rmem_free; atomic_add(skb->truesize, &sk->sk_rmem_alloc); /* before exiting rcu section, make sure dst is refcounted */ skb_dst_force(skb); skb_queue_tail(&sk->sk_error_queue, skb); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk); return 0;
nan
null
10,778
339241323239055793821424120269013734427
19
tcp: fix SCM_TIMESTAMPING_OPT_STATS for normal skbs __sock_recv_timestamp can be called for both normal skbs (for receive timestamps) and for skbs on the error queue (for transmit timestamps). Commit 1c885808e456 (tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING) assumes any skb passed to __sock_recv_timestamp are from the error queue, containing OPT_STATS in the content of the skb. This results in accessing invalid memory or generating junk data. To fix this, set skb->pkt_type to PACKET_OUTGOING for packets on the error queue. This is safe because on the receive path on local sockets skb->pkt_type is never set to PACKET_OUTGOING. With that, copy OPT_STATS from a packet, only if its pkt_type is PACKET_OUTGOING. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <zzoru007@gmail.com> Signed-off-by: Soheil Hassas Yeganeh <soheil@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Signed-off-by: Willem de Bruijn <willemb@google.com> Signed-off-by: David S. Miller <davem@davemloft.net>
null
radare2
9d348bcc2c4bbd3805e7eec97b594be9febbdf9a
1
INST_HANDLER (cpse) { // CPSE Rd, Rr int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); RAnalOp next_op; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to true, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp }
nan
null
10,780
109446500842023419648052110586536397036
23
Fix #9943 - Invalid free on RAnal.avr
null
exim
5b7a7c051c9ab9ee7c924a611f90ef2be03e0ad0
1
int dmarc_process() { int sr, origin; /* used in SPF section */ int dmarc_spf_result = 0; /* stores spf into dmarc conn ctx */ pdkim_signature *sig = NULL; BOOL has_dmarc_record = TRUE; u_char **ruf; /* forensic report addressees, if called for */ /* ACLs have "control=dmarc_disable_verify" */ if (dmarc_disable_verify == TRUE) { dmarc_ar_header = dmarc_auth_results_header(from_header, NULL); return OK; } /* Store the header From: sender domain for this part of DMARC. * If there is no from_header struct, then it's likely this message * is locally generated and relying on fixups to add it. Just skip * the entire DMARC system if we can't find a From: header....or if * there was a previous error. */ if (from_header == NULL || dmarc_abort == TRUE) dmarc_abort = TRUE; else { /* I strongly encourage anybody who can make this better to contact me directly! * <cannonball> Is this an insane way to extract the email address from the From: header? * <jgh_hm> it's sure a horrid layer-crossing.... * <cannonball> I'm not denying that :-/ * <jgh_hm> there may well be no better though */ header_from_sender = expand_string( string_sprintf("${domain:${extract{1}{:}{${addresses:%s}}}}", from_header->text) ); /* The opendmarc library extracts the domain from the email address, but * only try to store it if it's not empty. Otherwise, skip out of DMARC. */ if (strcmp( CCS header_from_sender, "") == 0) dmarc_abort = TRUE; libdm_status = (dmarc_abort == TRUE) ? DMARC_PARSE_OKAY : opendmarc_policy_store_from_domain(dmarc_pctx, header_from_sender); if (libdm_status != DMARC_PARSE_OKAY) { log_write(0, LOG_MAIN|LOG_PANIC, "failure to store header From: in DMARC: %s, header was '%s'", opendmarc_policy_status_to_str(libdm_status), from_header->text); dmarc_abort = TRUE; } } /* Skip DMARC if connection is SMTP Auth. Temporarily, admin should * instead do this in the ACLs. */ if (dmarc_abort == FALSE && sender_host_authenticated == NULL) { /* Use the envelope sender domain for this part of DMARC */ spf_sender_domain = expand_string(US"$sender_address_domain"); if ( spf_response == NULL ) { /* No spf data means null envelope sender so generate a domain name * from the sender_helo_name */ if (spf_sender_domain == NULL) { spf_sender_domain = sender_helo_name; log_write(0, LOG_MAIN, "DMARC using synthesized SPF sender domain = %s\n", spf_sender_domain); DEBUG(D_receive) debug_printf("DMARC using synthesized SPF sender domain = %s\n", spf_sender_domain); } dmarc_spf_result = DMARC_POLICY_SPF_OUTCOME_NONE; dmarc_spf_ares_result = ARES_RESULT_UNKNOWN; origin = DMARC_POLICY_SPF_ORIGIN_HELO; spf_human_readable = US""; } else { sr = spf_response->result; dmarc_spf_result = (sr == SPF_RESULT_NEUTRAL) ? DMARC_POLICY_SPF_OUTCOME_NONE : (sr == SPF_RESULT_PASS) ? DMARC_POLICY_SPF_OUTCOME_PASS : (sr == SPF_RESULT_FAIL) ? DMARC_POLICY_SPF_OUTCOME_FAIL : (sr == SPF_RESULT_SOFTFAIL) ? DMARC_POLICY_SPF_OUTCOME_TMPFAIL : DMARC_POLICY_SPF_OUTCOME_NONE; dmarc_spf_ares_result = (sr == SPF_RESULT_NEUTRAL) ? ARES_RESULT_NEUTRAL : (sr == SPF_RESULT_PASS) ? ARES_RESULT_PASS : (sr == SPF_RESULT_FAIL) ? ARES_RESULT_FAIL : (sr == SPF_RESULT_SOFTFAIL) ? ARES_RESULT_SOFTFAIL : (sr == SPF_RESULT_NONE) ? ARES_RESULT_NONE : (sr == SPF_RESULT_TEMPERROR) ? ARES_RESULT_TEMPERROR : (sr == SPF_RESULT_PERMERROR) ? ARES_RESULT_PERMERROR : ARES_RESULT_UNKNOWN; origin = DMARC_POLICY_SPF_ORIGIN_MAILFROM; spf_human_readable = (uschar *)spf_response->header_comment; DEBUG(D_receive) debug_printf("DMARC using SPF sender domain = %s\n", spf_sender_domain); } if (strcmp( CCS spf_sender_domain, "") == 0) dmarc_abort = TRUE; if (dmarc_abort == FALSE) { libdm_status = opendmarc_policy_store_spf(dmarc_pctx, spf_sender_domain, dmarc_spf_result, origin, spf_human_readable); if (libdm_status != DMARC_PARSE_OKAY) log_write(0, LOG_MAIN|LOG_PANIC, "failure to store spf for DMARC: %s", opendmarc_policy_status_to_str(libdm_status)); } /* Now we cycle through the dkim signature results and put into * the opendmarc context, further building the DMARC reply. */ sig = dkim_signatures; dkim_history_buffer = US""; while (sig != NULL) { int dkim_result, dkim_ares_result, vs, ves; vs = sig->verify_status; ves = sig->verify_ext_status; dkim_result = ( vs == PDKIM_VERIFY_PASS ) ? DMARC_POLICY_DKIM_OUTCOME_PASS : ( vs == PDKIM_VERIFY_FAIL ) ? DMARC_POLICY_DKIM_OUTCOME_FAIL : ( vs == PDKIM_VERIFY_INVALID ) ? DMARC_POLICY_DKIM_OUTCOME_TMPFAIL : DMARC_POLICY_DKIM_OUTCOME_NONE; libdm_status = opendmarc_policy_store_dkim(dmarc_pctx, (uschar *)sig->domain, dkim_result, US""); DEBUG(D_receive) debug_printf("DMARC adding DKIM sender domain = %s\n", sig->domain); if (libdm_status != DMARC_PARSE_OKAY) log_write(0, LOG_MAIN|LOG_PANIC, "failure to store dkim (%s) for DMARC: %s", sig->domain, opendmarc_policy_status_to_str(libdm_status)); dkim_ares_result = ( vs == PDKIM_VERIFY_PASS ) ? ARES_RESULT_PASS : ( vs == PDKIM_VERIFY_FAIL ) ? ARES_RESULT_FAIL : ( vs == PDKIM_VERIFY_NONE ) ? ARES_RESULT_NONE : ( vs == PDKIM_VERIFY_INVALID ) ? ( ves == PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE ? ARES_RESULT_PERMERROR : ves == PDKIM_VERIFY_INVALID_BUFFER_SIZE ? ARES_RESULT_PERMERROR : ves == PDKIM_VERIFY_INVALID_PUBKEY_PARSING ? ARES_RESULT_PERMERROR : ARES_RESULT_UNKNOWN ) : ARES_RESULT_UNKNOWN; dkim_history_buffer = string_sprintf("%sdkim %s %d\n", dkim_history_buffer, sig->domain, dkim_ares_result); sig = sig->next; } libdm_status = opendmarc_policy_query_dmarc(dmarc_pctx, US""); switch (libdm_status) { case DMARC_DNS_ERROR_NXDOMAIN: case DMARC_DNS_ERROR_NO_RECORD: DEBUG(D_receive) debug_printf("DMARC no record found for %s\n", header_from_sender); has_dmarc_record = FALSE; break; case DMARC_PARSE_OKAY: DEBUG(D_receive) debug_printf("DMARC record found for %s\n", header_from_sender); break; case DMARC_PARSE_ERROR_BAD_VALUE: DEBUG(D_receive) debug_printf("DMARC record parse error for %s\n", header_from_sender); has_dmarc_record = FALSE; break; default: /* everything else, skip dmarc */ DEBUG(D_receive) debug_printf("DMARC skipping (%d), unsure what to do with %s", libdm_status, from_header->text); has_dmarc_record = FALSE; break; } /* Can't use exim's string manipulation functions so allocate memory * for libopendmarc using its max hostname length definition. */ uschar *dmarc_domain = (uschar *)calloc(DMARC_MAXHOSTNAMELEN, sizeof(uschar)); libdm_status = opendmarc_policy_fetch_utilized_domain(dmarc_pctx, dmarc_domain, DMARC_MAXHOSTNAMELEN-1); dmarc_used_domain = string_copy(dmarc_domain); free(dmarc_domain); if (libdm_status != DMARC_PARSE_OKAY) { log_write(0, LOG_MAIN|LOG_PANIC, "failure to read domainname used for DMARC lookup: %s", opendmarc_policy_status_to_str(libdm_status)); } libdm_status = opendmarc_get_policy_to_enforce(dmarc_pctx); dmarc_policy = libdm_status; switch(libdm_status) { case DMARC_POLICY_ABSENT: /* No DMARC record found */ dmarc_status = US"norecord"; dmarc_pass_fail = US"none"; dmarc_status_text = US"No DMARC record"; action = DMARC_RESULT_ACCEPT; break; case DMARC_FROM_DOMAIN_ABSENT: /* No From: domain */ dmarc_status = US"nofrom"; dmarc_pass_fail = US"temperror"; dmarc_status_text = US"No From: domain found"; action = DMARC_RESULT_ACCEPT; break; case DMARC_POLICY_NONE: /* Accept and report */ dmarc_status = US"none"; dmarc_pass_fail = US"none"; dmarc_status_text = US"None, Accept"; action = DMARC_RESULT_ACCEPT; break; case DMARC_POLICY_PASS: /* Explicit accept */ dmarc_status = US"accept"; dmarc_pass_fail = US"pass"; dmarc_status_text = US"Accept"; action = DMARC_RESULT_ACCEPT; break; case DMARC_POLICY_REJECT: /* Explicit reject */ dmarc_status = US"reject"; dmarc_pass_fail = US"fail"; dmarc_status_text = US"Reject"; action = DMARC_RESULT_REJECT; break; case DMARC_POLICY_QUARANTINE: /* Explicit quarantine */ dmarc_status = US"quarantine"; dmarc_pass_fail = US"fail"; dmarc_status_text = US"Quarantine"; action = DMARC_RESULT_QUARANTINE; break; default: dmarc_status = US"temperror"; dmarc_pass_fail = US"temperror"; dmarc_status_text = US"Internal Policy Error"; action = DMARC_RESULT_TEMPFAIL; break; } libdm_status = opendmarc_policy_fetch_alignment(dmarc_pctx, &da, &sa); if (libdm_status != DMARC_PARSE_OKAY) { log_write(0, LOG_MAIN|LOG_PANIC, "failure to read DMARC alignment: %s", opendmarc_policy_status_to_str(libdm_status)); } if (has_dmarc_record == TRUE) { log_write(0, LOG_MAIN, "DMARC results: spf_domain=%s dmarc_domain=%s " "spf_align=%s dkim_align=%s enforcement='%s'", spf_sender_domain, dmarc_used_domain, (sa==DMARC_POLICY_SPF_ALIGNMENT_PASS) ?"yes":"no", (da==DMARC_POLICY_DKIM_ALIGNMENT_PASS)?"yes":"no", dmarc_status_text); history_file_status = dmarc_write_history_file(); /* Now get the forensic reporting addresses, if any */ ruf = opendmarc_policy_fetch_ruf(dmarc_pctx, NULL, 0, 1); dmarc_send_forensic_report(ruf); } } /* set some global variables here */ dmarc_ar_header = dmarc_auth_results_header(from_header, NULL); /* shut down libopendmarc */ if ( dmarc_pctx != NULL ) (void) opendmarc_policy_connect_shutdown(dmarc_pctx); if ( dmarc_disable_verify == FALSE ) (void) opendmarc_policy_library_shutdown(&dmarc_ctx); return OK; }
nan
null
10,781
164959432179770344629019744676425282482
256
SECURITY: DMARC uses From header untrusted data CVE-2014-2957 To find the sending domain, expand_string() was used to directly parse the contents of the From header. This passes untrusted data directly into an internal function. Convert to use standard internal parsing functions.
null
qemu
e95c9a493a5a8d6f969e86c9f19f80ffe6587e19
1
static void v9fs_read(void *opaque) { int32_t fid; uint64_t off; ssize_t err = 0; int32_t count = 0; size_t offset = 7; uint32_t max_count; V9fsFidState *fidp; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count); if (err < 0) { goto out_nofid; } trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count); fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -EINVAL; goto out_nofid; } if (fidp->fid_type == P9_FID_DIR) { if (off == 0) { v9fs_co_rewinddir(pdu, fidp); } count = v9fs_do_readdir_with_stat(pdu, fidp, max_count); if (count < 0) { err = count; goto out; } err = pdu_marshal(pdu, offset, "d", count); if (err < 0) { goto out; } err += offset + count; } else if (fidp->fid_type == P9_FID_FILE) { QEMUIOVector qiov_full; QEMUIOVector qiov; int32_t len; v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false); qemu_iovec_init(&qiov, qiov_full.niov); do { qemu_iovec_reset(&qiov); qemu_iovec_concat(&qiov, &qiov_full, count, qiov_full.size - count); if (0) { print_sg(qiov.iov, qiov.niov); } /* Loop in case of EINTR */ do { len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off); if (len >= 0) { off += len; count += len; } } while (len == -EINTR && !pdu->cancelled); if (len < 0) { /* IO error return the error */ err = len; goto out; } } while (count < max_count && len > 0); err = pdu_marshal(pdu, offset, "d", count); if (err < 0) { goto out; } err += offset + count; qemu_iovec_destroy(&qiov); qemu_iovec_destroy(&qiov_full); } else if (fidp->fid_type == P9_FID_XATTR) { err = v9fs_xattr_read(s, pdu, fidp, off, max_count); } else { err = -EINVAL; } trace_v9fs_read_return(pdu->tag, pdu->id, count, err); out: put_fid(pdu, fidp); out_nofid: pdu_complete(pdu, err); }
nan
null
10,782
163413897778522467807582670852933289759
83
9pfs: fix potential host memory leak in v9fs_read In 9pfs read dispatch function, it doesn't free two QEMUIOVector object thus causing potential memory leak. This patch avoid this. Signed-off-by: Li Qiang <liqiang6-s@360.cn> Signed-off-by: Greg Kurz <groug@kaod.org>
null
WavPack
f68a9555b548306c5b1ee45199ccdc4a16a6101b
1
int ParseCaffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { uint32_t chan_chunk = 0, channel_layout = 0, bcount; unsigned char *channel_identities = NULL; unsigned char *channel_reorder = NULL; int64_t total_samples = 0, infilesize; CAFFileHeader caf_file_header; CAFChunkHeader caf_chunk_header; CAFAudioFormat caf_audio_format; int i; infilesize = DoGetFileSize (infile); memcpy (&caf_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &caf_file_header) + 4, sizeof (CAFFileHeader) - 4, &bcount) || bcount != sizeof (CAFFileHeader) - 4)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_file_header, sizeof (CAFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_file_header, CAFFileHeaderFormat); if (caf_file_header.mFileVersion != 1) { error_line ("%s: can't handle version %d .CAF files!", infilename, caf_file_header.mFileVersion); return WAVPACK_SOFT_ERROR; } // loop through all elements of the RIFF wav header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &caf_chunk_header, sizeof (CAFChunkHeader), &bcount) || bcount != sizeof (CAFChunkHeader)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_chunk_header, sizeof (CAFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_chunk_header, CAFChunkHeaderFormat); // if it's the format chunk, we want to get some info out of there and // make sure it's a .caf file we can handle if (!strncmp (caf_chunk_header.mChunkType, "desc", 4)) { int supported = TRUE; if (caf_chunk_header.mChunkSize != sizeof (CAFAudioFormat) || !DoReadFile (infile, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize, &bcount) || bcount != caf_chunk_header.mChunkSize) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_audio_format, CAFAudioFormatFormat); if (debug_logging_mode) { char formatstr [5]; memcpy (formatstr, caf_audio_format.mFormatID, 4); formatstr [4] = 0; error_line ("format = %s, flags = %x, sampling rate = %g", formatstr, caf_audio_format.mFormatFlags, caf_audio_format.mSampleRate); error_line ("packet = %d bytes and %d frames", caf_audio_format.mBytesPerPacket, caf_audio_format.mFramesPerPacket); error_line ("channels per frame = %d, bits per channel = %d", caf_audio_format.mChannelsPerFrame, caf_audio_format.mBitsPerChannel); } if (strncmp (caf_audio_format.mFormatID, "lpcm", 4) || (caf_audio_format.mFormatFlags & ~3)) supported = FALSE; else if (caf_audio_format.mSampleRate < 1.0 || caf_audio_format.mSampleRate > 16777215.0 || caf_audio_format.mSampleRate != floor (caf_audio_format.mSampleRate)) supported = FALSE; else if (!caf_audio_format.mChannelsPerFrame || caf_audio_format.mChannelsPerFrame > 256) supported = FALSE; else if (caf_audio_format.mBitsPerChannel < 1 || caf_audio_format.mBitsPerChannel > 32 || ((caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) && caf_audio_format.mBitsPerChannel != 32)) supported = FALSE; else if (caf_audio_format.mFramesPerPacket != 1 || caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame < (caf_audio_format.mBitsPerChannel + 7) / 8 || caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame > 4 || caf_audio_format.mBytesPerPacket % caf_audio_format.mChannelsPerFrame) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .CAF format!", infilename); return WAVPACK_SOFT_ERROR; } config->bytes_per_sample = caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame; config->float_norm_exp = (caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) ? 127 : 0; config->bits_per_sample = caf_audio_format.mBitsPerChannel; config->num_channels = caf_audio_format.mChannelsPerFrame; config->sample_rate = (int) caf_audio_format.mSampleRate; if (!(caf_audio_format.mFormatFlags & CAF_FORMAT_LITTLE_ENDIAN) && config->bytes_per_sample > 1) config->qmode |= QMODE_BIG_ENDIAN; if (config->bytes_per_sample == 1) config->qmode |= QMODE_SIGNED_BYTES; if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: 32-bit %s-endian floating point", (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little"); else error_line ("data format: %d-bit %s-endian integers stored in %d byte(s)", config->bits_per_sample, (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little", config->bytes_per_sample); } } else if (!strncmp (caf_chunk_header.mChunkType, "chan", 4)) { CAFChannelLayout *caf_channel_layout; if (caf_chunk_header.mChunkSize < 0 || caf_chunk_header.mChunkSize > 1024 || caf_chunk_header.mChunkSize < sizeof (CAFChannelLayout)) { error_line ("this .CAF file has an invalid 'chan' chunk!"); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("'chan' chunk is %d bytes", (int) caf_chunk_header.mChunkSize); caf_channel_layout = malloc ((size_t) caf_chunk_header.mChunkSize); if (!DoReadFile (infile, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize, &bcount) || bcount != caf_chunk_header.mChunkSize) { error_line ("%s is not a valid .CAF file!", infilename); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (caf_channel_layout, CAFChannelLayoutFormat); chan_chunk = 1; if (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED)) { error_line ("this CAF file already has channel order information!"); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } switch (caf_channel_layout->mChannelLayoutTag) { case kCAFChannelLayoutTag_UseChannelDescriptions: { CAFChannelDescription *descriptions = (CAFChannelDescription *) (caf_channel_layout + 1); int num_descriptions = caf_channel_layout->mNumberChannelDescriptions; int label, cindex = 0, idents = 0; if (caf_chunk_header.mChunkSize != sizeof (CAFChannelLayout) + sizeof (CAFChannelDescription) * num_descriptions || num_descriptions != config->num_channels) { error_line ("channel descriptions in 'chan' chunk are the wrong size!"); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } if (num_descriptions >= 256) { error_line ("%d channel descriptions is more than we can handle...ignoring!"); break; } // we allocate (and initialize to invalid values) a channel reorder array // (even though we might not end up doing any reordering) and a string for // any non-Microsoft channels we encounter channel_reorder = malloc (num_descriptions); memset (channel_reorder, -1, num_descriptions); channel_identities = malloc (num_descriptions+1); // convert the descriptions array to our native endian so it's easy to access for (i = 0; i < num_descriptions; ++i) { WavpackBigEndianToNative (descriptions + i, CAFChannelDescriptionFormat); if (debug_logging_mode) error_line ("chan %d --> %d", i + 1, descriptions [i].mChannelLabel); } // first, we go though and find any MS channels present, and move those to the beginning for (label = 1; label <= 18; ++label) for (i = 0; i < num_descriptions; ++i) if (descriptions [i].mChannelLabel == label) { config->channel_mask |= 1 << (label - 1); channel_reorder [i] = cindex++; break; } // next, we go though the channels again assigning any we haven't done for (i = 0; i < num_descriptions; ++i) if (channel_reorder [i] == (unsigned char) -1) { uint32_t clabel = descriptions [i].mChannelLabel; if (clabel == 0 || clabel == 0xffffffff || clabel == 100) channel_identities [idents++] = 0xff; else if ((clabel >= 33 && clabel <= 44) || (clabel >= 200 && clabel <= 207) || (clabel >= 301 && clabel <= 305)) channel_identities [idents++] = clabel >= 301 ? clabel - 80 : clabel; else { error_line ("warning: unknown channel descriptions label: %d", clabel); channel_identities [idents++] = 0xff; } channel_reorder [i] = cindex++; } // then, go through the reordering array and see if we really have to reorder for (i = 0; i < num_descriptions; ++i) if (channel_reorder [i] != i) break; if (i == num_descriptions) { free (channel_reorder); // no reordering required, so don't channel_reorder = NULL; } else { config->qmode |= QMODE_REORDERED_CHANS; // reordering required, put channel count into layout channel_layout = num_descriptions; } if (!idents) { // if no non-MS channels, free the identities string free (channel_identities); channel_identities = NULL; } else channel_identities [idents] = 0; // otherwise NULL terminate it if (debug_logging_mode) { error_line ("layout_tag = 0x%08x, so generated bitmap of 0x%08x from %d descriptions, %d non-MS", caf_channel_layout->mChannelLayoutTag, config->channel_mask, caf_channel_layout->mNumberChannelDescriptions, idents); // if debugging, display the reordering as a string (but only little ones) if (channel_reorder && num_descriptions <= 8) { char reorder_string [] = "12345678"; for (i = 0; i < num_descriptions; ++i) reorder_string [i] = channel_reorder [i] + '1'; reorder_string [i] = 0; error_line ("reordering string = \"%s\"\n", reorder_string); } } } break; case kCAFChannelLayoutTag_UseChannelBitmap: config->channel_mask = caf_channel_layout->mChannelBitmap; if (debug_logging_mode) error_line ("layout_tag = 0x%08x, so using supplied bitmap of 0x%08x", caf_channel_layout->mChannelLayoutTag, caf_channel_layout->mChannelBitmap); break; default: for (i = 0; i < NUM_LAYOUTS; ++i) if (caf_channel_layout->mChannelLayoutTag == layouts [i].mChannelLayoutTag) { config->channel_mask = layouts [i].mChannelBitmap; channel_layout = layouts [i].mChannelLayoutTag; if (layouts [i].mChannelReorder) { channel_reorder = (unsigned char *) strdup (layouts [i].mChannelReorder); config->qmode |= QMODE_REORDERED_CHANS; } if (layouts [i].mChannelIdentities) channel_identities = (unsigned char *) strdup (layouts [i].mChannelIdentities); if (debug_logging_mode) error_line ("layout_tag 0x%08x found in table, bitmap = 0x%08x, reorder = %s, identities = %s", channel_layout, config->channel_mask, channel_reorder ? "yes" : "no", channel_identities ? "yes" : "no"); break; } if (i == NUM_LAYOUTS && debug_logging_mode) error_line ("layout_tag 0x%08x not found in table...all channels unassigned", caf_channel_layout->mChannelLayoutTag); break; } free (caf_channel_layout); } else if (!strncmp (caf_chunk_header.mChunkType, "data", 4)) { // on the data chunk, get size and exit loop uint32_t mEditCount; if (!DoReadFile (infile, &mEditCount, sizeof (mEditCount), &bcount) || bcount != sizeof (mEditCount)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &mEditCount, sizeof (mEditCount))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || caf_chunk_header.mChunkSize == -1) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / caf_audio_format.mBytesPerPacket; else total_samples = -1; } else { if (infilesize && infilesize - caf_chunk_header.mChunkSize > 16777216) { error_line (".CAF file %s has over 16 MB of extra CAFF data, probably is corrupt!", infilename); return WAVPACK_SOFT_ERROR; } if ((caf_chunk_header.mChunkSize - 4) % caf_audio_format.mBytesPerPacket) { error_line (".CAF file %s has an invalid data chunk size, probably is corrupt!", infilename); return WAVPACK_SOFT_ERROR; } total_samples = (caf_chunk_header.mChunkSize - 4) / caf_audio_format.mBytesPerPacket; if (!total_samples) { error_line ("this .CAF file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } break; } else { // just copy unknown chunks to output file uint32_t bytes_to_copy = (uint32_t) caf_chunk_header.mChunkSize; char *buff; if (caf_chunk_header.mChunkSize < 0 || caf_chunk_header.mChunkSize > 1048576) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", caf_chunk_header.mChunkType [0], caf_chunk_header.mChunkType [1], caf_chunk_header.mChunkType [2], caf_chunk_header.mChunkType [3], caf_chunk_header.mChunkSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!chan_chunk && !config->channel_mask && config->num_channels <= 2 && !(config->qmode & QMODE_CHANS_UNASSIGNED)) config->channel_mask = 0x5 - config->num_channels; if (!WavpackSetConfiguration64 (wpc, config, total_samples, channel_identities)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } if (channel_identities) free (channel_identities); if (channel_layout || channel_reorder) { if (!WavpackSetChannelLayout (wpc, channel_layout, channel_reorder)) { error_line ("problem with setting channel layout (should not happen)"); return WAVPACK_SOFT_ERROR; } if (channel_reorder) free (channel_reorder); } return WAVPACK_NO_ERROR; }
nan
null
10,783
118572273366970058075791126842335923815
406
issue #66: make sure CAF files have a "desc" chunk
null
linux
a0ad220c96692eda76b2e3fd7279f3dcd1d8a8ff
1
static int ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu) { const struct usb_cdc_union_desc *union_desc; struct usb_host_interface *alt; union_desc = ims_pcu_get_cdc_union_desc(intf); if (!union_desc) return -EINVAL; pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev, union_desc->bMasterInterface0); alt = pcu->ctrl_intf->cur_altsetting; pcu->ep_ctrl = &alt->endpoint[0].desc; pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl); pcu->data_intf = usb_ifnum_to_if(pcu->udev, union_desc->bSlaveInterface0); alt = pcu->data_intf->cur_altsetting; if (alt->desc.bNumEndpoints != 2) { dev_err(pcu->dev, "Incorrect number of endpoints on data interface (%d)\n", alt->desc.bNumEndpoints); return -EINVAL; } pcu->ep_out = &alt->endpoint[0].desc; if (!usb_endpoint_is_bulk_out(pcu->ep_out)) { dev_err(pcu->dev, "First endpoint on data interface is not BULK OUT\n"); return -EINVAL; } pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out); if (pcu->max_out_size < 8) { dev_err(pcu->dev, "Max OUT packet size is too small (%zd)\n", pcu->max_out_size); return -EINVAL; } pcu->ep_in = &alt->endpoint[1].desc; if (!usb_endpoint_is_bulk_in(pcu->ep_in)) { dev_err(pcu->dev, "Second endpoint on data interface is not BULK IN\n"); return -EINVAL; } pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in); if (pcu->max_in_size < 8) { dev_err(pcu->dev, "Max IN packet size is too small (%zd)\n", pcu->max_in_size); return -EINVAL; } return 0;
nan
null
10,784
77222324192872992688334854926074228587
59
Input: ims-pcu - sanity check against missing interfaces A malicious device missing interface can make the driver oops. Add sanity checking. Signed-off-by: Oliver Neukum <ONeukum@suse.com> CC: stable@vger.kernel.org Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
null
WavPack
4bc05fc490b66ef2d45b1de26abf1455b486b0dc
1
static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; unsigned char *byteptr = wpmd->data; wpc->version_five = 1; // just having this block signals version 5.0 wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0; if (wpc->channel_reordering) { free (wpc->channel_reordering); wpc->channel_reordering = NULL; } // if there's any data, the first two bytes are file_format and qmode flags if (bytecnt) { wpc->file_format = *byteptr++; wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++; bytecnt -= 2; // another byte indicates a channel layout if (bytecnt) { int nchans, i; wpc->channel_layout = (int32_t) *byteptr++ << 16; bytecnt--; // another byte means we have a channel count for the layout and maybe a reordering if (bytecnt) { wpc->channel_layout += nchans = *byteptr++; bytecnt--; // any more means there's a reordering string if (bytecnt) { if (bytecnt > nchans) return FALSE; wpc->channel_reordering = malloc (nchans); // note that redundant reordering info is not stored, so we fill in the rest if (wpc->channel_reordering) { for (i = 0; i < nchans; ++i) if (bytecnt) { wpc->channel_reordering [i] = *byteptr++; bytecnt--; } else wpc->channel_reordering [i] = i; } } } else wpc->channel_layout += wpc->config.num_channels; } } return TRUE; }
nan
null
10,785
84954385767670317503406679201915695375
63
fixes for 4 fuzz failures posted to SourceForge mailing list
null
WavPack
4bc05fc490b66ef2d45b1de26abf1455b486b0dc
1
int32_t FASTCALL get_word (WavpackStream *wps, int chan, int32_t *correction) { register struct entropy_data *c = wps->w.c + chan; uint32_t ones_count, low, mid, high; int32_t value; int sign; if (!wps->wvbits.ptr) return WORD_EOF; if (correction) *correction = 0; if (!(wps->w.c [0].median [0] & ~1) && !wps->w.holding_zero && !wps->w.holding_one && !(wps->w.c [1].median [0] & ~1)) { uint32_t mask; int cbits; if (wps->w.zeros_acc) { if (--wps->w.zeros_acc) { c->slow_level -= (c->slow_level + SLO) >> SLS; return 0; } } else { for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) wps->w.zeros_acc = cbits; else { for (mask = 1, wps->w.zeros_acc = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) wps->w.zeros_acc |= mask; wps->w.zeros_acc |= mask; } if (wps->w.zeros_acc) { c->slow_level -= (c->slow_level + SLO) >> SLS; CLEAR (wps->w.c [0].median); CLEAR (wps->w.c [1].median); return 0; } } } if (wps->w.holding_zero) ones_count = wps->w.holding_zero = 0; else { #ifdef USE_CTZ_OPTIMIZATION while (wps->wvbits.bc < LIMIT_ONES) { if (++(wps->wvbits.ptr) == wps->wvbits.end) wps->wvbits.wrap (&wps->wvbits); wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc; wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8; } #ifdef _WIN32 _BitScanForward (&ones_count, ~wps->wvbits.sr); #else ones_count = __builtin_ctz (~wps->wvbits.sr); #endif if (ones_count >= LIMIT_ONES) { wps->wvbits.bc -= ones_count; wps->wvbits.sr >>= ones_count; for (; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count); if (ones_count == (LIMIT_ONES + 1)) return WORD_EOF; if (ones_count == LIMIT_ONES) { uint32_t mask; int cbits; for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } } else { wps->wvbits.bc -= ones_count + 1; wps->wvbits.sr >>= ones_count + 1; } #elif defined (USE_NEXT8_OPTIMIZATION) int next8; if (wps->wvbits.bc < 8) { if (++(wps->wvbits.ptr) == wps->wvbits.end) wps->wvbits.wrap (&wps->wvbits); next8 = (wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc) & 0xff; wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8; } else next8 = wps->wvbits.sr & 0xff; if (next8 == 0xff) { wps->wvbits.bc -= 8; wps->wvbits.sr >>= 8; for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count); if (ones_count == (LIMIT_ONES + 1)) return WORD_EOF; if (ones_count == LIMIT_ONES) { uint32_t mask; int cbits; for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } } else { wps->wvbits.bc -= (ones_count = ones_count_table [next8]) + 1; wps->wvbits.sr >>= ones_count + 1; } #else for (ones_count = 0; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count); if (ones_count >= LIMIT_ONES) { uint32_t mask; int cbits; if (ones_count == (LIMIT_ONES + 1)) return WORD_EOF; for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } #endif if (wps->w.holding_one) { wps->w.holding_one = ones_count & 1; ones_count = (ones_count >> 1) + 1; } else { wps->w.holding_one = ones_count & 1; ones_count >>= 1; } wps->w.holding_zero = ~wps->w.holding_one & 1; } if ((wps->wphdr.flags & HYBRID_FLAG) && !chan) update_error_limit (wps); if (ones_count == 0) { low = 0; high = GET_MED (0) - 1; DEC_MED0 (); } else { low = GET_MED (0); INC_MED0 (); if (ones_count == 1) { high = low + GET_MED (1) - 1; DEC_MED1 (); } else { low += GET_MED (1); INC_MED1 (); if (ones_count == 2) { high = low + GET_MED (2) - 1; DEC_MED2 (); } else { low += (ones_count - 2) * GET_MED (2); high = low + GET_MED (2) - 1; INC_MED2 (); } } } low &= 0x7fffffff; high &= 0x7fffffff; mid = (high + low + 1) >> 1; if (!c->error_limit) mid = read_code (&wps->wvbits, high - low) + low; else while (high - low > c->error_limit) { if (getbit (&wps->wvbits)) mid = (high + (low = mid) + 1) >> 1; else mid = ((high = mid - 1) + low + 1) >> 1; } sign = getbit (&wps->wvbits); if (bs_is_open (&wps->wvcbits) && c->error_limit) { value = read_code (&wps->wvcbits, high - low) + low; if (correction) *correction = sign ? (mid - value) : (value - mid); } if (wps->wphdr.flags & HYBRID_BITRATE) { c->slow_level -= (c->slow_level + SLO) >> SLS; c->slow_level += wp_log2 (mid); } return sign ? ~mid : mid; }
nan
null
10,786
189954028957454084831901373981363257031
251
fixes for 4 fuzz failures posted to SourceForge mailing list
null
qemu
b53dd4495ced2432a0b652ea895e651d07336f7e
1
static void usb_xhci_exit(PCIDevice *dev) { int i; XHCIState *xhci = XHCI(dev); trace_usb_xhci_exit(); for (i = 0; i < xhci->numslots; i++) { xhci_disable_slot(xhci, i + 1); } if (xhci->mfwrap_timer) { timer_del(xhci->mfwrap_timer); timer_free(xhci->mfwrap_timer); xhci->mfwrap_timer = NULL; } memory_region_del_subregion(&xhci->mem, &xhci->mem_cap); memory_region_del_subregion(&xhci->mem, &xhci->mem_oper); memory_region_del_subregion(&xhci->mem, &xhci->mem_runtime); memory_region_del_subregion(&xhci->mem, &xhci->mem_doorbell); for (i = 0; i < xhci->numports; i++) { XHCIPort *port = &xhci->ports[i]; memory_region_del_subregion(&xhci->mem, &port->mem); } /* destroy msix memory region */ if (dev->msix_table && dev->msix_pba && dev->msix_entry_used) { memory_region_del_subregion(&xhci->mem, &dev->msix_table_mmio); memory_region_del_subregion(&xhci->mem, &dev->msix_pba_mmio); } usb_bus_release(&xhci->bus); }
nan
null
10,787
261890516668008721057461113560848314758
36
usb:xhci:fix memory leak in usb_xhci_exit If the xhci uses msix, it doesn't free the corresponding memory, thus leading a memory leak. This patch avoid this. Signed-off-by: Li Qiang <liqiang6-s@360.cn> Message-id: 57d7d2e0.d4301c0a.d13e9.9a55@mx.google.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>
null
libpcap
617b12c0339db4891d117b661982126c495439ea
1
daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain pcap_if_t *d; // temp pointer needed to scan the interface chain struct pcap_addr *address; // pcap structure that keeps a network address of an interface struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together uint16 nif = 0; // counts the number of interface listed // Discard the rest of the message; there shouldn't be any payload. if (rpcapd_discard(pars->sockctrl, plen) == -1) { // Network error. return -1; } // Retrieve the device list if (pcap_findalldevs(&alldevs, errmsgbuf) == -1) goto error; if (alldevs == NULL) { if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_NOREMOTEIF, "No interfaces found! Make sure libpcap/WinPcap is properly installed" " and you have the right to access to the remote device.", errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; } // checks the number of interfaces and it computes the total length of the payload for (d = alldevs; d != NULL; d = d->next) { nif++; if (d->description) plen+= strlen(d->description); if (d->name) plen+= strlen(d->name); plen+= sizeof(struct rpcap_findalldevs_if); for (address = d->addresses; address != NULL; address = address->next) { /* * Send only IPv4 and IPv6 addresses over the wire. */ switch (address->addr->sa_family) { case AF_INET: #ifdef AF_INET6 case AF_INET6: #endif plen+= (sizeof(struct rpcap_sockaddr) * 4); break; default: break; } } } // RPCAP findalldevs command if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_FINDALLIF_REPLY, nif, plen); // send the interface list for (d = alldevs; d != NULL; d = d->next) { uint16 lname, ldescr; findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if)); if (d->description) ldescr = (short) strlen(d->description); else ldescr = 0; if (d->name) lname = (short) strlen(d->name); else lname = 0; findalldevs_if->desclen = htons(ldescr); findalldevs_if->namelen = htons(lname); findalldevs_if->flags = htonl(d->flags); for (address = d->addresses; address != NULL; address = address->next) { /* * Send only IPv4 and IPv6 addresses over the wire. */ switch (address->addr->sa_family) { case AF_INET: #ifdef AF_INET6 case AF_INET6: #endif findalldevs_if->naddr++; break; default: break; } } findalldevs_if->naddr = htons(findalldevs_if->naddr); if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; // send all addresses for (address = d->addresses; address != NULL; address = address->next) { struct rpcap_sockaddr *sockaddr; /* * Send only IPv4 and IPv6 addresses over the wire. */ switch (address->addr->sa_family) { case AF_INET: #ifdef AF_INET6 case AF_INET6: #endif sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr); sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr); sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr); sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr); break; default: break; } } } // We no longer need the device list. Free it. pcap_freealldevs(alldevs); // Send a final command that says "now send it!" if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (alldevs) pcap_freealldevs(alldevs); if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_FINDALLIF, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; }
nan
null
10,788
300816215695720586835436367390921534300
198
Calculate the reply payload length in a local variable. Using the same variable for the remaining request length and the reply length is confusing at best and can cause errors at worst (if the request had extra stuff at the end, so that the variable is non-zero). This addresses Include Security issue I8: [libpcap] Remote Packet Capture Daemon Parameter Reuse.
null
qemu
4ffcdef4277a91af15a3c09f7d16af072c29f3f2
1
ssize_t v9fs_list_xattr(FsContext *ctx, const char *path, void *value, size_t vsize) { ssize_t size = 0; void *ovalue = value; XattrOperations *xops; char *orig_value, *orig_value_start; ssize_t xattr_len, parsed_len = 0, attr_len; char *dirpath, *name; int dirfd; /* Get the actual len */ dirpath = g_path_get_dirname(path); dirfd = local_opendir_nofollow(ctx, dirpath); g_free(dirpath); if (dirfd == -1) { return -1; } name = g_path_get_basename(path); xattr_len = flistxattrat_nofollow(dirfd, name, value, 0); if (xattr_len <= 0) { g_free(name); close_preserve_errno(dirfd); return xattr_len; } /* Now fetch the xattr and find the actual size */ orig_value = g_malloc(xattr_len); xattr_len = flistxattrat_nofollow(dirfd, name, orig_value, xattr_len); g_free(name); close_preserve_errno(dirfd); if (xattr_len < 0) { return -1; } /* store the orig pointer */ orig_value_start = orig_value; while (xattr_len > parsed_len) { xops = get_xattr_operations(ctx->xops, orig_value); if (!xops) { goto next_entry; } if (!value) { size += xops->listxattr(ctx, path, orig_value, value, vsize); } else { size = xops->listxattr(ctx, path, orig_value, value, vsize); if (size < 0) { goto err_out; } value += size; vsize -= size; } next_entry: /* Got the next entry */ attr_len = strlen(orig_value) + 1; parsed_len += attr_len; orig_value += attr_len; } if (value) { size = value - ovalue; } err_out: g_free(orig_value_start); return size; }
nan
null
10,789
296947472346732748188814743203567574534
68
9pfs: xattr: fix memory leak in v9fs_list_xattr Free 'orig_value' in error path. Signed-off-by: Li Qiang <liqiang6-s@360.cn> Signed-off-by: Greg Kurz <groug@kaod.org>
null
libav
ce7aee9b733134649a6ce2fa743e51733f33e67e
1
static int dpcm_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; const uint8_t *buf_end = buf + buf_size; DPCMContext *s = avctx->priv_data; int out = 0, ret; int predictor[2]; int ch = 0; int stereo = s->channels - 1; int16_t *output_samples; /* calculate output size */ switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: out = buf_size - 8; break; case CODEC_ID_INTERPLAY_DPCM: out = buf_size - 6 - s->channels; break; case CODEC_ID_XAN_DPCM: out = buf_size - 2 * s->channels; break; case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) out = buf_size * 2; else out = buf_size; break; } if (out <= 0) { av_log(avctx, AV_LOG_ERROR, "packet is too small\n"); return AVERROR(EINVAL); } /* get output buffer */ s->frame.nb_samples = out / s->channels; if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return ret; } output_samples = (int16_t *)s->frame.data[0]; switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: buf += 6; if (stereo) { predictor[1] = (int16_t)(bytestream_get_byte(&buf) << 8); predictor[0] = (int16_t)(bytestream_get_byte(&buf) << 8); } else { predictor[0] = (int16_t)bytestream_get_le16(&buf); } /* decode the samples */ while (buf < buf_end) { predictor[ch] += s->roq_square_array[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_INTERPLAY_DPCM: buf += 6; /* skip over the stream mask and stream length */ for (ch = 0; ch < s->channels; ch++) { predictor[ch] = (int16_t)bytestream_get_le16(&buf); *output_samples++ = predictor[ch]; } ch = 0; while (buf < buf_end) { predictor[ch] += interplay_delta_table[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_XAN_DPCM: { int shift[2] = { 4, 4 }; for (ch = 0; ch < s->channels; ch++) predictor[ch] = (int16_t)bytestream_get_le16(&buf); ch = 0; while (buf < buf_end) { uint8_t n = *buf++; int16_t diff = (n & 0xFC) << 8; if ((n & 0x03) == 3) shift[ch]++; else shift[ch] -= (2 * (n & 3)); /* saturate the shifter to a lower limit of 0 */ if (shift[ch] < 0) shift[ch] = 0; diff >>= shift[ch]; predictor[ch] += diff; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; } case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) { uint8_t *output_samples_u8 = s->frame.data[0]; while (buf < buf_end) { uint8_t n = *buf++; s->sample[0] += s->sol_table[n >> 4]; s->sample[0] = av_clip_uint8(s->sample[0]); *output_samples_u8++ = s->sample[0]; s->sample[stereo] += s->sol_table[n & 0x0F]; s->sample[stereo] = av_clip_uint8(s->sample[stereo]); *output_samples_u8++ = s->sample[stereo]; } } else { while (buf < buf_end) { uint8_t n = *buf++; if (n & 0x80) s->sample[ch] -= sol_table_16[n & 0x7F]; else s->sample[ch] += sol_table_16[n & 0x7F]; s->sample[ch] = av_clip_int16(s->sample[ch]); *output_samples++ = s->sample[ch]; /* toggle channel */ ch ^= stereo; } } break; } *got_frame_ptr = 1; *(AVFrame *)data = s->frame; return buf_size; }
nan
null
10,790
37165043090743031546151319943948577651
149
dpcm: ignore extra unpaired bytes in stereo streams. Fixes: CVE-2011-3951 Found-by: Mateusz "j00ru" Jurczyk and Gynvael Coldwind
null
linux
ea04efee7635c9120d015dcdeeeb6988130cb67a
1
static const struct usb_cdc_union_desc * ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, "Missing descriptor data\n"); return NULL; } if (!buflen) { dev_err(&intf->dev, "Zero length descriptor\n"); return NULL; } while (buflen > 0) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, "Found union header\n"); return union_desc; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, "Missing CDC union descriptor\n"); return NULL;
nan
null
10,791
205163903394648771272792324440701915480
32
Input: ims-psu - check if CDC union descriptor is sane Before trying to use CDC union descriptor, try to validate whether that it is sane by checking that intf->altsetting->extra is big enough and that descriptor bLength is not too big and not too small. Reported-by: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
null
gstreamer
566583e87147f774e7fc4c78b5f7e61d427e40a9
1
gst_vorbis_tag_add_coverart (GstTagList * tags, const gchar * img_data_base64, gint base64_len) { GstBuffer *img; guchar *img_data; gsize img_len; guint save = 0; gint state = 0; if (base64_len < 2) goto not_enough_data; img_data = g_try_malloc0 (base64_len * 3 / 4); if (img_data == NULL) goto alloc_failed; img_len = g_base64_decode_step (img_data_base64, base64_len, img_data, &state, &save); if (img_len == 0) goto decode_failed; img = gst_tag_image_data_to_image_buffer (img_data, img_len, GST_TAG_IMAGE_TYPE_NONE); if (img == NULL) goto convert_failed; gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_PREVIEW_IMAGE, img, NULL); gst_buffer_unref (img); g_free (img_data); return; /* ERRORS */ not_enough_data: { GST_WARNING ("COVERART tag with too little base64-encoded data"); return; } alloc_failed: { GST_WARNING ("Couldn't allocate enough memory to decode COVERART tag"); return; } decode_failed: { GST_WARNING ("Couldn't decode bas64 image data from COVERART tag"); g_free (img_data); return; } convert_failed: { GST_WARNING ("Couldn't extract image or image type from COVERART tag"); g_free (img_data); return; } }
nan
null
10,792
146313219496584415472503042812316046333
60
vorbistag: Protect memory allocation calculation from overflow. Patch by: Tomas Hoger <thoger@redhat.com> Fixes CVE-2009-0586
null
qemu
070c4b92b8cd5390889716677a0b92444d6e087a
1
static void mcf_fec_do_tx(mcf_fec_state *s) { uint32_t addr; mcf_fec_bd bd; int frame_size; int len; uint8_t frame[FEC_MAX_FRAME_SIZE]; uint8_t *ptr; DPRINTF("do_tx\n"); ptr = frame; frame_size = 0; addr = s->tx_descriptor; while (1) { mcf_fec_read_bd(&bd, addr); DPRINTF("tx_bd %x flags %04x len %d data %08x\n", addr, bd.flags, bd.length, bd.data); if ((bd.flags & FEC_BD_R) == 0) { /* Run out of descriptors to transmit. */ break; } len = bd.length; if (frame_size + len > FEC_MAX_FRAME_SIZE) { len = FEC_MAX_FRAME_SIZE - frame_size; s->eir |= FEC_INT_BABT; } cpu_physical_memory_read(bd.data, ptr, len); ptr += len; frame_size += len; if (bd.flags & FEC_BD_L) { /* Last buffer in frame. */ DPRINTF("Sending packet\n"); qemu_send_packet(qemu_get_queue(s->nic), frame, len); ptr = frame; frame_size = 0; s->eir |= FEC_INT_TXF; } s->eir |= FEC_INT_TXB; bd.flags &= ~FEC_BD_R; /* Write back the modified descriptor. */ mcf_fec_write_bd(&bd, addr); /* Advance to the next descriptor. */ if ((bd.flags & FEC_BD_W) != 0) { addr = s->etdsr; } else { addr += 8; } } s->tx_descriptor = addr; }
nan
null
10,793
39214142760099142409338439848078413262
50
net: mcf: limit buffer descriptor count ColdFire Fast Ethernet Controller uses buffer descriptors to manage data flow to/fro receive & transmit queues. While transmitting packets, it could continue to read buffer descriptors if a buffer descriptor has length of zero and has crafted values in bd.flags. Set upper limit to number of buffer descriptors. Reported-by: Li Qiang <liqiang6-s@360.cn> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Reviewed-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Jason Wang <jasowang@redhat.com>
null
xserver
5725849a1b427cd4a72b84e57f211edb35838718
1
ProcRenderAddGlyphs (ClientPtr client) { GlyphSetPtr glyphSet; REQUEST(xRenderAddGlyphsReq); GlyphNewRec glyphsLocal[NLOCALGLYPH]; GlyphNewPtr glyphsBase, glyphs, glyph_new; int remain, nglyphs; CARD32 *gids; xGlyphInfo *gi; CARD8 *bits; unsigned int size; int err; int i, screen; PicturePtr pSrc = NULL, pDst = NULL; PixmapPtr pSrcPix = NULL, pDstPix = NULL; CARD32 component_alpha; REQUEST_AT_LEAST_SIZE(xRenderAddGlyphsReq); err = dixLookupResourceByType((pointer *)&glyphSet, stuff->glyphset, GlyphSetType, client, DixAddAccess); if (err != Success) { client->errorValue = stuff->glyphset; return err; } err = BadAlloc; nglyphs = stuff->nglyphs; if (nglyphs > UINT32_MAX / sizeof(GlyphNewRec)) return BadAlloc; component_alpha = NeedsComponent (glyphSet->format->format); if (nglyphs <= NLOCALGLYPH) { memset (glyphsLocal, 0, sizeof (glyphsLocal)); glyphsBase = glyphsLocal; } else { glyphsBase = (GlyphNewPtr)calloc(nglyphs, sizeof (GlyphNewRec)); if (!glyphsBase) return BadAlloc; } remain = (client->req_len << 2) - sizeof (xRenderAddGlyphsReq); glyphs = glyphsBase; gids = (CARD32 *) (stuff + 1); gi = (xGlyphInfo *) (gids + nglyphs); bits = (CARD8 *) (gi + nglyphs); remain -= (sizeof (CARD32) + sizeof (xGlyphInfo)) * nglyphs; for (i = 0; i < nglyphs; i++) { size_t padded_width; glyph_new = &glyphs[i]; padded_width = PixmapBytePad (gi[i].width, glyphSet->format->depth); if (gi[i].height && padded_width > (UINT32_MAX - sizeof(GlyphRec))/gi[i].height) break; size = gi[i].height * padded_width; if (remain < size) break; err = HashGlyph (&gi[i], bits, size, glyph_new->sha1); if (err) goto bail; glyph_new->glyph = FindGlyphByHash (glyph_new->sha1, glyphSet->fdepth); if (glyph_new->glyph && glyph_new->glyph != DeletedGlyph) { glyph_new->found = TRUE; } else { GlyphPtr glyph; glyph_new->found = FALSE; glyph_new->glyph = glyph = AllocateGlyph (&gi[i], glyphSet->fdepth); if (! glyph) { err = BadAlloc; goto bail; } for (screen = 0; screen < screenInfo.numScreens; screen++) { int width = gi[i].width; int height = gi[i].height; int depth = glyphSet->format->depth; ScreenPtr pScreen; int error; /* Skip work if it's invisibly small anyway */ if (!width || !height) break; pScreen = screenInfo.screens[screen]; pSrcPix = GetScratchPixmapHeader (pScreen, width, height, depth, depth, -1, bits); if (! pSrcPix) { err = BadAlloc; goto bail; } pSrc = CreatePicture (0, &pSrcPix->drawable, glyphSet->format, 0, NULL, serverClient, &error); if (! pSrc) { err = BadAlloc; goto bail; } pDstPix = (pScreen->CreatePixmap) (pScreen, width, height, depth, CREATE_PIXMAP_USAGE_GLYPH_PICTURE); if (!pDstPix) { err = BadAlloc; goto bail; } GlyphPicture (glyph)[screen] = pDst = CreatePicture (0, &pDstPix->drawable, glyphSet->format, CPComponentAlpha, &component_alpha, serverClient, &error); /* The picture takes a reference to the pixmap, so we drop ours. */ (pScreen->DestroyPixmap) (pDstPix); pDstPix = NULL; if (! pDst) { err = BadAlloc; goto bail; } CompositePicture (PictOpSrc, pSrc, None, pDst, 0, 0, 0, 0, 0, 0, width, height); FreePicture ((pointer) pSrc, 0); pSrc = NULL; FreeScratchPixmapHeader (pSrcPix); pSrcPix = NULL; } memcpy (glyph_new->glyph->sha1, glyph_new->sha1, 20); } glyph_new->id = gids[i]; if (size & 3) size += 4 - (size & 3); bits += size; remain -= size; } if (remain || i < nglyphs) { err = BadLength; goto bail; } if (!ResizeGlyphSet (glyphSet, nglyphs)) { err = BadAlloc; goto bail; } for (i = 0; i < nglyphs; i++) AddGlyph (glyphSet, glyphs[i].glyph, glyphs[i].id); if (glyphsBase != glyphsLocal) free(glyphsBase); return Success; bail: if (pSrc) FreePicture ((pointer) pSrc, 0); if (pSrcPix) FreeScratchPixmapHeader (pSrcPix); for (i = 0; i < nglyphs; i++) if (glyphs[i].glyph && ! glyphs[i].found) free(glyphs[i].glyph); if (glyphsBase != glyphsLocal) free(glyphsBase); return err; }
nan
null
10,794
1204159738485994977965093608829950075
202
render: Bounds check for nglyphs in ProcRenderAddGlyphs (#28801) Signed-off-by: Adam Jackson <ajax@redhat.com> Reviewed-by: Julien Cristau <jcristau@debian.org> Signed-off-by: Keith Packard <keithp@keithp.com>
null
FFmpeg
2080bc33717955a0e4268e738acf8c1eeddbf8cb
1
void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]) { int i; int w_align = 1; int h_align = 1; AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt); if (desc) { w_align = 1 << desc->log2_chroma_w; h_align = 1 << desc->log2_chroma_h; } switch (s->pix_fmt) { case AV_PIX_FMT_YUV420P: case AV_PIX_FMT_YUYV422: case AV_PIX_FMT_YVYU422: case AV_PIX_FMT_UYVY422: case AV_PIX_FMT_YUV422P: case AV_PIX_FMT_YUV440P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GBRP: case AV_PIX_FMT_GBRAP: case AV_PIX_FMT_GRAY8: case AV_PIX_FMT_GRAY16BE: case AV_PIX_FMT_GRAY16LE: case AV_PIX_FMT_YUVJ420P: case AV_PIX_FMT_YUVJ422P: case AV_PIX_FMT_YUVJ440P: case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUVA420P: case AV_PIX_FMT_YUVA422P: case AV_PIX_FMT_YUVA444P: case AV_PIX_FMT_YUV420P9LE: case AV_PIX_FMT_YUV420P9BE: case AV_PIX_FMT_YUV420P10LE: case AV_PIX_FMT_YUV420P10BE: case AV_PIX_FMT_YUV420P12LE: case AV_PIX_FMT_YUV420P12BE: case AV_PIX_FMT_YUV420P14LE: case AV_PIX_FMT_YUV420P14BE: case AV_PIX_FMT_YUV420P16LE: case AV_PIX_FMT_YUV420P16BE: case AV_PIX_FMT_YUVA420P9LE: case AV_PIX_FMT_YUVA420P9BE: case AV_PIX_FMT_YUVA420P10LE: case AV_PIX_FMT_YUVA420P10BE: case AV_PIX_FMT_YUVA420P16LE: case AV_PIX_FMT_YUVA420P16BE: case AV_PIX_FMT_YUV422P9LE: case AV_PIX_FMT_YUV422P9BE: case AV_PIX_FMT_YUV422P10LE: case AV_PIX_FMT_YUV422P10BE: case AV_PIX_FMT_YUV422P12LE: case AV_PIX_FMT_YUV422P12BE: case AV_PIX_FMT_YUV422P14LE: case AV_PIX_FMT_YUV422P14BE: case AV_PIX_FMT_YUV422P16LE: case AV_PIX_FMT_YUV422P16BE: case AV_PIX_FMT_YUVA422P9LE: case AV_PIX_FMT_YUVA422P9BE: case AV_PIX_FMT_YUVA422P10LE: case AV_PIX_FMT_YUVA422P10BE: case AV_PIX_FMT_YUVA422P16LE: case AV_PIX_FMT_YUVA422P16BE: case AV_PIX_FMT_YUV440P10LE: case AV_PIX_FMT_YUV440P10BE: case AV_PIX_FMT_YUV440P12LE: case AV_PIX_FMT_YUV440P12BE: case AV_PIX_FMT_YUV444P9LE: case AV_PIX_FMT_YUV444P9BE: case AV_PIX_FMT_YUV444P10LE: case AV_PIX_FMT_YUV444P10BE: case AV_PIX_FMT_YUV444P12LE: case AV_PIX_FMT_YUV444P12BE: case AV_PIX_FMT_YUV444P14LE: case AV_PIX_FMT_YUV444P14BE: case AV_PIX_FMT_YUV444P16LE: case AV_PIX_FMT_YUV444P16BE: case AV_PIX_FMT_YUVA444P9LE: case AV_PIX_FMT_YUVA444P9BE: case AV_PIX_FMT_YUVA444P10LE: case AV_PIX_FMT_YUVA444P10BE: case AV_PIX_FMT_YUVA444P16LE: case AV_PIX_FMT_YUVA444P16BE: case AV_PIX_FMT_GBRP9LE: case AV_PIX_FMT_GBRP9BE: case AV_PIX_FMT_GBRP10LE: case AV_PIX_FMT_GBRP10BE: case AV_PIX_FMT_GBRP12LE: case AV_PIX_FMT_GBRP12BE: case AV_PIX_FMT_GBRP14LE: case AV_PIX_FMT_GBRP14BE: case AV_PIX_FMT_GBRP16LE: case AV_PIX_FMT_GBRP16BE: case AV_PIX_FMT_GBRAP12LE: case AV_PIX_FMT_GBRAP12BE: case AV_PIX_FMT_GBRAP16LE: case AV_PIX_FMT_GBRAP16BE: w_align = 16; //FIXME assume 16 pixel per macroblock h_align = 16 * 2; // interlaced needs 2 macroblocks height break; case AV_PIX_FMT_YUV411P: case AV_PIX_FMT_YUVJ411P: case AV_PIX_FMT_UYYVYY411: w_align = 32; h_align = 16 * 2; break; case AV_PIX_FMT_YUV410P: if (s->codec_id == AV_CODEC_ID_SVQ1) { w_align = 64; h_align = 64; } break; case AV_PIX_FMT_RGB555: if (s->codec_id == AV_CODEC_ID_RPZA) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_PAL8: case AV_PIX_FMT_BGR8: case AV_PIX_FMT_RGB8: if (s->codec_id == AV_CODEC_ID_SMC || s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_JV) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_BGR24: if ((s->codec_id == AV_CODEC_ID_MSZH) || (s->codec_id == AV_CODEC_ID_ZLIB)) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_RGB24: if (s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } break; default: break; } if (s->codec_id == AV_CODEC_ID_IFF_ILBM) { w_align = FFMAX(w_align, 8); } *width = FFALIGN(*width, w_align); *height = FFALIGN(*height, h_align); if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) { // some of the optimized chroma MC reads one line too much // which is also done in mpeg decoders with lowres > 0 *height += 2; // H.264 uses edge emulation for out of frame motion vectors, for this // it requires a temporary area large enough to hold a 21x21 block, // increasing witdth ensure that the temporary area is large enough, // the next rounded up width is 32 *width = FFMAX(*width, 32); } for (i = 0; i < 4; i++) linesize_align[i] = STRIDE_ALIGN; }
nan
null
10,795
327181451425415011598676120237706388191
171
avcodec/utils: correct align value for interplay Fixes out of array access Fixes: 452/fuzz-1-ffmpeg_VIDEO_AV_CODEC_ID_INTERPLAY_VIDEO_fuzzer Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
radare2
9b46d38dd3c4de6048a488b655c7319f845af185
1
static int parseOperand(RAsm *a, const char *str, Operand *op, bool isrepop) { size_t pos, nextpos = 0; x86newTokenType last_type; int size_token = 1; bool explicit_size = false; int reg_index = 0; // Reset type op->type = 0; // Consume tokens denoting the operand size while (size_token) { pos = nextpos; last_type = getToken (str, &pos, &nextpos); // Token may indicate size: then skip if (!r_str_ncasecmp (str + pos, "ptr", 3)) { continue; } else if (!r_str_ncasecmp (str + pos, "byte", 4)) { op->type |= OT_MEMORY | OT_BYTE; op->dest_size = OT_BYTE; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "word", 4)) { op->type |= OT_MEMORY | OT_WORD; op->dest_size = OT_WORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "dword", 5)) { op->type |= OT_MEMORY | OT_DWORD; op->dest_size = OT_DWORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "qword", 5)) { op->type |= OT_MEMORY | OT_QWORD; op->dest_size = OT_QWORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "oword", 5)) { op->type |= OT_MEMORY | OT_OWORD; op->dest_size = OT_OWORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "tbyte", 5)) { op->type |= OT_MEMORY | OT_TBYTE; op->dest_size = OT_TBYTE; explicit_size = true; } else { // the current token doesn't denote a size size_token = 0; } } // Next token: register, immediate, or '[' if (str[pos] == '[') { // Don't care about size, if none is given. if (!op->type) { op->type = OT_MEMORY; } // At the moment, we only accept plain linear combinations: // part := address | [factor *] register // address := part {+ part}* op->offset = op->scale[0] = op->scale[1] = 0; ut64 temp = 1; Register reg = X86R_UNDEFINED; bool first_reg = true; while (str[pos] != ']') { if (pos > nextpos) { // eprintf ("Error parsing instruction\n"); break; } pos = nextpos; if (!str[pos]) { break; } last_type = getToken (str, &pos, &nextpos); if (last_type == TT_SPECIAL) { if (str[pos] == '+' || str[pos] == '-' || str[pos] == ']') { if (reg != X86R_UNDEFINED) { op->regs[reg_index] = reg; op->scale[reg_index] = temp; ++reg_index; } else { op->offset += temp; op->regs[reg_index] = X86R_UNDEFINED; } temp = 1; reg = X86R_UNDEFINED; } else if (str[pos] == '*') { // go to ], + or - to get scale // Something to do here? // Seems we are just ignoring '*' or assuming it implicitly. } } else if (last_type == TT_WORD) { ut32 reg_type = 0; // We can't multiply registers if (reg != X86R_UNDEFINED) { op->type = 0; // Make the result invalid } // Reset nextpos: parseReg wants to parse from the beginning nextpos = pos; reg = parseReg (a, str, &nextpos, &reg_type); if (first_reg) { op->extended = false; if (reg > 8) { op->extended = true; op->reg = reg - 9; } first_reg = false; } else if (reg > 8) { op->reg = reg - 9; } if (reg_type & OT_REGTYPE & OT_SEGMENTREG) { op->reg = reg; op->type = reg_type; parse_segment_offset (a, str, &nextpos, op, reg_index); return nextpos; } // Still going to need to know the size if not specified if (!explicit_size) { op->type |= reg_type; } op->reg_size = reg_type; op->explicit_size = explicit_size; // Addressing only via general purpose registers if (!(reg_type & OT_GPREG)) { op->type = 0; // Make the result invalid } } else { char *p = strchr (str, '+'); op->offset_sign = 1; if (!p) { p = strchr (str, '-'); if (p) { op->offset_sign = -1; } } //with SIB notation, we need to consider the right sign char * plus = strchr (str, '+'); char * minus = strchr (str, '-'); char * closeB = strchr (str, ']'); if (plus && minus && plus < closeB && minus < closeB) { op->offset_sign = -1; } // If there's a scale, we don't want to parse out the // scale with the offset (scale + offset) otherwise the scale // will be the sum of the two. This splits the numbers char *tmp; tmp = malloc (strlen (str + pos) + 1); strcpy (tmp, str + pos); strtok (tmp, "+-"); st64 read = getnum (a, tmp); free (tmp); temp *= read; } } } else if (last_type == TT_WORD) { // register nextpos = pos; RFlagItem *flag; if (isrepop) { op->is_good_flag = false; strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1); op->rep_op[MAX_REPOP_LENGTH - 1] = '\0'; return nextpos; } op->reg = parseReg (a, str, &nextpos, &op->type); op->extended = false; if (op->reg > 8) { op->extended = true; op->reg -= 9; } if (op->type & OT_REGTYPE & OT_SEGMENTREG) { parse_segment_offset (a, str, &nextpos, op, reg_index); return nextpos; } if (op->reg == X86R_UNDEFINED) { op->is_good_flag = false; if (a->num && a->num->value == 0) { return nextpos; } op->type = OT_CONSTANT; RCore *core = a->num? (RCore *)(a->num->userptr): NULL; if (core && (flag = r_flag_get (core->flags, str))) { op->is_good_flag = true; } char *p = strchr (str, '-'); if (p) { op->sign = -1; str = ++p; } op->immediate = getnum (a, str); } else if (op->reg < X86R_UNDEFINED) { strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1); op->rep_op[MAX_REPOP_LENGTH - 1] = '\0'; } } else { // immediate // We don't know the size, so let's just set no size flag. op->type = OT_CONSTANT; op->sign = 1; char *p = strchr (str, '-'); if (p) { op->sign = -1; str = ++p; } op->immediate = getnum (a, str); } return nextpos; }
nan
null
10,796
6131296079931054316704200634967234054
216
Fix #12372 and #12373 - Crash in x86 assembler (#12380) 0 ,0,[bP-bL-bP-bL-bL-r-bL-bP-bL-bL- mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx-- leA ,0,[bP-bL-bL-bP-bL-bP-bL-60@bL- leA ,0,[bP-bL-r-bP-bL-bP-bL-60@bL- mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx--
null
WavPack
4c0faba32fddbd0745cbfaf1e1aeb3da5d35b9fc
1
int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif // loop through all elements of the DSDIFF header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk; if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize); prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (dff_chunk_header.ckDataSize > 0 && dff_chunk_header.ckDataSize <= eptr - cptr) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; if (numChannels < chansSpecified || numChannels < 1) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
nan
null
10,797
106925413231207762746636468942678740812
245
issue #65: make sure DSDIFF files have a valid channel count
null
radare2
c6d0076c924891ad9948a62d89d0bcdaf965f0cd
1
static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { ut8 *end, *need = NULL; const char *section_name = ""; Elf_(Shdr) *link_shdr = NULL; const char *link_section_name = ""; Sdb *sdb_vernaux = NULL; Sdb *sdb_version = NULL; Sdb *sdb = NULL; int i, cnt; if (!bin || !bin->dynstr) { return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { return NULL; } if (shdr->sh_size < 1) { return NULL; } sdb = sdb_new0 (); if (!sdb) { return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) { bprintf ("Warning: Cannot allocate memory for Elf_(Verneed)\n"); goto beach; } end = need + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "num_entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) { goto beach; } if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) { goto beach; } i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size); if (i < 0) goto beach; //XXX we should use DT_VERNEEDNUM instead of sh_info //TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) { int j, isum; ut8 *vstart = need + i; Elf_(Verneed) vvn = {0}; if (vstart + sizeof (Elf_(Verneed)) > end) { goto beach; } Elf_(Verneed) *entry = &vvn; char key[32] = {0}; sdb_version = sdb_new0 (); if (!sdb_version) { goto beach; } j = 0; vvn.vn_version = READ16 (vstart, j) vvn.vn_cnt = READ16 (vstart, j) vvn.vn_file = READ32 (vstart, j) vvn.vn_aux = READ32 (vstart, j) vvn.vn_next = READ32 (vstart, j) sdb_num_set (sdb_version, "vn_version", entry->vn_version, 0); sdb_num_set (sdb_version, "idx", i, 0); if (entry->vn_file > bin->dynstr_size) { goto beach; } { char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16); sdb_set (sdb_version, "file_name", s, 0); free (s); } sdb_num_set (sdb_version, "cnt", entry->vn_cnt, 0); vstart += entry->vn_aux; for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) { int k; Elf_(Vernaux) * aux = NULL; Elf_(Vernaux) vaux = {0}; sdb_vernaux = sdb_new0 (); if (!sdb_vernaux) { goto beach; } aux = (Elf_(Vernaux)*)&vaux; k = 0; vaux.vna_hash = READ32 (vstart, k) vaux.vna_flags = READ16 (vstart, k) vaux.vna_other = READ16 (vstart, k) vaux.vna_name = READ32 (vstart, k) vaux.vna_next = READ32 (vstart, k) if (aux->vna_name > bin->dynstr_size) { goto beach; } sdb_num_set (sdb_vernaux, "idx", isum, 0); if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) { char name [16]; strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1); name[sizeof(name)-1] = 0; sdb_set (sdb_vernaux, "name", name, 0); } sdb_set (sdb_vernaux, "flags", get_ver_flags (aux->vna_flags), 0); sdb_num_set (sdb_vernaux, "version", aux->vna_other, 0); isum += aux->vna_next; vstart += aux->vna_next; snprintf (key, sizeof (key), "vernaux%d", j); sdb_ns_set (sdb_version, key, sdb_vernaux); } if ((int)entry->vn_next < 0) { bprintf ("Invalid vn_next\n"); break; } i += entry->vn_next; snprintf (key, sizeof (key), "version%d", cnt ); sdb_ns_set (sdb, key, sdb_version); //if entry->vn_next is 0 it iterate infinitely if (!entry->vn_next) { break; } } free (need); return sdb; beach: free (need); sdb_free (sdb_vernaux); sdb_free (sdb_version); sdb_free (sdb); return NULL; }
nan
null
10,798
277570248229841461520480649377850871527
138
Fix #8731 - Crash in ELF parser with negative 32bit number
null
qemu
1e7aed70144b4673fc26e73062064b6724795e5f
1
static void virtqueue_map_desc(unsigned int *p_num_sg, hwaddr *addr, struct iovec *iov, unsigned int max_num_sg, bool is_write, hwaddr pa, size_t sz) { unsigned num_sg = *p_num_sg; assert(num_sg <= max_num_sg); while (sz) { hwaddr len = sz; if (num_sg == max_num_sg) { error_report("virtio: too many write descriptors in indirect table"); exit(1); } iov[num_sg].iov_base = cpu_physical_memory_map(pa, &len, is_write); iov[num_sg].iov_len = len; addr[num_sg] = pa; sz -= len; pa += len; num_sg++; } *p_num_sg = num_sg; }
nan
null
10,799
36317471279521865956953602658204486196
25
virtio: check vring descriptor buffer length virtio back end uses set of buffers to facilitate I/O operations. An infinite loop unfolds in virtqueue_pop() if a buffer was of zero size. Add check to avoid it. Reported-by: Li Qiang <liqiang6-s@360.cn> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Reviewed-by: Michael S. Tsirkin <mst@redhat.com> Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Reviewed-by: Stefan Hajnoczi <stefanha@redhat.com>
null
file
59e63838913eee47f5c120a6c53d4565af638158
1
*/ private int mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; uint8_t type; switch (type = cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { size_t sz = file_pstring_length_size(m); char *ptr1 = p->s, *ptr2 = ptr1 + sz; size_t len = file_pstring_get_length(m, ptr1); if (len >= sizeof(p->s)) { /* * The size of the pascal string length (sz) * is 1, 2, or 4. We need at least 1 byte for NUL * termination, but we've already truncated the * string by p->s, so we need to deduct sz. */ len = sizeof(p->s) - sz; } while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); if (type == FILE_BELONG) cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); if (type == FILE_BEQUAD) cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); if (type == FILE_LELONG) cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); if (type == FILE_LEQUAD) cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); if (type == FILE_MELONG) cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0;
nan
null
10,800
223205916752918667513155437621986050492
146
PR/398: Correctly truncate pascal strings (fixes out of bounds read of 1, 2, or 4 bytes).
null
php-src
b101a6bbd4f2181c360bd38e7683df4a03cba83e
1
static void zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */ { va_list va; char *message = NULL; va_start(va, format); zend_vspprintf(&message, 0, format, va); if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) { zend_throw_error(exception_ce, message); } else { zend_error(E_ERROR, "%s", message); } efree(message); va_end(va); }
nan
null
10,801
274261182855572451477980971944468655969
17
Use format string
null
gnupg
014b2103fcb12f261135e3954f26e9e07b39e342
1
do_uncompress( compress_filter_context_t *zfx, z_stream *zs, IOBUF a, size_t *ret_len ) { int zrc; int rc=0; size_t n; int nread, count; int refill = !zs->avail_in; if( DBG_FILTER ) log_debug("begin inflate: avail_in=%u, avail_out=%u, inbuf=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, (unsigned)zfx->inbufsize ); do { if( zs->avail_in < zfx->inbufsize && refill ) { n = zs->avail_in; if( !n ) zs->next_in = BYTEF_CAST (zfx->inbuf); count = zfx->inbufsize - n; nread = iobuf_read( a, zfx->inbuf + n, count ); if( nread == -1 ) nread = 0; n += nread; /* If we use the undocumented feature to suppress * the zlib header, we have to give inflate an * extra dummy byte to read */ if( nread < count && zfx->algo == 1 ) { *(zfx->inbuf + n) = 0xFF; /* is it really needed ? */ zfx->algo1hack = 1; n++; } zs->avail_in = n; } refill = 1; if( DBG_FILTER ) log_debug("enter inflate: avail_in=%u, avail_out=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out); zrc = inflate ( zs, Z_SYNC_FLUSH ); if( DBG_FILTER ) log_debug("leave inflate: avail_in=%u, avail_out=%u, zrc=%d\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, zrc); if( zrc == Z_STREAM_END ) rc = -1; /* eof */ else if( zrc != Z_OK && zrc != Z_BUF_ERROR ) { if( zs->msg ) log_fatal("zlib inflate problem: %s\n", zs->msg ); else log_fatal("zlib inflate problem: rc=%d\n", zrc ); } } while( zs->avail_out && zrc != Z_STREAM_END && zrc != Z_BUF_ERROR ); *ret_len = zfx->outbufsize - zs->avail_out; if( DBG_FILTER ) log_debug("do_uncompress: returning %u bytes (%u ignored)\n", (unsigned int)*ret_len, (unsigned int)zs->avail_in ); return rc; }
nan
null
10,802
87629636256725127151953116369002639873
56
gpg: Avoid infinite loop in uncompressing garbled packets. * g10/compress.c (do_uncompress): Limit the number of extra FF bytes. -- A packet like (a3 01 5b ff) leads to an infinite loop. Using --max-output won't help if it is a partial packet. This patch actually fixes a regression introduced on 1999-05-31 (c34c6769). Actually it would be sufficient to stuff just one extra 0xff byte. Given that this problem popped up only after 15 years, I feel safer to allow for a very few FF bytes. Thanks to Olivier Levillain and Florian Maury for their detailed report.
null
udisks
0fcc7cb3b66f23fac53ae08647aa0007a2bd56c4
1
dm_export (int major, int minor) { gboolean ret; struct dm_task *dmt; void *next; uint64_t start, length; char *target_type; char *params; const char *name; struct dm_info info; GString *target_types_str; GString *start_str; GString *length_str; GString *params_str; gchar buf[4096]; ret = FALSE; dmt = NULL; dmt = dm_task_create (DM_DEVICE_TABLE); if (dmt == NULL) { perror ("dm_task_create"); goto out; } if (dm_task_set_major (dmt, major) == 0) { perror ("dm_task_set_major"); goto out; } if (dm_task_set_minor (dmt, minor) == 0) { perror ("dm_task_set_minor"); goto out; } if (dm_task_run (dmt) == 0) { perror ("dm_task_run"); goto out; } if (dm_task_get_info (dmt, &info) == 0 || !info.exists) { perror ("dm_task_get_info"); goto out; } name = dm_task_get_name (dmt); if (name == NULL) { perror ("dm_task_get_name"); goto out; } if (!info.exists) { goto out; } if (info.target_count != -1) g_print ("UDISKS_DM_TARGETS_COUNT=%d\n", info.target_count); target_types_str = g_string_new (NULL); start_str = g_string_new (NULL); length_str = g_string_new (NULL); params_str = g_string_new (NULL); /* export all tables */ next = NULL; do { next = dm_get_next_target (dmt, next, &start, &length, &target_type, &params); if (target_type != NULL) { g_string_append (target_types_str, target_type); g_string_append_printf (start_str, "%" G_GUINT64_FORMAT, start); g_string_append_printf (length_str, "%" G_GUINT64_FORMAT, length); if (params != NULL && strlen (params) > 0) { _udev_util_encode_string (params, buf, sizeof (buf)); g_string_append (params_str, buf); } } if (next != NULL) { g_string_append_c (target_types_str, ' '); g_string_append_c (start_str, ' '); g_string_append_c (length_str, ' '); g_string_append_c (params_str, ' '); } } while (next != NULL); if (target_types_str->len > 0) g_print ("UDISKS_DM_TARGETS_TYPE=%s\n", target_types_str->str); if (start_str->len > 0) g_print ("UDISKS_DM_TARGETS_START=%s\n", start_str->str); if (length_str->len > 0) g_print ("UDISKS_DM_TARGETS_LENGTH=%s\n", length_str->str); if (params_str->len > 0) g_print ("UDISKS_DM_TARGETS_PARAMS=%s\n", params_str->str); g_string_free (target_types_str, TRUE); g_string_free (start_str, TRUE); g_string_free (length_str, TRUE); g_string_free (params_str, TRUE); ret = TRUE; out: if (dmt != NULL) dm_task_destroy(dmt); return ret; }
nan
null
10,804
324533183669046299039923090073960746787
118
Bug 27494 — publicly exports dm key information Change udisks-dm-export to only export UDISKS_DM_TARGETS_PARAMS for "linear" types. It is the only one we care about for now and know how to interpret. "crypto" types have information about the encryption key in the target parameters, which we must not leak. Also add appropriate comments to the two places which currently evaluate UDISKS_DM_TARGETS_PARAMS.
null
linux
fa3d315a4ce2c0891cdde262562e710d95fba19e
1
static int FNAME(walk_addr_generic)(struct guest_walker *walker, struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, gva_t addr, u32 access) { pt_element_t pte; pt_element_t __user *ptep_user; gfn_t table_gfn; unsigned index, pt_access, uninitialized_var(pte_access); gpa_t pte_gpa; bool eperm, present, rsvd_fault; int offset, write_fault, user_fault, fetch_fault; write_fault = access & PFERR_WRITE_MASK; user_fault = access & PFERR_USER_MASK; fetch_fault = access & PFERR_FETCH_MASK; trace_kvm_mmu_pagetable_walk(addr, write_fault, user_fault, fetch_fault); walk: present = true; eperm = rsvd_fault = false; walker->level = mmu->root_level; pte = mmu->get_cr3(vcpu); #if PTTYPE == 64 if (walker->level == PT32E_ROOT_LEVEL) { pte = kvm_pdptr_read_mmu(vcpu, mmu, (addr >> 30) & 3); trace_kvm_mmu_paging_element(pte, walker->level); if (!is_present_gpte(pte)) { present = false; goto error; } --walker->level; } #endif ASSERT((!is_long_mode(vcpu) && is_pae(vcpu)) || (mmu->get_cr3(vcpu) & CR3_NONPAE_RESERVED_BITS) == 0); pt_access = ACC_ALL; for (;;) { gfn_t real_gfn; unsigned long host_addr; index = PT_INDEX(addr, walker->level); table_gfn = gpte_to_gfn(pte); offset = index * sizeof(pt_element_t); pte_gpa = gfn_to_gpa(table_gfn) + offset; walker->table_gfn[walker->level - 1] = table_gfn; walker->pte_gpa[walker->level - 1] = pte_gpa; real_gfn = mmu->translate_gpa(vcpu, gfn_to_gpa(table_gfn), PFERR_USER_MASK|PFERR_WRITE_MASK); if (unlikely(real_gfn == UNMAPPED_GVA)) { present = false; break; } real_gfn = gpa_to_gfn(real_gfn); host_addr = gfn_to_hva(vcpu->kvm, real_gfn); if (unlikely(kvm_is_error_hva(host_addr))) { present = false; break; } ptep_user = (pt_element_t __user *)((void *)host_addr + offset); if (unlikely(copy_from_user(&pte, ptep_user, sizeof(pte)))) { present = false; break; } trace_kvm_mmu_paging_element(pte, walker->level); if (unlikely(!is_present_gpte(pte))) { present = false; break; } if (unlikely(is_rsvd_bits_set(&vcpu->arch.mmu, pte, walker->level))) { rsvd_fault = true; break; } if (unlikely(write_fault && !is_writable_pte(pte) && (user_fault || is_write_protection(vcpu)))) eperm = true; if (unlikely(user_fault && !(pte & PT_USER_MASK))) eperm = true; #if PTTYPE == 64 if (unlikely(fetch_fault && (pte & PT64_NX_MASK))) eperm = true; #endif if (!eperm && !rsvd_fault && unlikely(!(pte & PT_ACCESSED_MASK))) { int ret; trace_kvm_mmu_set_accessed_bit(table_gfn, index, sizeof(pte)); ret = FNAME(cmpxchg_gpte)(vcpu, mmu, table_gfn, index, pte, pte|PT_ACCESSED_MASK); if (ret < 0) { present = false; break; } else if (ret) goto walk; mark_page_dirty(vcpu->kvm, table_gfn); pte |= PT_ACCESSED_MASK; } pte_access = pt_access & FNAME(gpte_access)(vcpu, pte); walker->ptes[walker->level - 1] = pte; if ((walker->level == PT_PAGE_TABLE_LEVEL) || ((walker->level == PT_DIRECTORY_LEVEL) && is_large_pte(pte) && (PTTYPE == 64 || is_pse(vcpu))) || ((walker->level == PT_PDPE_LEVEL) && is_large_pte(pte) && mmu->root_level == PT64_ROOT_LEVEL)) { int lvl = walker->level; gpa_t real_gpa; gfn_t gfn; u32 ac; gfn = gpte_to_gfn_lvl(pte, lvl); gfn += (addr & PT_LVL_OFFSET_MASK(lvl)) >> PAGE_SHIFT; if (PTTYPE == 32 && walker->level == PT_DIRECTORY_LEVEL && is_cpuid_PSE36()) gfn += pse36_gfn_delta(pte); ac = write_fault | fetch_fault | user_fault; real_gpa = mmu->translate_gpa(vcpu, gfn_to_gpa(gfn), ac); if (real_gpa == UNMAPPED_GVA) return 0; walker->gfn = real_gpa >> PAGE_SHIFT; break; } pt_access = pte_access; --walker->level; } if (unlikely(!present || eperm || rsvd_fault)) goto error; if (write_fault && unlikely(!is_dirty_gpte(pte))) { int ret; trace_kvm_mmu_set_dirty_bit(table_gfn, index, sizeof(pte)); ret = FNAME(cmpxchg_gpte)(vcpu, mmu, table_gfn, index, pte, pte|PT_DIRTY_MASK); if (ret < 0) { present = false; goto error; } else if (ret) goto walk; mark_page_dirty(vcpu->kvm, table_gfn); pte |= PT_DIRTY_MASK; walker->ptes[walker->level - 1] = pte; } walker->pt_access = pt_access; walker->pte_access = pte_access; pgprintk("%s: pte %llx pte_access %x pt_access %x\n", __func__, (u64)pte, pte_access, pt_access); return 1; error: walker->fault.vector = PF_VECTOR; walker->fault.error_code_valid = true; walker->fault.error_code = 0; if (present) walker->fault.error_code |= PFERR_PRESENT_MASK; walker->fault.error_code |= write_fault | user_fault; if (fetch_fault && mmu->nx) walker->fault.error_code |= PFERR_FETCH_MASK; if (rsvd_fault) walker->fault.error_code |= PFERR_RSVD_MASK; walker->fault.address = addr; walker->fault.nested_page_fault = mmu != vcpu->arch.walk_mmu; trace_kvm_mmu_walker_error(walker->fault.error_code); return 0; }
nan
null
10,807
152638346673194922340011889617763157996
200
KVM: Validate userspace_addr of memslot when registered This way, we can avoid checking the user space address many times when we read the guest memory. Although we can do the same for write if we check which slots are writable, we do not care write now: reading the guest memory happens more often than writing. [avi: change VERIFY_READ to VERIFY_WRITE] Signed-off-by: Takuya Yoshikawa <yoshikawa.takuya@oss.ntt.co.jp> Signed-off-by: Avi Kivity <avi@redhat.com>
null
FFmpeg
296debd213bd6dce7647cedd34eb64e5b94cdc92
1
static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame, const uint8_t *buf, int buf_size, int first_field) { int i, cid, ret; int old_bit_depth = ctx->bit_depth, bitdepth; uint64_t header_prefix; if (buf_size < 0x280) { av_log(ctx->avctx, AV_LOG_ERROR, "buffer too small (%d < 640).\n", buf_size); return AVERROR_INVALIDDATA; } header_prefix = ff_dnxhd_parse_header_prefix(buf); if (header_prefix == 0) { av_log(ctx->avctx, AV_LOG_ERROR, "unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n", buf[0], buf[1], buf[2], buf[3], buf[4]); return AVERROR_INVALIDDATA; } if (buf[5] & 2) { /* interlaced */ ctx->cur_field = buf[5] & 1; frame->interlaced_frame = 1; frame->top_field_first = first_field ^ ctx->cur_field; av_log(ctx->avctx, AV_LOG_DEBUG, "interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field); } else { ctx->cur_field = 0; } ctx->mbaff = (buf[0x6] >> 5) & 1; ctx->height = AV_RB16(buf + 0x18); ctx->width = AV_RB16(buf + 0x1a); switch(buf[0x21] >> 5) { case 1: bitdepth = 8; break; case 2: bitdepth = 10; break; case 3: bitdepth = 12; break; default: av_log(ctx->avctx, AV_LOG_ERROR, "Unknown bitdepth indicator (%d)\n", buf[0x21] >> 5); return AVERROR_INVALIDDATA; } cid = AV_RB32(buf + 0x28); ctx->avctx->profile = dnxhd_get_profile(cid); if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0) return ret; if (ctx->mbaff && ctx->cid_table->cid != 1260) av_log(ctx->avctx, AV_LOG_WARNING, "Adaptive MB interlace flag in an unsupported profile.\n"); ctx->act = buf[0x2C] & 7; if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270) av_log(ctx->avctx, AV_LOG_WARNING, "Adaptive color transform in an unsupported profile.\n"); ctx->is_444 = (buf[0x2C] >> 6) & 1; if (ctx->is_444) { if (bitdepth == 8) { avpriv_request_sample(ctx->avctx, "4:4:4 8 bits"); return AVERROR_INVALIDDATA; } else if (bitdepth == 10) { ctx->decode_dct_block = dnxhd_decode_dct_block_10_444; ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10 : AV_PIX_FMT_GBRP10; } else { ctx->decode_dct_block = dnxhd_decode_dct_block_12_444; ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12 : AV_PIX_FMT_GBRP12; } } else if (bitdepth == 12) { ctx->decode_dct_block = dnxhd_decode_dct_block_12; ctx->pix_fmt = AV_PIX_FMT_YUV422P12; } else if (bitdepth == 10) { if (ctx->avctx->profile == FF_PROFILE_DNXHR_HQX) ctx->decode_dct_block = dnxhd_decode_dct_block_10_444; else ctx->decode_dct_block = dnxhd_decode_dct_block_10; ctx->pix_fmt = AV_PIX_FMT_YUV422P10; } else { ctx->decode_dct_block = dnxhd_decode_dct_block_8; ctx->pix_fmt = AV_PIX_FMT_YUV422P; } ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth; if (ctx->bit_depth != old_bit_depth) { ff_blockdsp_init(&ctx->bdsp, ctx->avctx); ff_idctdsp_init(&ctx->idsp, ctx->avctx); ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable, ff_zigzag_direct); } // make sure profile size constraints are respected // DNx100 allows 1920->1440 and 1280->960 subsampling if (ctx->width != ctx->cid_table->width && ctx->cid_table->width != DNXHD_VARIABLE) { av_reduce(&ctx->avctx->sample_aspect_ratio.num, &ctx->avctx->sample_aspect_ratio.den, ctx->width, ctx->cid_table->width, 255); ctx->width = ctx->cid_table->width; } if (buf_size < ctx->cid_table->coding_unit_size) { av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %u).\n", buf_size, ctx->cid_table->coding_unit_size); return AVERROR_INVALIDDATA; } ctx->mb_width = (ctx->width + 15)>> 4; ctx->mb_height = AV_RB16(buf + 0x16c); if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame) ctx->height <<= 1; av_log(ctx->avctx, AV_LOG_VERBOSE, "%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\n", ctx->width, ctx->height, ctx->is_444 ? "4:4" : "2:2", ctx->bit_depth, ctx->mbaff, ctx->act); // Newer format supports variable mb_scan_index sizes if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) { ctx->data_offset = 0x170 + (ctx->mb_height << 2); } else { if (ctx->mb_height > 68 || (ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) { av_log(ctx->avctx, AV_LOG_ERROR, "mb height too big: %d\n", ctx->mb_height); return AVERROR_INVALIDDATA; } ctx->data_offset = 0x280; } if (buf_size < ctx->data_offset) { av_log(ctx->avctx, AV_LOG_ERROR, "buffer too small (%d < %d).\n", buf_size, ctx->data_offset); return AVERROR_INVALIDDATA; } if (ctx->mb_height > FF_ARRAY_ELEMS(ctx->mb_scan_index)) { av_log(ctx->avctx, AV_LOG_ERROR, "mb_height too big (%d > %"SIZE_SPECIFIER").\n", ctx->mb_height, FF_ARRAY_ELEMS(ctx->mb_scan_index)); return AVERROR_INVALIDDATA; } for (i = 0; i < ctx->mb_height; i++) { ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2)); ff_dlog(ctx->avctx, "mb scan index %d, pos %d: %"PRIu32"\n", i, 0x170 + (i << 2), ctx->mb_scan_index[i]); if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) { av_log(ctx->avctx, AV_LOG_ERROR, "invalid mb scan index (%"PRIu32" vs %u).\n", ctx->mb_scan_index[i], buf_size - ctx->data_offset); return AVERROR_INVALIDDATA; } } return 0; }
nan
null
10,809
177963056591493665543252553847431484276
160
avcodec/dnxhddec: Move mb height check out of non hr branch Fixes: out of array access Fixes: poc.dnxhd Found-by: Bingchang, Liu@VARAS of IIE Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
FFmpeg
6b67d7f05918f7a1ee8fc6ff21355d7e8736aa10
1
static int flv_write_packet(AVFormatContext *s, AVPacket *pkt) { AVIOContext *pb = s->pb; AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar; FLVContext *flv = s->priv_data; FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data; unsigned ts; int size = pkt->size; uint8_t *data = NULL; int flags = -1, flags_size, ret; int64_t cur_offset = avio_tell(pb); if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A || par->codec_id == AV_CODEC_ID_VP6 || par->codec_id == AV_CODEC_ID_AAC) flags_size = 2; else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) flags_size = 5; else flags_size = 1; if (par->codec_id == AV_CODEC_ID_AAC || par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { av_free(par->extradata); par->extradata = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!par->extradata) { par->extradata_size = 0; return AVERROR(ENOMEM); } memcpy(par->extradata, side, side_size); par->extradata_size = side_size; flv_write_codec_header(s, par, pkt->dts); } } if (flv->delay == AV_NOPTS_VALUE) flv->delay = -pkt->dts; if (pkt->dts < -flv->delay) { av_log(s, AV_LOG_WARNING, "Packets are not in the proper order with respect to DTS\n"); return AVERROR(EINVAL); } ts = pkt->dts; if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) { write_metadata(s, ts); s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED; } avio_write_marker(pb, av_rescale(ts, AV_TIME_BASE, 1000), pkt->flags & AV_PKT_FLAG_KEY && (flv->video_par ? par->codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: avio_w8(pb, FLV_TAG_TYPE_VIDEO); flags = ff_codec_get_tag(flv_video_codec_ids, par->codec_id); flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER; break; case AVMEDIA_TYPE_AUDIO: flags = get_audio_flags(s, par); av_assert0(size); avio_w8(pb, FLV_TAG_TYPE_AUDIO); break; case AVMEDIA_TYPE_SUBTITLE: case AVMEDIA_TYPE_DATA: avio_w8(pb, FLV_TAG_TYPE_META); break; default: return AVERROR(EINVAL); } if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { /* check if extradata looks like mp4 formatted */ if (par->extradata_size > 0 && *(uint8_t*)par->extradata != 1) if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0) return ret; } else if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return AVERROR_INVALIDDATA; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } /* check Speex packet duration */ if (par->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160) av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than " "8 frames per packet. Adobe Flash " "Player cannot handle this!\n"); if (sc->last_ts < ts) sc->last_ts = ts; if (size + flags_size >= 1<<24) { av_log(s, AV_LOG_ERROR, "Too large packet with size %u >= %u\n", size + flags_size, 1<<24); return AVERROR(EINVAL); } avio_wb24(pb, size + flags_size); put_timestamp(pb, ts); avio_wb24(pb, flv->reserved); if (par->codec_type == AVMEDIA_TYPE_DATA || par->codec_type == AVMEDIA_TYPE_SUBTITLE ) { int data_size; int64_t metadata_size_pos = avio_tell(pb); if (par->codec_id == AV_CODEC_ID_TEXT) { // legacy FFmpeg magic? avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "onTextData"); avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY); avio_wb32(pb, 2); put_amf_string(pb, "type"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "Text"); put_amf_string(pb, "text"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, pkt->data); put_amf_string(pb, ""); avio_w8(pb, AMF_END_OF_OBJECT); } else { // just pass the metadata through avio_write(pb, data ? data : pkt->data, size); } /* write total size of tag */ data_size = avio_tell(pb) - metadata_size_pos; avio_seek(pb, metadata_size_pos - 10, SEEK_SET); avio_wb24(pb, data_size); avio_seek(pb, data_size + 10 - 3, SEEK_CUR); avio_wb32(pb, data_size + 11); } else { av_assert1(flags>=0); avio_w8(pb,flags); if (par->codec_id == AV_CODEC_ID_VP6) avio_w8(pb,0); if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A) { if (par->extradata_size) avio_w8(pb, par->extradata[0]); else avio_w8(pb, ((FFALIGN(par->width, 16) - par->width) << 4) | (FFALIGN(par->height, 16) - par->height)); } else if (par->codec_id == AV_CODEC_ID_AAC) avio_w8(pb, 1); // AAC raw else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { avio_w8(pb, 1); // AVC NALU avio_wb24(pb, pkt->pts - pkt->dts); } avio_write(pb, data ? data : pkt->data, size); avio_wb32(pb, size + flags_size + 11); // previous tag size flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration); } if (flv->flags & FLV_ADD_KEYFRAME_INDEX) { switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: flv->videosize += (avio_tell(pb) - cur_offset); flv->lasttimestamp = flv->acurframeindex / flv->framerate; if (pkt->flags & AV_PKT_FLAG_KEY) { double ts = flv->acurframeindex / flv->framerate; int64_t pos = cur_offset; flv->lastkeyframetimestamp = flv->acurframeindex / flv->framerate; flv->lastkeyframelocation = pos; flv_append_keyframe_info(s, flv, ts, pos); } flv->acurframeindex++; break; case AVMEDIA_TYPE_AUDIO: flv->audiosize += (avio_tell(pb) - cur_offset); break; default: av_log(s, AV_LOG_WARNING, "par->codec_type is type = [%d]\n", par->codec_type); break; } } av_free(data); return pb->error; }
nan
null
10,810
322148846991142317684833223775394039961
197
avformat/flvenc: Check audio packet size Fixes: Assertion failure Fixes: assert_flvenc.c:941_1.swf Found-by: #CHEN HONGXU# <HCHEN017@e.ntu.edu.sg> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
FFmpeg
29ffeef5e73b8f41ff3a3f2242d356759c66f91f
1
static int decode_slice_header(H264Context *h, H264Context *h0) { unsigned int first_mb_in_slice; unsigned int pps_id; int ret; unsigned int slice_type, tmp, i, j; int last_pic_structure, last_pic_droppable; int must_reinit; int needs_reinit = 0; int field_pic_flag, bottom_field_flag; h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab; h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab; first_mb_in_slice = get_ue_golomb_long(&h->gb); if (first_mb_in_slice == 0) { // FIXME better field boundary detection if (h0->current_slice && FIELD_PICTURE(h)) { field_end(h, 1); } h0->current_slice = 0; if (!h0->first_field) { if (h->cur_pic_ptr && !h->droppable) { ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, h->picture_structure == PICT_BOTTOM_FIELD); } h->cur_pic_ptr = NULL; } } slice_type = get_ue_golomb_31(&h->gb); if (slice_type > 9) { av_log(h->avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", slice_type, h->mb_x, h->mb_y); return AVERROR_INVALIDDATA; } if (slice_type > 4) { slice_type -= 5; h->slice_type_fixed = 1; } else h->slice_type_fixed = 0; slice_type = golomb_to_pict_type[slice_type]; h->slice_type = slice_type; h->slice_type_nos = slice_type & 3; // to make a few old functions happy, it's wrong though h->pict_type = h->slice_type; pps_id = get_ue_golomb(&h->gb); if (pps_id >= MAX_PPS_COUNT) { av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id); return AVERROR_INVALIDDATA; } if (!h0->pps_buffers[pps_id]) { av_log(h->avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id); return AVERROR_INVALIDDATA; } h->pps = *h0->pps_buffers[pps_id]; if (!h0->sps_buffers[h->pps.sps_id]) { av_log(h->avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id); return AVERROR_INVALIDDATA; } if (h->pps.sps_id != h->current_sps_id || h0->sps_buffers[h->pps.sps_id]->new) { h0->sps_buffers[h->pps.sps_id]->new = 0; h->current_sps_id = h->pps.sps_id; h->sps = *h0->sps_buffers[h->pps.sps_id]; if (h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc ) needs_reinit = 1; if (h->bit_depth_luma != h->sps.bit_depth_luma || h->chroma_format_idc != h->sps.chroma_format_idc) { h->bit_depth_luma = h->sps.bit_depth_luma; h->chroma_format_idc = h->sps.chroma_format_idc; needs_reinit = 1; } if ((ret = h264_set_parameter_from_sps(h)) < 0) return ret; } h->avctx->profile = ff_h264_get_profile(&h->sps); h->avctx->level = h->sps.level_idc; h->avctx->refs = h->sps.ref_frame_count; must_reinit = (h->context_initialized && ( 16*h->sps.mb_width != h->avctx->coded_width || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio) || h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) )); if (h0->avctx->pix_fmt != get_pixel_format(h0, 0)) must_reinit = 1; h->mb_width = h->sps.mb_width; h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag); h->mb_num = h->mb_width * h->mb_height; h->mb_stride = h->mb_width + 1; h->b_stride = h->mb_width * 4; h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p h->width = 16 * h->mb_width; h->height = 16 * h->mb_height; ret = init_dimensions(h); if (ret < 0) return ret; if (h->sps.video_signal_type_present_flag) { h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (h->sps.colour_description_present_flag) { if (h->avctx->colorspace != h->sps.colorspace) needs_reinit = 1; h->avctx->color_primaries = h->sps.color_primaries; h->avctx->color_trc = h->sps.color_trc; h->avctx->colorspace = h->sps.colorspace; } } if (h->context_initialized && (h->width != h->avctx->coded_width || h->height != h->avctx->coded_height || must_reinit || needs_reinit)) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "changing width/height on " "slice %d\n", h0->current_slice + 1); return AVERROR_INVALIDDATA; } flush_change(h); if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, " "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt)); if ((ret = h264_slice_header_init(h, 1)) < 0) { av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed\n"); return ret; } } if (!h->context_initialized) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "Cannot (re-)initialize context during parallel decoding.\n"); return AVERROR_PATCHWELCOME; } if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; if ((ret = h264_slice_header_init(h, 0)) < 0) { av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed\n"); return ret; } } if (h == h0 && h->dequant_coeff_pps != pps_id) { h->dequant_coeff_pps = pps_id; init_dequant_tables(h); } h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num); h->mb_mbaff = 0; h->mb_aff_frame = 0; last_pic_structure = h0->picture_structure; last_pic_droppable = h0->droppable; h->droppable = h->nal_ref_idc == 0; if (h->sps.frame_mbs_only_flag) { h->picture_structure = PICT_FRAME; } else { if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) { av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n"); return -1; } field_pic_flag = get_bits1(&h->gb); if (field_pic_flag) { bottom_field_flag = get_bits1(&h->gb); h->picture_structure = PICT_TOP_FIELD + bottom_field_flag; } else { h->picture_structure = PICT_FRAME; h->mb_aff_frame = h->sps.mb_aff; } } h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME; if (h0->current_slice != 0) { if (last_pic_structure != h->picture_structure || last_pic_droppable != h->droppable) { av_log(h->avctx, AV_LOG_ERROR, "Changing field mode (%d -> %d) between slices is not allowed\n", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (!h0->cur_pic_ptr) { av_log(h->avctx, AV_LOG_ERROR, "unset cur_pic_ptr on %d. slice\n", h0->current_slice + 1); return AVERROR_INVALIDDATA; } } else { /* Shorten frame num gaps so we don't have to allocate reference * frames just to throw them away */ if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) { int unwrap_prev_frame_num = h->prev_frame_num; int max_frame_num = 1 << h->sps.log2_max_frame_num; if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num; if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) { unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1; if (unwrap_prev_frame_num < 0) unwrap_prev_frame_num += max_frame_num; h->prev_frame_num = unwrap_prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * Here, we're using that to see if we should mark previously * decode frames as "finished". * We have to do that before the "dummy" in-between frame allocation, * since that can modify h->cur_pic_ptr. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.data[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* Mark old field/frame as completed */ if (!last_pic_droppable && h0->cur_pic_ptr->tf.owner == h0->avctx) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_BOTTOM_FIELD); } /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ if (!last_pic_droppable && last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { /* This and previous field were reference, but had * different frame_nums. Consider this field first in * pair. Throw away previous field except for reference * purposes. */ if (!last_pic_droppable && last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { /* Second field in complementary pair */ if (!((last_pic_structure == PICT_TOP_FIELD && h->picture_structure == PICT_BOTTOM_FIELD) || (last_pic_structure == PICT_BOTTOM_FIELD && h->picture_structure == PICT_TOP_FIELD))) { av_log(h->avctx, AV_LOG_ERROR, "Invalid field mode combination %d/%d\n", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (last_pic_droppable != h->droppable) { avpriv_request_sample(h->avctx, "Found reference and non-reference fields in the same frame, which"); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_PATCHWELCOME; } } } } while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !h0->first_field && h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) { Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL; av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num); if (!h->sps.gaps_in_frame_num_allowed_flag) for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++) h->last_pocs[i] = INT_MIN; ret = h264_frame_start(h); if (ret < 0) return ret; h->prev_frame_num++; h->prev_frame_num %= 1 << h->sps.log2_max_frame_num; h->cur_pic_ptr->frame_num = h->prev_frame_num; ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0); ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1); ret = ff_generate_sliding_window_mmcos(h, 1); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; /* Error concealment: If a ref is missing, copy the previous ref * in its place. * FIXME: Avoiding a memcpy would be nice, but ref handling makes * many assumptions about there being no actual duplicates. * FIXME: This does not copy padding for out-of-frame motion * vectors. Given we are concealing a lost frame, this probably * is not noticeable by comparison, but it should be fixed. */ if (h->short_ref_count) { if (prev) { av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize, (const uint8_t **)prev->f.data, prev->f.linesize, h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16); h->short_ref[0]->poc = prev->poc + 2; } h->short_ref[0]->frame_num = h->prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * We're using that to see whether to continue decoding in that * frame, or to allocate a new one. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.data[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ h0->cur_pic_ptr = NULL; h0->first_field = FIELD_PICTURE(h); } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, h0->picture_structure==PICT_BOTTOM_FIELD); /* This and the previous field had different frame_nums. * Consider this field first in pair. Throw away previous * one except for reference purposes. */ h0->first_field = 1; h0->cur_pic_ptr = NULL; } else { /* Second field in complementary pair */ h0->first_field = 0; } } } else { /* Frame or first field in a potentially complementary pair */ h0->first_field = FIELD_PICTURE(h); } if (!FIELD_PICTURE(h) || h0->first_field) { if (h264_frame_start(h) < 0) { h0->first_field = 0; return AVERROR_INVALIDDATA; } } else { release_unused_pictures(h, 0); } /* Some macroblocks can be accessed before they're available in case * of lost slices, MBAFF or threading. */ if (FIELD_PICTURE(h)) { for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++) memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table)); } else { memset(h->slice_table, -1, (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table)); } h0->last_slice_type = -1; } if (h != h0 && (ret = clone_slice(h, h0)) < 0) return ret; /* can't be in alloc_tables because linesize isn't known there. * FIXME: redo bipred weight to not require extra buffer? */ for (i = 0; i < h->slice_context_count; i++) if (h->thread_context[i]) { ret = alloc_scratch_buffers(h->thread_context[i], h->linesize); if (ret < 0) return ret; } h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup av_assert1(h->mb_num == h->mb_width * h->mb_height); if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num || first_mb_in_slice >= h->mb_num) { av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n"); return AVERROR_INVALIDDATA; } h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width; h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE(h); if (h->picture_structure == PICT_BOTTOM_FIELD) h->resync_mb_y = h->mb_y = h->mb_y + 1; av_assert1(h->mb_y < h->mb_height); if (h->picture_structure == PICT_FRAME) { h->curr_pic_num = h->frame_num; h->max_pic_num = 1 << h->sps.log2_max_frame_num; } else { h->curr_pic_num = 2 * h->frame_num + 1; h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1); } if (h->nal_unit_type == NAL_IDR_SLICE) get_ue_golomb(&h->gb); /* idr_pic_id */ if (h->sps.poc_type == 0) { h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc_bottom = get_se_golomb(&h->gb); } if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) { h->delta_poc[0] = get_se_golomb(&h->gb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc[1] = get_se_golomb(&h->gb); } ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc); if (h->pps.redundant_pic_cnt_present) h->redundant_pic_count = get_ue_golomb(&h->gb); ret = ff_set_ref_count(h); if (ret < 0) return ret; if (slice_type != AV_PICTURE_TYPE_I && (h0->current_slice == 0 || slice_type != h0->last_slice_type || memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) { ff_h264_fill_default_ref_list(h); } if (h->slice_type_nos != AV_PICTURE_TYPE_I) { ret = ff_h264_decode_ref_pic_list_reordering(h); if (ret < 0) { h->ref_count[1] = h->ref_count[0] = 0; return ret; } } if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) || (h->pps.weighted_bipred_idc == 1 && h->slice_type_nos == AV_PICTURE_TYPE_B)) ff_pred_weight_table(h); else if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, -1); } else { h->use_weight = 0; for (i = 0; i < 2; i++) { h->luma_weight_flag[i] = 0; h->chroma_weight_flag[i] = 0; } } // If frame-mt is enabled, only update mmco tables for the first slice // in a field. Subsequent slices can temporarily clobber h->mmco_index // or h->mmco, which will cause ref list mix-ups and decoding errors // further down the line. This may break decoding if the first slice is // corrupt, thus we only do this if frame-mt is enabled. if (h->nal_ref_idc) { ret = ff_h264_decode_ref_pic_marking(h0, &h->gb, !(h->avctx->active_thread_type & FF_THREAD_FRAME) || h0->current_slice == 0); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return AVERROR_INVALIDDATA; } if (FRAME_MBAFF(h)) { ff_h264_fill_mbaff_ref_list(h); if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, 0); implicit_weight_table(h, 1); } } if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred) ff_h264_direct_dist_scale_factor(h); ff_h264_direct_ref_list_init(h); if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n"); return AVERROR_INVALIDDATA; } h->cabac_init_idc = tmp; } h->last_qscale_diff = 0; tmp = h->pps.init_qp + get_se_golomb(&h->gb); if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) { av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp); return AVERROR_INVALIDDATA; } h->qscale = tmp; h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale); h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale); // FIXME qscale / qp ... stuff if (h->slice_type == AV_PICTURE_TYPE_SP) get_bits1(&h->gb); /* sp_for_switch_flag */ if (h->slice_type == AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI) get_se_golomb(&h->gb); /* slice_qs_delta */ h->deblocking_filter = 1; h->slice_alpha_c0_offset = 52; h->slice_beta_offset = 52; if (h->pps.deblocking_filter_parameters_present) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp); return AVERROR_INVALIDDATA; } h->deblocking_filter = tmp; if (h->deblocking_filter < 2) h->deblocking_filter ^= 1; // 1<->0 if (h->deblocking_filter) { h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1; h->slice_beta_offset += get_se_golomb(&h->gb) << 1; if (h->slice_alpha_c0_offset > 104U || h->slice_beta_offset > 104U) { av_log(h->avctx, AV_LOG_ERROR, "deblocking filter parameters %d %d out of range\n", h->slice_alpha_c0_offset, h->slice_beta_offset); return AVERROR_INVALIDDATA; } } } if (h->avctx->skip_loop_filter >= AVDISCARD_ALL || (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != AV_PICTURE_TYPE_I) || (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == AV_PICTURE_TYPE_B) || (h->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0)) h->deblocking_filter = 0; if (h->deblocking_filter == 1 && h0->max_contexts > 1) { if (h->avctx->flags2 & CODEC_FLAG2_FAST) { /* Cheat slightly for speed: * Do not bother to deblock across slices. */ h->deblocking_filter = 2; } else { h0->max_contexts = 1; if (!h0->single_decode_warning) { av_log(h->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n"); h0->single_decode_warning = 1; } if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "Deblocking switched inside frame.\n"); return 1; } } } h->qp_thresh = 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]) + 6 * (h->sps.bit_depth_luma - 8); h0->last_slice_type = slice_type; memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count)); h->slice_num = ++h0->current_slice; if (h->slice_num) h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y; if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y && h->slice_num >= MAX_SLICES) { //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES); } for (j = 0; j < 2; j++) { int id_list[16]; int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j]; for (i = 0; i < 16; i++) { id_list[i] = 60; if (j < h->list_count && i < h->ref_count[j] && h->ref_list[j][i].f.buf[0]) { int k; AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer; for (k = 0; k < h->short_ref_count; k++) if (h->short_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = k; break; } for (k = 0; k < h->long_ref_count; k++) if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = h->short_ref_count + k; break; } } } ref2frm[0] = ref2frm[1] = -1; for (i = 0; i < 16; i++) ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3); ref2frm[18 + 0] = ref2frm[18 + 1] = -1; for (i = 16; i < 48; i++) ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] + (h->ref_list[j][i].reference & 3); } if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0]; if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0]; h->er.ref_count = h->ref_count[0]; if (h->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(h->avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n", h->slice_num, (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"), first_mb_in_slice, av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "", pps_id, h->frame_num, h->cur_pic_ptr->field_poc[0], h->cur_pic_ptr->field_poc[1], h->ref_count[0], h->ref_count[1], h->qscale, h->deblocking_filter, h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26, h->use_weight, h->use_weight == 1 && h->use_weight_chroma ? "c" : "", h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""); } return 0; }
nan
null
10,811
236248743148359600277595583613499591786
678
avcodec/h264: do not trust last_pic_droppable when marking pictures as done This simplifies the code and fixes a deadlock Fixes Ticket2927 Signed-off-by: Michael Niedermayer <michaelni@gmx.at>
null
qemu
98f93ddd84800f207889491e0b5d851386b459cf
1
static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) { VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); int ret, i, link_down; if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION) return -EINVAL; ret = virtio_load(vdev, f); if (ret) { return ret; } qemu_get_buffer(f, n->mac, ETH_ALEN); n->vqs[0].tx_waiting = qemu_get_be32(f); virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f)); if (version_id >= 3) n->status = qemu_get_be16(f); if (version_id >= 4) { if (version_id < 8) { n->promisc = qemu_get_be32(f); n->allmulti = qemu_get_be32(f); } else { n->promisc = qemu_get_byte(f); n->allmulti = qemu_get_byte(f); } } if (version_id >= 5) { n->mac_table.in_use = qemu_get_be32(f); /* MAC_TABLE_ENTRIES may be different from the saved image */ if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) { qemu_get_buffer(f, n->mac_table.macs, n->mac_table.in_use * ETH_ALEN); } else if (n->mac_table.in_use) { uint8_t *buf = g_malloc0(n->mac_table.in_use); qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN); g_free(buf); n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1; n->mac_table.in_use = 0; } } if (version_id >= 6) qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3); if (version_id >= 7) { if (qemu_get_be32(f) && !peer_has_vnet_hdr(n)) { error_report("virtio-net: saved image requires vnet_hdr=on"); return -1; } } if (version_id >= 9) { n->mac_table.multi_overflow = qemu_get_byte(f); n->mac_table.uni_overflow = qemu_get_byte(f); } if (version_id >= 10) { n->alluni = qemu_get_byte(f); n->nomulti = qemu_get_byte(f); n->nouni = qemu_get_byte(f); n->nobcast = qemu_get_byte(f); } if (version_id >= 11) { if (qemu_get_byte(f) && !peer_has_ufo(n)) { error_report("virtio-net: saved image requires TUN_F_UFO support"); return -1; } } if (n->max_queues > 1) { if (n->max_queues != qemu_get_be16(f)) { error_report("virtio-net: different max_queues "); return -1; } n->curr_queues = qemu_get_be16(f); if (n->curr_queues > n->max_queues) { error_report("virtio-net: curr_queues %x > max_queues %x", n->curr_queues, n->max_queues); return -1; } for (i = 1; i < n->curr_queues; i++) { n->vqs[i].tx_waiting = qemu_get_be32(f); } } if ((1 << VIRTIO_NET_F_CTRL_GUEST_OFFLOADS) & vdev->guest_features) { n->curr_guest_offloads = qemu_get_be64(f); } else { n->curr_guest_offloads = virtio_net_supported_guest_offloads(n); } if (peer_has_vnet_hdr(n)) { virtio_net_apply_guest_offloads(n); } virtio_net_set_queues(n); /* Find the first multicast entry in the saved MAC filter */ for (i = 0; i < n->mac_table.in_use; i++) { if (n->mac_table.macs[i * ETH_ALEN] & 1) { break; } } n->mac_table.first_multi = i; /* nc.link_down can't be migrated, so infer link_down according * to link status bit in n->status */ link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0; for (i = 0; i < n->max_queues; i++) { qemu_get_subqueue(n->nic, i)->link_down = link_down; } return 0; }
nan
null
10,812
244500327533408621550897790014588606679
122
virtio-net: out-of-bounds buffer write on load CVE-2013-4149 QEMU 1.3.0 out-of-bounds buffer write in virtio_net_load()@hw/net/virtio-net.c > } else if (n->mac_table.in_use) { > uint8_t *buf = g_malloc0(n->mac_table.in_use); We are allocating buffer of size n->mac_table.in_use > qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN); and read to the n->mac_table.in_use size buffer n->mac_table.in_use * ETH_ALEN bytes, corrupting memory. If adversary controls state then memory written there is controlled by adversary. Reviewed-by: Michael Roth <mdroth@linux.vnet.ibm.com> Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Signed-off-by: Juan Quintela <quintela@redhat.com>
null
varnish-cache
176f8a075a963ffbfa56f1c460c15f6a1a6af5a7
1
vbf_stp_error(struct worker *wrk, struct busyobj *bo) { ssize_t l, ll, o; double now; uint8_t *ptr; struct vsb *synth_body; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC); AN(bo->fetch_objcore->flags & OC_F_BUSY); assert(bo->director_state == DIR_S_NULL); wrk->stats->fetch_failed++; now = W_TIM_real(wrk); VSLb_ts_busyobj(bo, "Error", now); if (bo->fetch_objcore->stobj->stevedore != NULL) ObjFreeObj(bo->wrk, bo->fetch_objcore); // XXX: reset all beresp flags ? HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod); http_PutResponse(bo->beresp, "HTTP/1.1", 503, "Backend fetch failed"); http_TimeHeader(bo->beresp, "Date: ", now); http_SetHeader(bo->beresp, "Server: Varnish"); bo->fetch_objcore->t_origin = now; if (!VTAILQ_EMPTY(&bo->fetch_objcore->objhead->waitinglist)) { /* * If there is a waitinglist, it means that there is no * grace-able object, so cache the error return for a * short time, so the waiting list can drain, rather than * each objcore on the waiting list sequentially attempt * to fetch from the backend. */ bo->fetch_objcore->ttl = 1; bo->fetch_objcore->grace = 5; bo->fetch_objcore->keep = 5; } else { bo->fetch_objcore->ttl = 0; bo->fetch_objcore->grace = 0; bo->fetch_objcore->keep = 0; } synth_body = VSB_new_auto(); AN(synth_body); VCL_backend_error_method(bo->vcl, wrk, NULL, bo, synth_body); AZ(VSB_finish(synth_body)); if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) { VSB_destroy(&synth_body); return (F_STP_FAIL); } if (wrk->handling == VCL_RET_RETRY) { VSB_destroy(&synth_body); if (bo->retries++ < cache_param->max_retries) return (F_STP_RETRY); VSLb(bo->vsl, SLT_VCL_Error, "Too many retries, failing"); return (F_STP_FAIL); } assert(wrk->handling == VCL_RET_DELIVER); bo->vfc->bo = bo; bo->vfc->wrk = bo->wrk; bo->vfc->oc = bo->fetch_objcore; bo->vfc->http = bo->beresp; bo->vfc->esi_req = bo->bereq; if (vbf_beresp2obj(bo)) { (void)VFP_Error(bo->vfc, "Could not get storage"); VSB_destroy(&synth_body); return (F_STP_FAIL); } ll = VSB_len(synth_body); o = 0; while (ll > 0) { l = ll; if (VFP_GetStorage(bo->vfc, &l, &ptr) != VFP_OK) break; memcpy(ptr, VSB_data(synth_body) + o, l); VFP_Extend(bo->vfc, l); ll -= l; o += l; } AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN, o)); VSB_destroy(&synth_body); HSH_Unbusy(wrk, bo->fetch_objcore); ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED); return (F_STP_DONE); }
nan
null
10,813
38998115844148542092514345486771737777
97
Avoid buffer read overflow on vcl_error and -sfile The file stevedore may return a buffer larger than asked for when requesting storage. Due to lack of check for this condition, the code to copy the synthetic error memory buffer from vcl_error would overrun the buffer. Patch by @shamger Fixes: #2429
null
gpac
90dc7f853d31b0a4e9441cba97feccf36d8b69a4
1
GF_Err gf_isom_oinf_read_entry(void *entry, GF_BitStream *bs) { GF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry; u32 i, j, count; if (!ptr) return GF_BAD_PARAM; ptr->scalability_mask = gf_bs_read_u16(bs); gf_bs_read_int(bs, 2);//reserved count = gf_bs_read_int(bs, 6); for (i = 0; i < count; i++) { LHEVC_ProfileTierLevel *ptl; GF_SAFEALLOC(ptl, LHEVC_ProfileTierLevel); if (!ptl) return GF_OUT_OF_MEM; ptl->general_profile_space = gf_bs_read_int(bs, 2); ptl->general_tier_flag= gf_bs_read_int(bs, 1); ptl->general_profile_idc = gf_bs_read_int(bs, 5); ptl->general_profile_compatibility_flags = gf_bs_read_u32(bs); ptl->general_constraint_indicator_flags = gf_bs_read_long_int(bs, 48); ptl->general_level_idc = gf_bs_read_u8(bs); gf_list_add(ptr->profile_tier_levels, ptl); } count = gf_bs_read_u16(bs); for (i = 0; i < count; i++) { LHEVC_OperatingPoint *op; GF_SAFEALLOC(op, LHEVC_OperatingPoint); if (!op) return GF_OUT_OF_MEM; op->output_layer_set_idx = gf_bs_read_u16(bs); op->max_temporal_id = gf_bs_read_u8(bs); op->layer_count = gf_bs_read_u8(bs); for (j = 0; j < op->layer_count; j++) { op->layers_info[j].ptl_idx = gf_bs_read_u8(bs); op->layers_info[j].layer_id = gf_bs_read_int(bs, 6); op->layers_info[j].is_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; op->layers_info[j].is_alternate_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; } op->minPicWidth = gf_bs_read_u16(bs); op->minPicHeight = gf_bs_read_u16(bs); op->maxPicWidth = gf_bs_read_u16(bs); op->maxPicHeight = gf_bs_read_u16(bs); op->maxChromaFormat = gf_bs_read_int(bs, 2); op->maxBitDepth = gf_bs_read_int(bs, 3) + 8; gf_bs_read_int(bs, 1);//reserved op->frame_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; op->bit_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; if (op->frame_rate_info_flag) { op->avgFrameRate = gf_bs_read_u16(bs); gf_bs_read_int(bs, 6); //reserved op->constantFrameRate = gf_bs_read_int(bs, 2); } if (op->bit_rate_info_flag) { op->maxBitRate = gf_bs_read_u32(bs); op->avgBitRate = gf_bs_read_u32(bs); } gf_list_add(ptr->operating_points, op); } count = gf_bs_read_u8(bs); for (i = 0; i < count; i++) { LHEVC_DependentLayer *dep; GF_SAFEALLOC(dep, LHEVC_DependentLayer); if (!dep) return GF_OUT_OF_MEM; dep->dependent_layerID = gf_bs_read_u8(bs); dep->num_layers_dependent_on = gf_bs_read_u8(bs); for (j = 0; j < dep->num_layers_dependent_on; j++) dep->dependent_on_layerID[j] = gf_bs_read_u8(bs); for (j = 0; j < 16; j++) { if (ptr->scalability_mask & (1 << j)) dep->dimension_identifier[j] = gf_bs_read_u8(bs); } gf_list_add(ptr->dependency_layers, dep); } return GF_OK; }
nan
null
10,814
45493324744899782171549462183591406587
73
fix some exploitable overflows (#994, #997)
null
gpac
90dc7f853d31b0a4e9441cba97feccf36d8b69a4
1
s32 gf_media_avc_read_sps(const char *sps_data, u32 sps_size, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos) { AVC_SPS *sps; u32 ChromaArrayType = 0; s32 mb_width, mb_height, sps_id = -1; u32 profile_idc, level_idc, pcomp, i, chroma_format_idc, cl=0, cr=0, ct=0, cb=0, luma_bd, chroma_bd; u8 separate_colour_plane_flag = 0; GF_BitStream *bs; char *sps_data_without_emulation_bytes = NULL; u32 sps_data_without_emulation_bytes_size = 0; /*SPS still contains emulation bytes*/ sps_data_without_emulation_bytes = gf_malloc(sps_size*sizeof(char)); sps_data_without_emulation_bytes_size = avc_remove_emulation_bytes(sps_data, sps_data_without_emulation_bytes, sps_size); bs = gf_bs_new(sps_data_without_emulation_bytes, sps_data_without_emulation_bytes_size, GF_BITSTREAM_READ); if (!bs) { sps_id = -1; goto exit; } if (vui_flag_pos) *vui_flag_pos = 0; /*nal hdr*/ gf_bs_read_int(bs, 8); profile_idc = gf_bs_read_int(bs, 8); pcomp = gf_bs_read_int(bs, 8); /*sanity checks*/ if (pcomp & 0x3) goto exit; level_idc = gf_bs_read_int(bs, 8); /*SubsetSps is used to be sure that AVC SPS are not going to be scratched by subset SPS. According to the SVC standard, subset SPS can have the same sps_id than its base layer, but it does not refer to the same SPS. */ sps_id = bs_get_ue(bs) + GF_SVC_SSPS_ID_SHIFT * subseq_sps; if (sps_id >=32) { sps_id = -1; goto exit; } if (sps_id < 0) { sps_id = -1; goto exit; } luma_bd = chroma_bd = 0; chroma_format_idc = ChromaArrayType = 1; sps = &avc->sps[sps_id]; sps->state |= subseq_sps ? AVC_SUBSPS_PARSED : AVC_SPS_PARSED; /*High Profile and SVC*/ switch (profile_idc) { case 100: case 110: case 122: case 244: case 44: /*sanity checks: note1 from 7.4.2.1.1 of iso/iec 14496-10-N11084*/ if (pcomp & 0xE0) goto exit; case 83: case 86: case 118: case 128: chroma_format_idc = bs_get_ue(bs); ChromaArrayType = chroma_format_idc; if (chroma_format_idc == 3) { separate_colour_plane_flag = gf_bs_read_int(bs, 1); /* Depending on the value of separate_colour_plane_flag, the value of the variable ChromaArrayType is assigned as follows. \96 If separate_colour_plane_flag is equal to 0, ChromaArrayType is set equal to chroma_format_idc. \96 Otherwise (separate_colour_plane_flag is equal to 1), ChromaArrayType is set equal to 0. */ if (separate_colour_plane_flag) ChromaArrayType = 0; } luma_bd = bs_get_ue(bs); chroma_bd = bs_get_ue(bs); /*qpprime_y_zero_transform_bypass_flag = */ gf_bs_read_int(bs, 1); /*seq_scaling_matrix_present_flag*/ if (gf_bs_read_int(bs, 1)) { u32 k; for (k=0; k<8; k++) { if (gf_bs_read_int(bs, 1)) { u32 z, last = 8, next = 8; u32 sl = k<6 ? 16 : 64; for (z=0; z<sl; z++) { if (next) { s32 delta = bs_get_se(bs); next = (last + delta + 256) % 256; } last = next ? next : last; } } } } break; } sps->profile_idc = profile_idc; sps->level_idc = level_idc; sps->prof_compat = pcomp; sps->log2_max_frame_num = bs_get_ue(bs) + 4; sps->poc_type = bs_get_ue(bs); sps->chroma_format = chroma_format_idc; sps->luma_bit_depth_m8 = luma_bd; sps->chroma_bit_depth_m8 = chroma_bd; if (sps->poc_type == 0) { sps->log2_max_poc_lsb = bs_get_ue(bs) + 4; } else if(sps->poc_type == 1) { sps->delta_pic_order_always_zero_flag = gf_bs_read_int(bs, 1); sps->offset_for_non_ref_pic = bs_get_se(bs); sps->offset_for_top_to_bottom_field = bs_get_se(bs); sps->poc_cycle_length = bs_get_ue(bs); for(i=0; i<sps->poc_cycle_length; i++) sps->offset_for_ref_frame[i] = bs_get_se(bs); } if (sps->poc_type > 2) { sps_id = -1; goto exit; } sps->max_num_ref_frames = bs_get_ue(bs); sps->gaps_in_frame_num_value_allowed_flag = gf_bs_read_int(bs, 1); mb_width = bs_get_ue(bs) + 1; mb_height= bs_get_ue(bs) + 1; sps->frame_mbs_only_flag = gf_bs_read_int(bs, 1); sps->width = mb_width * 16; sps->height = (2-sps->frame_mbs_only_flag) * mb_height * 16; if (!sps->frame_mbs_only_flag) sps->mb_adaptive_frame_field_flag = gf_bs_read_int(bs, 1); gf_bs_read_int(bs, 1); /*direct_8x8_inference_flag*/ if (gf_bs_read_int(bs, 1)) { /*crop*/ int CropUnitX, CropUnitY, SubWidthC = -1, SubHeightC = -1; if (chroma_format_idc == 1) { SubWidthC = 2, SubHeightC = 2; } else if (chroma_format_idc == 2) { SubWidthC = 2, SubHeightC = 1; } else if ((chroma_format_idc == 3) && (separate_colour_plane_flag == 0)) { SubWidthC = 1, SubHeightC = 1; } if (ChromaArrayType == 0) { assert(SubWidthC==-1); CropUnitX = 1; CropUnitY = 2-sps->frame_mbs_only_flag; } else { CropUnitX = SubWidthC; CropUnitY = SubHeightC * (2-sps->frame_mbs_only_flag); } cl = bs_get_ue(bs); /*crop_left*/ cr = bs_get_ue(bs); /*crop_right*/ ct = bs_get_ue(bs); /*crop_top*/ cb = bs_get_ue(bs); /*crop_bottom*/ sps->width -= CropUnitX * (cl + cr); sps->height -= CropUnitY * (ct + cb); cl *= CropUnitX; cr *= CropUnitX; ct *= CropUnitY; cb *= CropUnitY; } sps->crop.left = cl; sps->crop.right = cr; sps->crop.top = ct; sps->crop.bottom = cb; if (vui_flag_pos) { *vui_flag_pos = (u32) gf_bs_get_bit_offset(bs); } /*vui_parameters_present_flag*/ sps->vui_parameters_present_flag = gf_bs_read_int(bs, 1); if (sps->vui_parameters_present_flag) { sps->vui.aspect_ratio_info_present_flag = gf_bs_read_int(bs, 1); if (sps->vui.aspect_ratio_info_present_flag) { s32 aspect_ratio_idc = gf_bs_read_int(bs, 8); if (aspect_ratio_idc == 255) { sps->vui.par_num = gf_bs_read_int(bs, 16); /*AR num*/ sps->vui.par_den = gf_bs_read_int(bs, 16); /*AR den*/ } else if (aspect_ratio_idc<14) { sps->vui.par_num = avc_sar[aspect_ratio_idc].w; sps->vui.par_den = avc_sar[aspect_ratio_idc].h; } } sps->vui.overscan_info_present_flag = gf_bs_read_int(bs, 1); if(sps->vui.overscan_info_present_flag) gf_bs_read_int(bs, 1); /* overscan_appropriate_flag */ /* default values */ sps->vui.video_format = 5; sps->vui.colour_primaries = 2; sps->vui.transfer_characteristics = 2; sps->vui.matrix_coefficients = 2; /* now read values if possible */ sps->vui.video_signal_type_present_flag = gf_bs_read_int(bs, 1); if (sps->vui.video_signal_type_present_flag) { sps->vui.video_format = gf_bs_read_int(bs, 3); sps->vui.video_full_range_flag = gf_bs_read_int(bs, 1); sps->vui.colour_description_present_flag = gf_bs_read_int(bs, 1); if (sps->vui.colour_description_present_flag) { sps->vui.colour_primaries = gf_bs_read_int(bs, 8); sps->vui.transfer_characteristics = gf_bs_read_int(bs, 8); sps->vui.matrix_coefficients = gf_bs_read_int(bs, 8); } } if (gf_bs_read_int(bs, 1)) { /* chroma_location_info_present_flag */ bs_get_ue(bs); /* chroma_sample_location_type_top_field */ bs_get_ue(bs); /* chroma_sample_location_type_bottom_field */ } sps->vui.timing_info_present_flag = gf_bs_read_int(bs, 1); if (sps->vui.timing_info_present_flag) { sps->vui.num_units_in_tick = gf_bs_read_int(bs, 32); sps->vui.time_scale = gf_bs_read_int(bs, 32); sps->vui.fixed_frame_rate_flag = gf_bs_read_int(bs, 1); } sps->vui.nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1); if (sps->vui.nal_hrd_parameters_present_flag) avc_parse_hrd_parameters(bs, &sps->vui.hrd); sps->vui.vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1); if (sps->vui.vcl_hrd_parameters_present_flag) avc_parse_hrd_parameters(bs, &sps->vui.hrd); if (sps->vui.nal_hrd_parameters_present_flag || sps->vui.vcl_hrd_parameters_present_flag) sps->vui.low_delay_hrd_flag = gf_bs_read_int(bs, 1); sps->vui.pic_struct_present_flag = gf_bs_read_int(bs, 1); } /*end of seq_parameter_set_data*/ if (subseq_sps) { if ((profile_idc==83) || (profile_idc==86)) { u8 extended_spatial_scalability_idc; /*parsing seq_parameter_set_svc_extension*/ /*inter_layer_deblocking_filter_control_present_flag=*/ gf_bs_read_int(bs, 1); extended_spatial_scalability_idc = gf_bs_read_int(bs, 2); if (ChromaArrayType == 1 || ChromaArrayType == 2) { /*chroma_phase_x_plus1_flag*/ gf_bs_read_int(bs, 1); } if( ChromaArrayType == 1 ) { /*chroma_phase_y_plus1*/ gf_bs_read_int(bs, 2); } if (extended_spatial_scalability_idc == 1) { if( ChromaArrayType > 0 ) { /*seq_ref_layer_chroma_phase_x_plus1_flag*/gf_bs_read_int(bs, 1); /*seq_ref_layer_chroma_phase_y_plus1*/gf_bs_read_int(bs, 2); } /*seq_scaled_ref_layer_left_offset*/ bs_get_se(bs); /*seq_scaled_ref_layer_top_offset*/bs_get_se(bs); /*seq_scaled_ref_layer_right_offset*/bs_get_se(bs); /*seq_scaled_ref_layer_bottom_offset*/bs_get_se(bs); } if (/*seq_tcoeff_level_prediction_flag*/gf_bs_read_int(bs, 1)) { /*adaptive_tcoeff_level_prediction_flag*/ gf_bs_read_int(bs, 1); } /*slice_header_restriction_flag*/gf_bs_read_int(bs, 1); /*svc_vui_parameters_present*/ if (gf_bs_read_int(bs, 1)) { u32 i, vui_ext_num_entries_minus1; vui_ext_num_entries_minus1 = bs_get_ue(bs); for (i=0; i <= vui_ext_num_entries_minus1; i++) { u8 vui_ext_nal_hrd_parameters_present_flag, vui_ext_vcl_hrd_parameters_present_flag, vui_ext_timing_info_present_flag; /*u8 vui_ext_dependency_id =*/ gf_bs_read_int(bs, 3); /*u8 vui_ext_quality_id =*/ gf_bs_read_int(bs, 4); /*u8 vui_ext_temporal_id =*/ gf_bs_read_int(bs, 3); vui_ext_timing_info_present_flag = gf_bs_read_int(bs, 1); if (vui_ext_timing_info_present_flag) { /*u32 vui_ext_num_units_in_tick = */gf_bs_read_int(bs, 32); /*u32 vui_ext_time_scale = */gf_bs_read_int(bs, 32); /*u8 vui_ext_fixed_frame_rate_flag = */gf_bs_read_int(bs, 1); } vui_ext_nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1); if (vui_ext_nal_hrd_parameters_present_flag) { //hrd_parameters( ) } vui_ext_vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1); if (vui_ext_vcl_hrd_parameters_present_flag) { //hrd_parameters( ) } if ( vui_ext_nal_hrd_parameters_present_flag || vui_ext_vcl_hrd_parameters_present_flag) { /*vui_ext_low_delay_hrd_flag*/gf_bs_read_int(bs, 1); } /*vui_ext_pic_struct_present_flag*/gf_bs_read_int(bs, 1); } } } else if ((profile_idc==118) || (profile_idc==128)) { GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] MVC not supported - skipping parsing end of Subset SPS\n")); goto exit; } if (gf_bs_read_int(bs, 1)) { GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] skipping parsing end of Subset SPS (additional_extension2)\n")); goto exit; } } exit: gf_bs_del(bs); gf_free(sps_data_without_emulation_bytes); return sps_id; }
nan
null
10,815
118493925447285944810226867626948965178
311
fix some exploitable overflows (#994, #997)
null
FFmpeg
2960576378d17d71cc8dccc926352ce568b5eec1
1
static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y, const uint8_t *src, int src_size) { int width, height; int hdr, zsize, npal, tidx = -1, ret; int i, j; const uint8_t *src_end = src + src_size; uint8_t pal[768], transp[3]; uLongf dlen = (c->tile_width + 1) * c->tile_height; int sub_type; int nblocks, cblocks, bstride; int bits, bitbuf, coded; uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 + tile_y * c->tile_height * c->framebuf_stride; if (src_size < 2) return AVERROR_INVALIDDATA; width = FFMIN(c->width - tile_x * c->tile_width, c->tile_width); height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height); hdr = *src++; sub_type = hdr >> 5; if (sub_type == 0) { int j; memcpy(transp, src, 3); src += 3; for (j = 0; j < height; j++, dst += c->framebuf_stride) for (i = 0; i < width; i++) memcpy(dst + i * 3, transp, 3); return 0; } else if (sub_type == 1) { return jpg_decode_data(&c->jc, width, height, src, src_end - src, dst, c->framebuf_stride, NULL, 0, 0, 0); } if (sub_type != 2) { memcpy(transp, src, 3); src += 3; } npal = *src++ + 1; memcpy(pal, src, npal * 3); src += npal * 3; if (sub_type != 2) { for (i = 0; i < npal; i++) { if (!memcmp(pal + i * 3, transp, 3)) { tidx = i; break; } } } if (src_end - src < 2) return 0; zsize = (src[0] << 8) | src[1]; src += 2; if (src_end - src < zsize) return AVERROR_INVALIDDATA; ret = uncompress(c->kempf_buf, &dlen, src, zsize); if (ret) return AVERROR_INVALIDDATA; src += zsize; if (sub_type == 2) { kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride, NULL, 0, width, height, pal, npal, tidx); return 0; } nblocks = *src++ + 1; cblocks = 0; bstride = FFALIGN(width, 16) >> 4; // blocks are coded LSB and we need normal bitreader for JPEG data bits = 0; for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) { for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) { if (!bits) { bitbuf = *src++; bits = 8; } coded = bitbuf & 1; bits--; bitbuf >>= 1; cblocks += coded; if (cblocks > nblocks) return AVERROR_INVALIDDATA; c->kempf_flags[j + i * bstride] = coded; } } memset(c->jpeg_tile, 0, c->tile_stride * height); jpg_decode_data(&c->jc, width, height, src, src_end - src, c->jpeg_tile, c->tile_stride, c->kempf_flags, bstride, nblocks, 0); kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride, c->jpeg_tile, c->tile_stride, width, height, pal, npal, tidx); return 0; }
nan
null
10,816
157199865468937762208047265959964862177
101
avcodec/g2meet: fix src pointer checks in kempf_decode_tile() Fixes Ticket2842 Signed-off-by: Michael Niedermayer <michaelni@gmx.at>
null
radare2
bd276ef2fd8ac3401e65be7c126a43175ccfbcd7
1
int wasm_dis(WasmOp *op, const unsigned char *buf, int buf_len) { op->len = 1; op->op = buf[0]; if (op->op > 0xbf) { return 1; } // add support for extension opcodes (SIMD + atomics) WasmOpDef *opdef = &opcodes[op->op]; switch (op->op) { case WASM_OP_TRAP: case WASM_OP_NOP: case WASM_OP_ELSE: case WASM_OP_RETURN: case WASM_OP_DROP: case WASM_OP_SELECT: case WASM_OP_I32EQZ: case WASM_OP_I32EQ: case WASM_OP_I32NE: case WASM_OP_I32LTS: case WASM_OP_I32LTU: case WASM_OP_I32GTS: case WASM_OP_I32GTU: case WASM_OP_I32LES: case WASM_OP_I32LEU: case WASM_OP_I32GES: case WASM_OP_I32GEU: case WASM_OP_I64EQZ: case WASM_OP_I64EQ: case WASM_OP_I64NE: case WASM_OP_I64LTS: case WASM_OP_I64LTU: case WASM_OP_I64GTS: case WASM_OP_I64GTU: case WASM_OP_I64LES: case WASM_OP_I64LEU: case WASM_OP_I64GES: case WASM_OP_I64GEU: case WASM_OP_F32EQ: case WASM_OP_F32NE: case WASM_OP_F32LT: case WASM_OP_F32GT: case WASM_OP_F32LE: case WASM_OP_F32GE: case WASM_OP_F64EQ: case WASM_OP_F64NE: case WASM_OP_F64LT: case WASM_OP_F64GT: case WASM_OP_F64LE: case WASM_OP_F64GE: case WASM_OP_I32CLZ: case WASM_OP_I32CTZ: case WASM_OP_I32POPCNT: case WASM_OP_I32ADD: case WASM_OP_I32SUB: case WASM_OP_I32MUL: case WASM_OP_I32DIVS: case WASM_OP_I32DIVU: case WASM_OP_I32REMS: case WASM_OP_I32REMU: case WASM_OP_I32AND: case WASM_OP_I32OR: case WASM_OP_I32XOR: case WASM_OP_I32SHL: case WASM_OP_I32SHRS: case WASM_OP_I32SHRU: case WASM_OP_I32ROTL: case WASM_OP_I32ROTR: case WASM_OP_I64CLZ: case WASM_OP_I64CTZ: case WASM_OP_I64POPCNT: case WASM_OP_I64ADD: case WASM_OP_I64SUB: case WASM_OP_I64MUL: case WASM_OP_I64DIVS: case WASM_OP_I64DIVU: case WASM_OP_I64REMS: case WASM_OP_I64REMU: case WASM_OP_I64AND: case WASM_OP_I64OR: case WASM_OP_I64XOR: case WASM_OP_I64SHL: case WASM_OP_I64SHRS: case WASM_OP_I64SHRU: case WASM_OP_I64ROTL: case WASM_OP_I64ROTR: case WASM_OP_F32ABS: case WASM_OP_F32NEG: case WASM_OP_F32CEIL: case WASM_OP_F32FLOOR: case WASM_OP_F32TRUNC: case WASM_OP_F32NEAREST: case WASM_OP_F32SQRT: case WASM_OP_F32ADD: case WASM_OP_F32SUB: case WASM_OP_F32MUL: case WASM_OP_F32DIV: case WASM_OP_F32MIN: case WASM_OP_F32MAX: case WASM_OP_F32COPYSIGN: case WASM_OP_F64ABS: case WASM_OP_F64NEG: case WASM_OP_F64CEIL: case WASM_OP_F64FLOOR: case WASM_OP_F64TRUNC: case WASM_OP_F64NEAREST: case WASM_OP_F64SQRT: case WASM_OP_F64ADD: case WASM_OP_F64SUB: case WASM_OP_F64MUL: case WASM_OP_F64DIV: case WASM_OP_F64MIN: case WASM_OP_F64MAX: case WASM_OP_F64COPYSIGN: case WASM_OP_I32WRAPI64: case WASM_OP_I32TRUNCSF32: case WASM_OP_I32TRUNCUF32: case WASM_OP_I32TRUNCSF64: case WASM_OP_I32TRUNCUF64: case WASM_OP_I64EXTENDSI32: case WASM_OP_I64EXTENDUI32: case WASM_OP_I64TRUNCSF32: case WASM_OP_I64TRUNCUF32: case WASM_OP_I64TRUNCSF64: case WASM_OP_I64TRUNCUF64: case WASM_OP_F32CONVERTSI32: case WASM_OP_F32CONVERTUI32: case WASM_OP_F32CONVERTSI64: case WASM_OP_F32CONVERTUI64: case WASM_OP_F32DEMOTEF64: case WASM_OP_F64CONVERTSI32: case WASM_OP_F64CONVERTUI32: case WASM_OP_F64CONVERTSI64: case WASM_OP_F64CONVERTUI64: case WASM_OP_F64PROMOTEF32: case WASM_OP_I32REINTERPRETF32: case WASM_OP_I64REINTERPRETF64: case WASM_OP_F32REINTERPRETI32: case WASM_OP_F64REINTERPRETI64: case WASM_OP_END: { snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt); } break; case WASM_OP_BLOCK: case WASM_OP_LOOP: case WASM_OP_IF: { st32 val = 0; size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; switch (0x80 - val) { case R_BIN_WASM_VALUETYPE_EMPTY: snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt); break; case R_BIN_WASM_VALUETYPE_i32: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i32)", opdef->txt); break; case R_BIN_WASM_VALUETYPE_i64: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i64)", opdef->txt); break; case R_BIN_WASM_VALUETYPE_f32: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f32)", opdef->txt); break; case R_BIN_WASM_VALUETYPE_f64: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f64)", opdef->txt); break; default: snprintf (op->txt, R_ASM_BUFSIZE, "%s (result ?)", opdef->txt); break; } op->len += n; } break; case WASM_OP_BR: case WASM_OP_BRIF: case WASM_OP_CALL: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val); op->len += n; } break; case WASM_OP_BRTABLE: { ut32 count = 0, *table = NULL, def = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &count); if (!(n > 0 && n < buf_len)) { goto err; } if (!(table = calloc (count, sizeof (ut32)))) { goto err; } int i = 0; op->len += n; for (i = 0; i < count; i++) { n = read_u32_leb128 (buf + op->len, buf + buf_len, &table[i]); if (!(op->len + n <= buf_len)) { goto beach; } op->len += n; } n = read_u32_leb128 (buf + op->len, buf + buf_len, &def); if (!(n > 0 && n + op->len < buf_len)) { goto beach; } op->len += n; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d ", opdef->txt, count); for (i = 0; i < count && strlen (op->txt) + 10 < R_ASM_BUFSIZE; i++) { int optxtlen = strlen (op->txt); snprintf (op->txt + optxtlen, R_ASM_BUFSIZE - optxtlen, "%d ", table[i]); } snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, "%d", def); free (table); break; beach: free (table); goto err; } break; case WASM_OP_CALLINDIRECT: { ut32 val = 0, reserved = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; op->len += n; n = read_u32_leb128 (buf + op->len, buf + buf_len, &reserved); if (!(n == 1 && op->len + n <= buf_len)) goto err; reserved &= 0x1; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, val, reserved); op->len += n; } break; case WASM_OP_GETLOCAL: case WASM_OP_SETLOCAL: case WASM_OP_TEELOCAL: case WASM_OP_GETGLOBAL: case WASM_OP_SETGLOBAL: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val); op->len += n; } break; case WASM_OP_I32LOAD: case WASM_OP_I64LOAD: case WASM_OP_F32LOAD: case WASM_OP_F64LOAD: case WASM_OP_I32LOAD8S: case WASM_OP_I32LOAD8U: case WASM_OP_I32LOAD16S: case WASM_OP_I32LOAD16U: case WASM_OP_I64LOAD8S: case WASM_OP_I64LOAD8U: case WASM_OP_I64LOAD16S: case WASM_OP_I64LOAD16U: case WASM_OP_I64LOAD32S: case WASM_OP_I64LOAD32U: case WASM_OP_I32STORE: case WASM_OP_I64STORE: case WASM_OP_F32STORE: case WASM_OP_F64STORE: case WASM_OP_I32STORE8: case WASM_OP_I32STORE16: case WASM_OP_I64STORE8: case WASM_OP_I64STORE16: case WASM_OP_I64STORE32: { ut32 flag = 0, offset = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &flag); if (!(n > 0 && n < buf_len)) goto err; op->len += n; n = read_u32_leb128 (buf + op->len, buf + buf_len, &offset); if (!(n > 0 && op->len + n <= buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, flag, offset); op->len += n; } break; case WASM_OP_CURRENTMEMORY: case WASM_OP_GROWMEMORY: { ut32 reserved = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &reserved); if (!(n == 1 && n < buf_len)) goto err; reserved &= 0x1; snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, reserved); op->len += n; } break; case WASM_OP_I32CONST: { st32 val = 0; size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT32d, opdef->txt, val); op->len += n; } break; case WASM_OP_I64CONST: { st64 val = 0; size_t n = read_i64_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT64d, opdef->txt, val); op->len += n; } break; case WASM_OP_F32CONST: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; long double d = (long double)val; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d); op->len += n; } break; case WASM_OP_F64CONST: { ut64 val = 0; size_t n = read_u64_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; long double d = (long double)val; snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d); op->len += n; } break; default: goto err; } return op->len; err: op->len = 1; snprintf (op->txt, R_ASM_BUFSIZE, "invalid"); return op->len; }
nan
null
10,817
6673601905180169643014511822450504240
342
Fix #9969 - Stack overflow in wasm disassembler
null
virglrenderer
747a293ff6055203e529f083896b823e22523fe7
1
void vrend_renderer_context_create_internal(uint32_t handle, uint32_t nlen, const char *debug_name) { struct vrend_decode_ctx *dctx; if (handle >= VREND_MAX_CTX) return; dctx = malloc(sizeof(struct vrend_decode_ctx)); if (!dctx) return; dctx->grctx = vrend_create_context(handle, nlen, debug_name); if (!dctx->grctx) { free(dctx); return; } dctx->ds = &dctx->ids; dec_ctx[handle] = dctx; }
nan
null
10,818
314270549268056028852966452900609925559
22
vrend: fix a leak in context create internal Create a context more than once causes memory leak issue. Juest return if the context exists. Signed-off-by: Li Qiang <liq3ea@gmail.com> Signed-off-by: Dave Airlie <airlied@redhat.com>
null
poppler
58e04a08afee39370283c494ee2e4e392fd3b684
1
void JBIG2Stream::readSegments() { Guint segNum, segFlags, segType, page, segLength; Guint refFlags, nRefSegs; Guint *refSegs; Goffset segDataPos; int c1, c2, c3; Guint i; while (readULong(&segNum)) { // segment header flags if (!readUByte(&segFlags)) { goto eofError1; } segType = segFlags & 0x3f; // referred-to segment count and retention flags if (!readUByte(&refFlags)) { goto eofError1; } nRefSegs = refFlags >> 5; if (nRefSegs == 7) { if ((c1 = curStr->getChar()) == EOF || (c2 = curStr->getChar()) == EOF || (c3 = curStr->getChar()) == EOF) { goto eofError1; } refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3; nRefSegs = refFlags & 0x1fffffff; for (i = 0; i < (nRefSegs + 9) >> 3; ++i) { if ((c1 = curStr->getChar()) == EOF) { goto eofError1; } } } // referred-to segment numbers refSegs = (Guint *)gmallocn(nRefSegs, sizeof(Guint)); if (segNum <= 256) { for (i = 0; i < nRefSegs; ++i) { if (!readUByte(&refSegs[i])) { goto eofError2; } } } else if (segNum <= 65536) { for (i = 0; i < nRefSegs; ++i) { if (!readUWord(&refSegs[i])) { goto eofError2; } } } else { for (i = 0; i < nRefSegs; ++i) { if (!readULong(&refSegs[i])) { goto eofError2; } } } // segment page association if (segFlags & 0x40) { if (!readULong(&page)) { goto eofError2; } } else { if (!readUByte(&page)) { goto eofError2; } } // segment data length if (!readULong(&segLength)) { goto eofError2; } // keep track of the start of the segment data segDataPos = curStr->getPos(); // check for missing page information segment if (!pageBitmap && ((segType >= 4 && segType <= 7) || (segType >= 20 && segType <= 43))) { error(errSyntaxError, curStr->getPos(), "First JBIG2 segment associated with a page must be a page information segment"); goto syntaxError; } // read the segment data switch (segType) { case 0: if (!readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs)) { goto syntaxError; } break; case 4: readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs); break; case 6: readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs); break; case 7: readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs); break; case 16: readPatternDictSeg(segNum, segLength); break; case 20: readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs); break; case 22: readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs); break; case 23: readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs); break; case 36: readGenericRegionSeg(segNum, gFalse, gFalse, segLength); break; case 38: readGenericRegionSeg(segNum, gTrue, gFalse, segLength); break; case 39: readGenericRegionSeg(segNum, gTrue, gTrue, segLength); break; case 40: readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs); break; case 42: readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs); break; case 43: readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs); break; case 48: readPageInfoSeg(segLength); break; case 50: readEndOfStripeSeg(segLength); break; case 52: readProfilesSeg(segLength); break; case 53: readCodeTableSeg(segNum, segLength); break; case 62: readExtensionSeg(segLength); break; default: error(errSyntaxError, curStr->getPos(), "Unknown segment type in JBIG2 stream"); for (i = 0; i < segLength; ++i) { if ((c1 = curStr->getChar()) == EOF) { goto eofError2; } } break; } // Make sure the segment handler read all of the bytes in the // segment data, unless this segment is marked as having an // unknown length (section 7.2.7 of the JBIG2 Final Committee Draft) if (segLength != 0xffffffff) { Goffset segExtraBytes = segDataPos + segLength - curStr->getPos(); if (segExtraBytes > 0) { // If we didn't read all of the bytes in the segment data, // indicate an error, and throw away the rest of the data. // v.3.1.01.13 of the LuraTech PDF Compressor Server will // sometimes generate an extraneous NULL byte at the end of // arithmetic-coded symbol dictionary segments when numNewSyms // == 0. Segments like this often occur for blank pages. error(errSyntaxError, curStr->getPos(), "{0:d} extraneous byte{1:s} after segment", segExtraBytes, (segExtraBytes > 1) ? "s" : ""); // Burn through the remaining bytes -- inefficient, but // hopefully we're not doing this much int trash; for (Goffset i = segExtraBytes; i > 0; i--) { readByte(&trash); } } else if (segExtraBytes < 0) { // If we read more bytes than we should have, according to the // segment length field, note an error. error(errSyntaxError, curStr->getPos(), "Previous segment handler read too many bytes"); } } gfree(refSegs); } return; syntaxError: gfree(refSegs); return; eofError2: gfree(refSegs); eofError1: error(errSyntaxError, curStr->getPos(), "Unexpected EOF in JBIG2 stream"); }
nan
null
10,819
234137405656432353954992801617425192184
214
segExtraBytes is a goffset not an int so use lld Fixes KDE bug #328511
null
nmap
350bbe0597d37ad67abe5fef8fba984707b4e9ad
1
static int do_session_handshake (lua_State *L, int status, lua_KContext ctx) { int rc; struct ssh_userdata *sshu = NULL; assert(lua_gettop(L) == 4); sshu = (struct ssh_userdata *) nseU_checkudata(L, 3, SSH2_UDATA, "ssh2"); while ((rc = libssh2_session_handshake(sshu->session, sshu->sp[0])) == LIBSSH2_ERROR_EAGAIN) { luaL_getmetafield(L, 3, "filter"); lua_pushvalue(L, 3); assert(lua_status(L) == LUA_OK); lua_callk(L, 1, 0, 0, do_session_handshake); } if (rc) { libssh2_session_free(sshu->session); return luaL_error(L, "Unable to complete libssh2 handshake."); } // lua_pushvalue(L, 3); lua_settop(L, 3); return 1; }
nan
null
10,820
158553276448407058877806570620623389090
25
Avoid a crash (double-free) when SSH connection fails
null
linux
5a0fdfada3a2aa50d7b947a2e958bf00cbe0d830
1
static inline void set_pte_at(struct mm_struct *mm, unsigned long addr, pte_t *ptep, pte_t pte) { if (pte_valid_ng(pte)) { if (!pte_special(pte) && pte_exec(pte)) __sync_icache_dcache(pte, addr); if (pte_dirty(pte) && pte_write(pte)) pte_val(pte) &= ~PTE_RDONLY; else pte_val(pte) |= PTE_RDONLY; } set_pte(ptep, pte); }
nan
null
10,822
72720086549577505075898506501332737884
14
Revert "arm64: Introduce execute-only page access permissions" This reverts commit bc07c2c6e9ed125d362af0214b6313dca180cb08. While the aim is increased security for --x memory maps, it does not protect against kernel level reads. Until SECCOMP is implemented for arm64, revert this patch to avoid giving a false idea of execute-only mappings. Signed-off-by: Catalin Marinas <catalin.marinas@arm.com>
null
linux
b4789b8e6be3151a955ade74872822f30e8cd914
1
static int aac_send_raw_srb(struct aac_dev* dev, void __user * arg) { struct fib* srbfib; int status; struct aac_srb *srbcmd = NULL; struct user_aac_srb *user_srbcmd = NULL; struct user_aac_srb __user *user_srb = arg; struct aac_srb_reply __user *user_reply; struct aac_srb_reply* reply; u32 fibsize = 0; u32 flags = 0; s32 rcode = 0; u32 data_dir; void __user *sg_user[32]; void *sg_list[32]; u32 sg_indx = 0; u32 byte_count = 0; u32 actual_fibsize64, actual_fibsize = 0; int i; if (dev->in_reset) { dprintk((KERN_DEBUG"aacraid: send raw srb -EBUSY\n")); return -EBUSY; } if (!capable(CAP_SYS_ADMIN)){ dprintk((KERN_DEBUG"aacraid: No permission to send raw srb\n")); return -EPERM; } /* * Allocate and initialize a Fib then setup a SRB command */ if (!(srbfib = aac_fib_alloc(dev))) { return -ENOMEM; } aac_fib_init(srbfib); /* raw_srb FIB is not FastResponseCapable */ srbfib->hw_fib_va->header.XferState &= ~cpu_to_le32(FastResponseCapable); srbcmd = (struct aac_srb*) fib_data(srbfib); memset(sg_list, 0, sizeof(sg_list)); /* cleanup may take issue */ if(copy_from_user(&fibsize, &user_srb->count,sizeof(u32))){ dprintk((KERN_DEBUG"aacraid: Could not copy data size from user\n")); rcode = -EFAULT; goto cleanup; } if (fibsize > (dev->max_fib_size - sizeof(struct aac_fibhdr))) { rcode = -EINVAL; goto cleanup; } user_srbcmd = kmalloc(fibsize, GFP_KERNEL); if (!user_srbcmd) { dprintk((KERN_DEBUG"aacraid: Could not make a copy of the srb\n")); rcode = -ENOMEM; goto cleanup; } if(copy_from_user(user_srbcmd, user_srb,fibsize)){ dprintk((KERN_DEBUG"aacraid: Could not copy srb from user\n")); rcode = -EFAULT; goto cleanup; } user_reply = arg+fibsize; flags = user_srbcmd->flags; /* from user in cpu order */ // Fix up srb for endian and force some values srbcmd->function = cpu_to_le32(SRBF_ExecuteScsi); // Force this srbcmd->channel = cpu_to_le32(user_srbcmd->channel); srbcmd->id = cpu_to_le32(user_srbcmd->id); srbcmd->lun = cpu_to_le32(user_srbcmd->lun); srbcmd->timeout = cpu_to_le32(user_srbcmd->timeout); srbcmd->flags = cpu_to_le32(flags); srbcmd->retry_limit = 0; // Obsolete parameter srbcmd->cdb_size = cpu_to_le32(user_srbcmd->cdb_size); memcpy(srbcmd->cdb, user_srbcmd->cdb, sizeof(srbcmd->cdb)); switch (flags & (SRB_DataIn | SRB_DataOut)) { case SRB_DataOut: data_dir = DMA_TO_DEVICE; break; case (SRB_DataIn | SRB_DataOut): data_dir = DMA_BIDIRECTIONAL; break; case SRB_DataIn: data_dir = DMA_FROM_DEVICE; break; default: data_dir = DMA_NONE; } if (user_srbcmd->sg.count > ARRAY_SIZE(sg_list)) { dprintk((KERN_DEBUG"aacraid: too many sg entries %d\n", le32_to_cpu(srbcmd->sg.count))); rcode = -EINVAL; goto cleanup; } actual_fibsize = sizeof(struct aac_srb) - sizeof(struct sgentry) + ((user_srbcmd->sg.count & 0xff) * sizeof(struct sgentry)); actual_fibsize64 = actual_fibsize + (user_srbcmd->sg.count & 0xff) * (sizeof(struct sgentry64) - sizeof(struct sgentry)); /* User made a mistake - should not continue */ if ((actual_fibsize != fibsize) && (actual_fibsize64 != fibsize)) { dprintk((KERN_DEBUG"aacraid: Bad Size specified in " "Raw SRB command calculated fibsize=%lu;%lu " "user_srbcmd->sg.count=%d aac_srb=%lu sgentry=%lu;%lu " "issued fibsize=%d\n", actual_fibsize, actual_fibsize64, user_srbcmd->sg.count, sizeof(struct aac_srb), sizeof(struct sgentry), sizeof(struct sgentry64), fibsize)); rcode = -EINVAL; goto cleanup; } if ((data_dir == DMA_NONE) && user_srbcmd->sg.count) { dprintk((KERN_DEBUG"aacraid: SG with no direction specified in Raw SRB command\n")); rcode = -EINVAL; goto cleanup; } byte_count = 0; if (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64) { struct user_sgmap64* upsg = (struct user_sgmap64*)&user_srbcmd->sg; struct sgmap64* psg = (struct sgmap64*)&srbcmd->sg; /* * This should also catch if user used the 32 bit sgmap */ if (actual_fibsize64 == fibsize) { actual_fibsize = actual_fibsize64; for (i = 0; i < upsg->count; i++) { u64 addr; void* p; if (upsg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { rcode = -EINVAL; goto cleanup; } /* Does this really need to be GFP_DMA? */ p = kmalloc(upsg->sg[i].count,GFP_KERNEL|__GFP_DMA); if(!p) { dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", upsg->sg[i].count,i,upsg->count)); rcode = -ENOMEM; goto cleanup; } addr = (u64)upsg->sg[i].addr[0]; addr += ((u64)upsg->sg[i].addr[1]) << 32; sg_user[i] = (void __user *)(uintptr_t)addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){ dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, upsg->sg[i].count, data_dir); psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff); psg->sg[i].addr[1] = cpu_to_le32(addr>>32); byte_count += upsg->sg[i].count; psg->sg[i].count = cpu_to_le32(upsg->sg[i].count); } } else { struct user_sgmap* usg; usg = kmalloc(actual_fibsize - sizeof(struct aac_srb) + sizeof(struct sgmap), GFP_KERNEL); if (!usg) { dprintk((KERN_DEBUG"aacraid: Allocation error in Raw SRB command\n")); rcode = -ENOMEM; goto cleanup; } memcpy (usg, upsg, actual_fibsize - sizeof(struct aac_srb) + sizeof(struct sgmap)); actual_fibsize = actual_fibsize64; for (i = 0; i < usg->count; i++) { u64 addr; void* p; if (usg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { kfree(usg); rcode = -EINVAL; goto cleanup; } /* Does this really need to be GFP_DMA? */ p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA); if(!p) { dprintk((KERN_DEBUG "aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", usg->sg[i].count,i,usg->count)); kfree(usg); rcode = -ENOMEM; goto cleanup; } sg_user[i] = (void __user *)(uintptr_t)usg->sg[i].addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){ kfree (usg); dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir); psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff); psg->sg[i].addr[1] = cpu_to_le32(addr>>32); byte_count += usg->sg[i].count; psg->sg[i].count = cpu_to_le32(usg->sg[i].count); } kfree (usg); } srbcmd->count = cpu_to_le32(byte_count); psg->count = cpu_to_le32(sg_indx+1); status = aac_fib_send(ScsiPortCommand64, srbfib, actual_fibsize, FsaNormal, 1, 1,NULL,NULL); } else { struct user_sgmap* upsg = &user_srbcmd->sg; struct sgmap* psg = &srbcmd->sg; if (actual_fibsize64 == fibsize) { struct user_sgmap64* usg = (struct user_sgmap64 *)upsg; for (i = 0; i < upsg->count; i++) { uintptr_t addr; void* p; if (usg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { rcode = -EINVAL; goto cleanup; } /* Does this really need to be GFP_DMA? */ p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA); if(!p) { dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", usg->sg[i].count,i,usg->count)); rcode = -ENOMEM; goto cleanup; } addr = (u64)usg->sg[i].addr[0]; addr += ((u64)usg->sg[i].addr[1]) << 32; sg_user[i] = (void __user *)addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p,sg_user[i],usg->sg[i].count)){ dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir); psg->sg[i].addr = cpu_to_le32(addr & 0xffffffff); byte_count += usg->sg[i].count; psg->sg[i].count = cpu_to_le32(usg->sg[i].count); } } else { for (i = 0; i < upsg->count; i++) { dma_addr_t addr; void* p; if (upsg->sg[i].count > ((dev->adapter_info.options & AAC_OPT_NEW_COMM) ? (dev->scsi_host_ptr->max_sectors << 9) : 65536)) { rcode = -EINVAL; goto cleanup; } p = kmalloc(upsg->sg[i].count, GFP_KERNEL); if (!p) { dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", upsg->sg[i].count, i, upsg->count)); rcode = -ENOMEM; goto cleanup; } sg_user[i] = (void __user *)(uintptr_t)upsg->sg[i].addr; sg_list[i] = p; // save so we can clean up later sg_indx = i; if (flags & SRB_DataOut) { if(copy_from_user(p, sg_user[i], upsg->sg[i].count)) { dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); rcode = -EFAULT; goto cleanup; } } addr = pci_map_single(dev->pdev, p, upsg->sg[i].count, data_dir); psg->sg[i].addr = cpu_to_le32(addr); byte_count += upsg->sg[i].count; psg->sg[i].count = cpu_to_le32(upsg->sg[i].count); } } srbcmd->count = cpu_to_le32(byte_count); psg->count = cpu_to_le32(sg_indx+1); status = aac_fib_send(ScsiPortCommand, srbfib, actual_fibsize, FsaNormal, 1, 1, NULL, NULL); } if (status == -ERESTARTSYS) { rcode = -ERESTARTSYS; goto cleanup; } if (status != 0){ dprintk((KERN_DEBUG"aacraid: Could not send raw srb fib to hba\n")); rcode = -ENXIO; goto cleanup; } if (flags & SRB_DataIn) { for(i = 0 ; i <= sg_indx; i++){ byte_count = le32_to_cpu( (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64) ? ((struct sgmap64*)&srbcmd->sg)->sg[i].count : srbcmd->sg.sg[i].count); if(copy_to_user(sg_user[i], sg_list[i], byte_count)){ dprintk((KERN_DEBUG"aacraid: Could not copy sg data to user\n")); rcode = -EFAULT; goto cleanup; } } } reply = (struct aac_srb_reply *) fib_data(srbfib); if(copy_to_user(user_reply,reply,sizeof(struct aac_srb_reply))){ dprintk((KERN_DEBUG"aacraid: Could not copy reply to user\n")); rcode = -EFAULT; goto cleanup; } cleanup: kfree(user_srbcmd); for(i=0; i <= sg_indx; i++){ kfree(sg_list[i]); } if (rcode != -ERESTARTSYS) { aac_fib_complete(srbfib); aac_fib_free(srbfib); } return rcode; }
nan
null
10,824
278785541490766402988293999285996258406
359
aacraid: prevent invalid pointer dereference It appears that driver runs into a problem here if fibsize is too small because we allocate user_srbcmd with fibsize size only but later we access it until user_srbcmd->sg.count to copy it over to srbcmd. It is not correct to test (fibsize < sizeof(*user_srbcmd)) because this structure already includes one sg element and this is not needed for commands without data. So, we would recommend to add the following (instead of test for fibsize == 0). Signed-off-by: Mahesh Rajashekhara <Mahesh.Rajashekhara@pmcs.com> Reported-by: Nico Golde <nico@ngolde.de> Reported-by: Fabian Yamaguchi <fabs@goesec.de> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
null
samba
25452a2268ac7013da28125f3df22085139af12d
1
void chain_reply(struct smb_request *req) { size_t smblen = smb_len(req->inbuf); size_t already_used, length_needed; uint8_t chain_cmd; uint32_t chain_offset; /* uint32_t to avoid overflow */ uint8_t wct; uint16_t *vwv; uint16_t buflen; uint8_t *buf; if (IVAL(req->outbuf, smb_rcls) != 0) { fixup_chain_error_packet(req); } /* * Any of the AndX requests and replies have at least a wct of * 2. vwv[0] is the next command, vwv[1] is the offset from the * beginning of the SMB header to the next wct field. * * None of the AndX requests put anything valuable in vwv[0] and [1], * so we can overwrite it here to form the chain. */ if ((req->wct < 2) || (CVAL(req->outbuf, smb_wct) < 2)) { goto error; } /* * Here we assume that this is the end of the chain. For that we need * to set "next command" to 0xff and the offset to 0. If we later find * more commands in the chain, this will be overwritten again. */ SCVAL(req->outbuf, smb_vwv0, 0xff); SCVAL(req->outbuf, smb_vwv0+1, 0); SSVAL(req->outbuf, smb_vwv1, 0); if (req->chain_outbuf == NULL) { /* * In req->chain_outbuf we collect all the replies. Start the * chain by copying in the first reply. * * We do the realloc because later on we depend on * talloc_get_size to determine the length of * chain_outbuf. The reply_xxx routines might have * over-allocated (reply_pipe_read_and_X used to be such an * example). */ req->chain_outbuf = TALLOC_REALLOC_ARRAY( req, req->outbuf, uint8_t, smb_len(req->outbuf) + 4); if (req->chain_outbuf == NULL) { goto error; } req->outbuf = NULL; } else { /* * Update smb headers where subsequent chained commands * may have updated them. */ SCVAL(req->chain_outbuf, smb_tid, CVAL(req->outbuf, smb_tid)); SCVAL(req->chain_outbuf, smb_uid, CVAL(req->outbuf, smb_uid)); if (!smb_splice_chain(&req->chain_outbuf, CVAL(req->outbuf, smb_com), CVAL(req->outbuf, smb_wct), (uint16_t *)(req->outbuf + smb_vwv), 0, smb_buflen(req->outbuf), (uint8_t *)smb_buf(req->outbuf))) { goto error; } TALLOC_FREE(req->outbuf); } /* * We use the old request's vwv field to grab the next chained command * and offset into the chained fields. */ chain_cmd = CVAL(req->vwv+0, 0); chain_offset = SVAL(req->vwv+1, 0); if (chain_cmd == 0xff) { /* * End of chain, no more requests from the client. So ship the * replies. */ smb_setlen((char *)(req->chain_outbuf), talloc_get_size(req->chain_outbuf) - 4); if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf, true, req->seqnum+1, IS_CONN_ENCRYPTED(req->conn) ||req->encrypted, &req->pcd)) { exit_server_cleanly("chain_reply: srv_send_smb " "failed."); } TALLOC_FREE(req->chain_outbuf); req->done = true; return; } /* add a new perfcounter for this element of chain */ SMB_PERFCOUNT_ADD(&req->pcd); SMB_PERFCOUNT_SET_OP(&req->pcd, chain_cmd); SMB_PERFCOUNT_SET_MSGLEN_IN(&req->pcd, smblen); /* * Check if the client tries to fool us. The request so far uses the * space to the end of the byte buffer in the request just * processed. The chain_offset can't point into that area. If that was * the case, we could end up with an endless processing of the chain, * we would always handle the same request. */ already_used = PTR_DIFF(req->buf+req->buflen, smb_base(req->inbuf)); if (chain_offset < already_used) { goto error; } /* * Next check: Make sure the chain offset does not point beyond the * overall smb request length. */ length_needed = chain_offset+1; /* wct */ if (length_needed > smblen) { goto error; } /* * Now comes the pointer magic. Goal here is to set up req->vwv and * req->buf correctly again to be able to call the subsequent * switch_message(). The chain offset (the former vwv[1]) points at * the new wct field. */ wct = CVAL(smb_base(req->inbuf), chain_offset); /* * Next consistency check: Make the new vwv array fits in the overall * smb request. */ length_needed += (wct+1)*sizeof(uint16_t); /* vwv+buflen */ if (length_needed > smblen) { goto error; } vwv = (uint16_t *)(smb_base(req->inbuf) + chain_offset + 1); /* * Now grab the new byte buffer.... */ buflen = SVAL(vwv+wct, 0); /* * .. and check that it fits. */ length_needed += buflen; if (length_needed > smblen) { goto error; } buf = (uint8_t *)(vwv+wct+1); req->cmd = chain_cmd; req->wct = wct; req->vwv = vwv; req->buflen = buflen; req->buf = buf; switch_message(chain_cmd, req, smblen); if (req->outbuf == NULL) { /* * This happens if the chained command has suspended itself or * if it has called srv_send_smb() itself. */ return; } /* * We end up here if the chained command was not itself chained or * suspended, but for example a close() command. We now need to splice * the chained commands' outbuf into the already built up chain_outbuf * and ship the result. */ goto done; error: /* * We end up here if there's any error in the chain syntax. Report a * DOS error, just like Windows does. */ reply_force_doserror(req, ERRSRV, ERRerror); fixup_chain_error_packet(req); done: /* * This scary statement intends to set the * FLAGS2_32_BIT_ERROR_CODES flg2 field in req->chain_outbuf * to the value req->outbuf carries */ SSVAL(req->chain_outbuf, smb_flg2, (SVAL(req->chain_outbuf, smb_flg2) & ~FLAGS2_32_BIT_ERROR_CODES) | (SVAL(req->outbuf, smb_flg2) & FLAGS2_32_BIT_ERROR_CODES)); /* * Transfer the error codes from the subrequest to the main one */ SSVAL(req->chain_outbuf, smb_rcls, SVAL(req->outbuf, smb_rcls)); SSVAL(req->chain_outbuf, smb_err, SVAL(req->outbuf, smb_err)); if (!smb_splice_chain(&req->chain_outbuf, CVAL(req->outbuf, smb_com), CVAL(req->outbuf, smb_wct), (uint16_t *)(req->outbuf + smb_vwv), 0, smb_buflen(req->outbuf), (uint8_t *)smb_buf(req->outbuf))) { exit_server_cleanly("chain_reply: smb_splice_chain failed\n"); } TALLOC_FREE(req->outbuf); smb_setlen((char *)(req->chain_outbuf), talloc_get_size(req->chain_outbuf) - 4); show_msg((char *)(req->chain_outbuf)); if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf, true, req->seqnum+1, IS_CONN_ENCRYPTED(req->conn)||req->encrypted, &req->pcd)) { exit_server_cleanly("construct_reply: srv_send_smb failed."); } TALLOC_FREE(req->chain_outbuf); req->done = true; }
nan
null
10,825
109200006521800197683757265795325171881
240
s3: Fix a NULL pointer dereference Found by Laurent Gaffie <laurent.gaffie@gmail.com>. Thanks! Volker
null
linux
15fab63e1e57be9fdb5eec1bbc5916e9825e9acb
1
static inline void pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { buf->ops->get(pipe, buf); }
nan
null
10,827
82379531495560302876561015936188277715
5
fs: prevent page refcount overflow in pipe_buf_get Change pipe_buf_get() to return a bool indicating whether it succeeded in raising the refcount of the page (if the thing in the pipe is a page). This removes another mechanism for overflowing the page refcount. All callers converted to handle a failure. Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Matthew Wilcox <willy@infradead.org> Cc: stable@kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
null
gstreamer
bc2cdd57d549ab3ba59782e9b395d0cd683fd3ac
1
UINT CSoundFile::ReadSample(MODINSTRUMENT *pIns, UINT nFlags, LPCSTR lpMemFile, DWORD dwMemLength) //------------------------------------------------------------------------------------------------ { UINT len = 0, mem = pIns->nLength+6; if ((!pIns) || (pIns->nLength < 4) || (!lpMemFile)) return 0; if (pIns->nLength > MAX_SAMPLE_LENGTH) pIns->nLength = MAX_SAMPLE_LENGTH; pIns->uFlags &= ~(CHN_16BIT|CHN_STEREO); if (nFlags & RSF_16BIT) { mem *= 2; pIns->uFlags |= CHN_16BIT; } if (nFlags & RSF_STEREO) { mem *= 2; pIns->uFlags |= CHN_STEREO; } if ((pIns->pSample = AllocateSample(mem)) == NULL) { pIns->nLength = 0; return 0; } switch(nFlags) { // 1: 8-bit unsigned PCM data case RS_PCM8U: { len = pIns->nLength; if (len > dwMemLength) len = pIns->nLength = dwMemLength; signed char *pSample = pIns->pSample; for (UINT j=0; j<len; j++) pSample[j] = (signed char)(lpMemFile[j] - 0x80); } break; // 2: 8-bit ADPCM data with linear table case RS_PCM8D: { len = pIns->nLength; if (len > dwMemLength) break; signed char *pSample = pIns->pSample; const signed char *p = (const signed char *)lpMemFile; int delta = 0; for (UINT j=0; j<len; j++) { delta += p[j]; *pSample++ = (signed char)delta; } } break; // 3: 4-bit ADPCM data case RS_ADPCM4: { len = (pIns->nLength + 1) / 2; if (len > dwMemLength - 16) break; memcpy(CompressionTable, lpMemFile, 16); lpMemFile += 16; signed char *pSample = pIns->pSample; signed char delta = 0; for (UINT j=0; j<len; j++) { BYTE b0 = (BYTE)lpMemFile[j]; BYTE b1 = (BYTE)(lpMemFile[j] >> 4); delta = (signed char)GetDeltaValue((int)delta, b0); pSample[0] = delta; delta = (signed char)GetDeltaValue((int)delta, b1); pSample[1] = delta; pSample += 2; } len += 16; } break; // 4: 16-bit ADPCM data with linear table case RS_PCM16D: { len = pIns->nLength * 2; if (len > dwMemLength) break; short int *pSample = (short int *)pIns->pSample; short int *p = (short int *)lpMemFile; int delta16 = 0; for (UINT j=0; j<len; j+=2) { delta16 += bswapLE16(*p++); *pSample++ = (short int)delta16; } } break; // 5: 16-bit signed PCM data case RS_PCM16S: { len = pIns->nLength * 2; if (len <= dwMemLength) memcpy(pIns->pSample, lpMemFile, len); short int *pSample = (short int *)pIns->pSample; for (UINT j=0; j<len; j+=2) { short int s = bswapLE16(*pSample); *pSample++ = s; } } break; // 16-bit signed mono PCM motorola byte order case RS_PCM16M: len = pIns->nLength * 2; if (len > dwMemLength) len = dwMemLength & ~1; if (len > 1) { signed char *pSample = (signed char *)pIns->pSample; signed char *pSrc = (signed char *)lpMemFile; for (UINT j=0; j<len; j+=2) { // pSample[j] = pSrc[j+1]; // pSample[j+1] = pSrc[j]; *((unsigned short *)(pSample+j)) = bswapBE16(*((unsigned short *)(pSrc+j))); } } break; // 6: 16-bit unsigned PCM data case RS_PCM16U: { len = pIns->nLength * 2; if (len > dwMemLength) break; short int *pSample = (short int *)pIns->pSample; short int *pSrc = (short int *)lpMemFile; for (UINT j=0; j<len; j+=2) *pSample++ = bswapLE16(*(pSrc++)) - 0x8000; } break; // 16-bit signed stereo big endian case RS_STPCM16M: len = pIns->nLength * 2; if (len*2 <= dwMemLength) { signed char *pSample = (signed char *)pIns->pSample; signed char *pSrc = (signed char *)lpMemFile; for (UINT j=0; j<len; j+=2) { // pSample[j*2] = pSrc[j+1]; // pSample[j*2+1] = pSrc[j]; // pSample[j*2+2] = pSrc[j+1+len]; // pSample[j*2+3] = pSrc[j+len]; *((unsigned short *)(pSample+j*2)) = bswapBE16(*((unsigned short *)(pSrc+j))); *((unsigned short *)(pSample+j*2+2)) = bswapBE16(*((unsigned short *)(pSrc+j+len))); } len *= 2; } break; // 8-bit stereo samples case RS_STPCM8S: case RS_STPCM8U: case RS_STPCM8D: { int iadd_l = 0, iadd_r = 0; if (nFlags == RS_STPCM8U) { iadd_l = iadd_r = -128; } len = pIns->nLength; signed char *psrc = (signed char *)lpMemFile; signed char *pSample = (signed char *)pIns->pSample; if (len*2 > dwMemLength) break; for (UINT j=0; j<len; j++) { pSample[j*2] = (signed char)(psrc[0] + iadd_l); pSample[j*2+1] = (signed char)(psrc[len] + iadd_r); psrc++; if (nFlags == RS_STPCM8D) { iadd_l = pSample[j*2]; iadd_r = pSample[j*2+1]; } } len *= 2; } break; // 16-bit stereo samples case RS_STPCM16S: case RS_STPCM16U: case RS_STPCM16D: { int iadd_l = 0, iadd_r = 0; if (nFlags == RS_STPCM16U) { iadd_l = iadd_r = -0x8000; } len = pIns->nLength; short int *psrc = (short int *)lpMemFile; short int *pSample = (short int *)pIns->pSample; if (len*4 > dwMemLength) break; for (UINT j=0; j<len; j++) { pSample[j*2] = (short int) (bswapLE16(psrc[0]) + iadd_l); pSample[j*2+1] = (short int) (bswapLE16(psrc[len]) + iadd_r); psrc++; if (nFlags == RS_STPCM16D) { iadd_l = pSample[j*2]; iadd_r = pSample[j*2+1]; } } len *= 4; } break; // IT 2.14 compressed samples case RS_IT2148: case RS_IT21416: case RS_IT2158: case RS_IT21516: len = dwMemLength; if (len < 4) break; if ((nFlags == RS_IT2148) || (nFlags == RS_IT2158)) ITUnpack8Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT2158)); else ITUnpack16Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT21516)); break; #ifndef MODPLUG_BASIC_SUPPORT #ifndef FASTSOUNDLIB // 8-bit interleaved stereo samples case RS_STIPCM8S: case RS_STIPCM8U: { int iadd = 0; if (nFlags == RS_STIPCM8U) { iadd = -0x80; } len = pIns->nLength; if (len*2 > dwMemLength) len = dwMemLength >> 1; LPBYTE psrc = (LPBYTE)lpMemFile; LPBYTE pSample = (LPBYTE)pIns->pSample; for (UINT j=0; j<len; j++) { pSample[j*2] = (signed char)(psrc[0] + iadd); pSample[j*2+1] = (signed char)(psrc[1] + iadd); psrc+=2; } len *= 2; } break; // 16-bit interleaved stereo samples case RS_STIPCM16S: case RS_STIPCM16U: { int iadd = 0; if (nFlags == RS_STIPCM16U) iadd = -32768; len = pIns->nLength; if (len*4 > dwMemLength) len = dwMemLength >> 2; short int *psrc = (short int *)lpMemFile; short int *pSample = (short int *)pIns->pSample; for (UINT j=0; j<len; j++) { pSample[j*2] = (short int)(bswapLE16(psrc[0]) + iadd); pSample[j*2+1] = (short int)(bswapLE16(psrc[1]) + iadd); psrc += 2; } len *= 4; } break; // AMS compressed samples case RS_AMS8: case RS_AMS16: len = 9; if (dwMemLength > 9) { const char *psrc = lpMemFile; char packcharacter = lpMemFile[8], *pdest = (char *)pIns->pSample; len += bswapLE32(*((LPDWORD)(lpMemFile+4))); if (len > dwMemLength) len = dwMemLength; UINT dmax = pIns->nLength; if (pIns->uFlags & CHN_16BIT) dmax <<= 1; AMSUnpack(psrc+9, len-9, pdest, dmax, packcharacter); } break; // PTM 8bit delta to 16-bit sample case RS_PTM8DTO16: { len = pIns->nLength * 2; if (len > dwMemLength) break; signed char *pSample = (signed char *)pIns->pSample; signed char delta8 = 0; for (UINT j=0; j<len; j++) { delta8 += lpMemFile[j]; *pSample++ = delta8; } WORD *pSampleW = (WORD *)pIns->pSample; for (UINT j=0; j<len; j+=2) // swaparoni! { WORD s = bswapLE16(*pSampleW); *pSampleW++ = s; } } break; // Huffman MDL compressed samples case RS_MDL8: case RS_MDL16: len = dwMemLength; if (len >= 4) { LPBYTE pSample = (LPBYTE)pIns->pSample; LPBYTE ibuf = (LPBYTE)lpMemFile; DWORD bitbuf = bswapLE32(*((DWORD *)ibuf)); UINT bitnum = 32; BYTE dlt = 0, lowbyte = 0; ibuf += 4; for (UINT j=0; j<pIns->nLength; j++) { BYTE hibyte; BYTE sign; if (nFlags == RS_MDL16) lowbyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 8); sign = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 1); if (MDLReadBits(bitbuf, bitnum, ibuf, 1)) { hibyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 3); } else { hibyte = 8; while (!MDLReadBits(bitbuf, bitnum, ibuf, 1)) hibyte += 0x10; hibyte += MDLReadBits(bitbuf, bitnum, ibuf, 4); } if (sign) hibyte = ~hibyte; dlt += hibyte; if (nFlags != RS_MDL16) pSample[j] = dlt; else { pSample[j<<1] = lowbyte; pSample[(j<<1)+1] = dlt; } } } break; case RS_DMF8: case RS_DMF16: len = dwMemLength; if (len >= 4) { UINT maxlen = pIns->nLength; if (pIns->uFlags & CHN_16BIT) maxlen <<= 1; LPBYTE ibuf = (LPBYTE)lpMemFile, ibufmax = (LPBYTE)(lpMemFile+dwMemLength); len = DMFUnpack((LPBYTE)pIns->pSample, ibuf, ibufmax, maxlen); } break; #ifdef MODPLUG_TRACKER // PCM 24-bit signed -> load sample, and normalize it to 16-bit case RS_PCM24S: case RS_PCM32S: len = pIns->nLength * 3; if (nFlags == RS_PCM32S) len += pIns->nLength; if (len > dwMemLength) break; if (len > 4*8) { UINT slsize = (nFlags == RS_PCM32S) ? 4 : 3; LPBYTE pSrc = (LPBYTE)lpMemFile; LONG max = 255; if (nFlags == RS_PCM32S) pSrc++; for (UINT j=0; j<len; j+=slsize) { LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8; l /= 256; if (l > max) max = l; if (-l > max) max = -l; } max = (max / 128) + 1; signed short *pDest = (signed short *)pIns->pSample; for (UINT k=0; k<len; k+=slsize) { LONG l = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8; *pDest++ = (signed short)(l / max); } } break; // Stereo PCM 24-bit signed -> load sample, and normalize it to 16-bit case RS_STIPCM24S: case RS_STIPCM32S: len = pIns->nLength * 6; if (nFlags == RS_STIPCM32S) len += pIns->nLength * 2; if (len > dwMemLength) break; if (len > 8*8) { UINT slsize = (nFlags == RS_STIPCM32S) ? 4 : 3; LPBYTE pSrc = (LPBYTE)lpMemFile; LONG max = 255; if (nFlags == RS_STIPCM32S) pSrc++; for (UINT j=0; j<len; j+=slsize) { LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8; l /= 256; if (l > max) max = l; if (-l > max) max = -l; } max = (max / 128) + 1; signed short *pDest = (signed short *)pIns->pSample; for (UINT k=0; k<len; k+=slsize) { LONG lr = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8; k += slsize; LONG ll = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8; pDest[0] = (signed short)ll; pDest[1] = (signed short)lr; pDest += 2; } } break; // 16-bit signed big endian interleaved stereo case RS_STIPCM16M: { len = pIns->nLength; if (len*4 > dwMemLength) len = dwMemLength >> 2; LPCBYTE psrc = (LPCBYTE)lpMemFile; short int *pSample = (short int *)pIns->pSample; for (UINT j=0; j<len; j++) { pSample[j*2] = (signed short)(((UINT)psrc[0] << 8) | (psrc[1])); pSample[j*2+1] = (signed short)(((UINT)psrc[2] << 8) | (psrc[3])); psrc += 4; } len *= 4; } break; #endif // MODPLUG_TRACKER #endif // !FASTSOUNDLIB #endif // !MODPLUG_BASIC_SUPPORT // Default: 8-bit signed PCM data default: len = pIns->nLength; if (len > dwMemLength) len = pIns->nLength = dwMemLength; memcpy(pIns->pSample, lpMemFile, len); } if (len > dwMemLength) { if (pIns->pSample) { pIns->nLength = 0; FreeSample(pIns->pSample); pIns->pSample = NULL; } return 0; } AdjustSampleLoop(pIns); return len; }
nan
null
10,829
67540001168489353744881394746637712038
452
gst/modplug/libmodplug/sndfile.cpp: Fix potential buffer overflow (CVE-2006-4192) (#385788). Original commit message from CVS: * gst/modplug/libmodplug/sndfile.cpp: Fix potential buffer overflow (CVE-2006-4192) (#385788).
null
FFmpeg
8c2ea3030af7b40a3c4275696fb5c76cdb80950a
1
static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { PicContext *s = avctx->priv_data; AVFrame *frame = data; uint32_t *palette; int bits_per_plane, bpp, etype, esize, npal, pos_after_pal; int i, x, y, plane, tmp, ret, val; bytestream2_init(&s->g, avpkt->data, avpkt->size); if (bytestream2_get_bytes_left(&s->g) < 11) return AVERROR_INVALIDDATA; if (bytestream2_get_le16u(&s->g) != 0x1234) return AVERROR_INVALIDDATA; s->width = bytestream2_get_le16u(&s->g); s->height = bytestream2_get_le16u(&s->g); bytestream2_skip(&s->g, 4); tmp = bytestream2_get_byteu(&s->g); bits_per_plane = tmp & 0xF; s->nb_planes = (tmp >> 4) + 1; bpp = bits_per_plane * s->nb_planes; if (bits_per_plane > 8 || bpp < 1 || bpp > 32) { avpriv_request_sample(avctx, "Unsupported bit depth"); return AVERROR_PATCHWELCOME; } if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) { bytestream2_skip(&s->g, 2); etype = bytestream2_get_le16(&s->g); esize = bytestream2_get_le16(&s->g); if (bytestream2_get_bytes_left(&s->g) < esize) return AVERROR_INVALIDDATA; } else { etype = -1; esize = 0; } avctx->pix_fmt = AV_PIX_FMT_PAL8; if (av_image_check_size(s->width, s->height, 0, avctx) < 0) return -1; if (s->width != avctx->width && s->height != avctx->height) { ret = ff_set_dimensions(avctx, s->width, s->height); if (ret < 0) return ret; } if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; memset(frame->data[0], 0, s->height * frame->linesize[0]); frame->pict_type = AV_PICTURE_TYPE_I; frame->palette_has_changed = 1; pos_after_pal = bytestream2_tell(&s->g) + esize; palette = (uint32_t*)frame->data[1]; if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) { int idx = bytestream2_get_byte(&s->g); npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ]; } else if (etype == 2) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)]; } } else if (etype == 3) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)]; } } else if (etype == 4 || etype == 5) { npal = FFMIN(esize / 3, 256); for (i = 0; i < npal; i++) { palette[i] = bytestream2_get_be24(&s->g) << 2; palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303; } } else { if (bpp == 1) { npal = 2; palette[0] = 0xFF000000; palette[1] = 0xFFFFFFFF; } else if (bpp == 2) { npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ]; } else { npal = 16; memcpy(palette, ff_cga_palette, npal * 4); } } // fill remaining palette entries memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4); // skip remaining palette bytes bytestream2_seek(&s->g, pos_after_pal, SEEK_SET); val = 0; y = s->height - 1; if (bytestream2_get_le16(&s->g)) { x = 0; plane = 0; while (bytestream2_get_bytes_left(&s->g) >= 6) { int stop_size, marker, t1, t2; t1 = bytestream2_get_bytes_left(&s->g); t2 = bytestream2_get_le16(&s->g); stop_size = t1 - FFMIN(t1, t2); // ignore uncompressed block size bytestream2_skip(&s->g, 2); marker = bytestream2_get_byte(&s->g); while (plane < s->nb_planes && bytestream2_get_bytes_left(&s->g) > stop_size) { int run = 1; val = bytestream2_get_byte(&s->g); if (val == marker) { run = bytestream2_get_byte(&s->g); if (run == 0) run = bytestream2_get_le16(&s->g); val = bytestream2_get_byte(&s->g); } if (!bytestream2_get_bytes_left(&s->g)) break; if (bits_per_plane == 8) { picmemset_8bpp(s, frame, val, run, &x, &y); if (y < 0) goto finish; } else { picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane); } } } if (x < avctx->width) { int run = (y + 1) * avctx->width - x; if (bits_per_plane == 8) picmemset_8bpp(s, frame, val, run, &x, &y); else picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane); } } else { while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) { memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g))); bytestream2_skip(&s->g, avctx->width); y--; } } finish: *got_frame = 1; return avpkt->size; }
nan
null
10,830
221742097572568795231388070315896049988
158
avcodec/pictordec: Fix logic error Fixes: 559/clusterfuzz-testcase-6424225917173760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
radare2
f41e941341e44aa86edd4483c4487ec09a074257
1
static int dalvik_disassemble (RAsm *a, RAsmOp *op, const ut8 *buf, int len) { int vA, vB, vC, payload = 0, i = (int) buf[0]; int size = dalvik_opcodes[i].len; char str[1024], *strasm; ut64 offset; const char *flag_str; op->buf_asm[0] = 0; if (buf[0] == 0x00) { /* nop */ switch (buf[1]) { case 0x01: /* packed-switch-payload */ // ushort size // int first_key // int[size] = relative offsets { unsigned short array_size = buf[2] | (buf[3] << 8); int first_key = buf[4] | (buf[5] << 8) | (buf[6] << 16) | (buf[7] << 24); sprintf (op->buf_asm, "packed-switch-payload %d, %d", array_size, first_key); size = 8; payload = 2 * (array_size * 2); len = 0; } break; case 0x02: /* sparse-switch-payload */ // ushort size // int[size] keys // int[size] relative offsets { unsigned short array_size = buf[2] | (buf[3] << 8); sprintf (op->buf_asm, "sparse-switch-payload %d", array_size); size = 4; payload = 2 * (array_size*4); len = 0; } break; case 0x03: /* fill-array-data-payload */ // element_width = 2 bytes ushort little endian // size = 4 bytes uint // ([size*element_width+1)/2)+4 if (len > 7) { unsigned short elem_width = buf[2] | (buf[3] << 8); unsigned int array_size = buf[4] | (buf[5] << 8) | (buf[6] << 16) | (buf[7] << 24); snprintf (op->buf_asm, sizeof (op->buf_asm), "fill-array-data-payload %d, %d", elem_width, array_size); payload = 2 * ((array_size * elem_width+1)/2); } size = 8; len = 0; break; default: /* nop */ break; } } strasm = NULL; if (size <= len) { strncpy (op->buf_asm, dalvik_opcodes[i].name, sizeof (op->buf_asm) - 1); strasm = strdup (op->buf_asm); size = dalvik_opcodes[i].len; switch (dalvik_opcodes[i].fmt) { case fmtop: break; case fmtopvAvB: vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; sprintf (str, " v%i, v%i", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAvBBBB: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; sprintf (str, " v%i, v%i", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAAAvBBBB: // buf[1] seems useless :/ vA = (buf[3] << 8) | buf[2]; vB = (buf[5] << 8) | buf[4]; sprintf (str, " v%i, v%i", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAA: vA = (int) buf[1]; sprintf (str, " v%i", vA); strasm = r_str_concat (strasm, str); break; case fmtopvAcB: vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; sprintf (str, " v%i, %#x", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAcBBBB: vA = (int) buf[1]; { short sB = (buf[3] << 8) | buf[2]; sprintf (str, " v%i, %#04hx", vA, sB); strasm = r_str_concat (strasm, str); } break; case fmtopvAAcBBBBBBBB: vA = (int) buf[1]; vB = buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24); if (buf[0] == 0x17) { //const-wide/32 snprintf (str, sizeof (str), " v%i:v%i, 0x%08x", vA, vA + 1, vB); } else { //const snprintf (str, sizeof (str), " v%i, 0x%08x", vA, vB); } strasm = r_str_concat (strasm, str); break; case fmtopvAAcBBBB0000: vA = (int) buf[1]; // vB = 0|(buf[3]<<16)|(buf[2]<<24); vB = 0 | (buf[2] << 16) | (buf[3] << 24); if (buf[0] == 0x19) { // const-wide/high16 snprintf (str, sizeof (str), " v%i:v%i, 0x%08x", vA, vA + 1, vB); } else { snprintf (str, sizeof (str), " v%i, 0x%08x", vA, vB); } strasm = r_str_concat (strasm, str); break; case fmtopvAAcBBBBBBBBBBBBBBBB: vA = (int) buf[1]; #define llint long long int llint lB = (llint)buf[2] | ((llint)buf[3] << 8)| ((llint)buf[4] << 16) | ((llint)buf[5] << 24)| ((llint)buf[6] << 32) | ((llint)buf[7] << 40)| ((llint)buf[8] << 48) | ((llint)buf[9] << 56); #undef llint sprintf (str, " v%i:v%i, 0x%"PFMT64x, vA, vA + 1, lB); strasm = r_str_concat (strasm, str); break; case fmtopvAAvBBvCC: vA = (int) buf[1]; vB = (int) buf[2]; vC = (int) buf[3]; sprintf (str, " v%i, v%i, v%i", vA, vB, vC); strasm = r_str_concat (strasm, str); break; case fmtopvAAvBBcCC: vA = (int) buf[1]; vB = (int) buf[2]; vC = (int) buf[3]; sprintf (str, " v%i, v%i, %#x", vA, vB, vC); strasm = r_str_concat (strasm, str); break; case fmtopvAvBcCCCC: vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; vC = (buf[3] << 8) | buf[2]; sprintf (str, " v%i, v%i, %#x", vA, vB, vC); strasm = r_str_concat (strasm, str); break; case fmtoppAA: vA = (char) buf[1]; //sprintf (str, " %i", vA*2); // vA : word -> byte snprintf (str, sizeof (str), " 0x%08"PFMT64x, a->pc + (vA * 2)); // vA : word -> byte strasm = r_str_concat (strasm, str); break; case fmtoppAAAA: vA = (short) (buf[3] << 8 | buf[2]); snprintf (str, sizeof (str), " 0x%08"PFMT64x, a->pc + (vA * 2)); // vA : word -> byte strasm = r_str_concat (strasm, str); break; case fmtopvAApBBBB: // if-*z vA = (int) buf[1]; vB = (int) (buf[3] << 8 | buf[2]); //sprintf (str, " v%i, %i", vA, vB); snprintf (str, sizeof (str), " v%i, 0x%08"PFMT64x, vA, a->pc + (vB * 2)); strasm = r_str_concat (strasm, str); break; case fmtoppAAAAAAAA: vA = (int) (buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24)); //sprintf (str, " %#08x", vA*2); // vA: word -> byte snprintf (str, sizeof (str), " 0x%08"PFMT64x, a->pc + (vA*2)); // vA : word -> byte strasm = r_str_concat (strasm, str); break; case fmtopvAvBpCCCC: // if-* vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; vC = (int) (buf[3] << 8 | buf[2]); //sprintf (str, " v%i, v%i, %i", vA, vB, vC); snprintf (str, sizeof (str)," v%i, v%i, 0x%08"PFMT64x, vA, vB, a->pc + (vC * 2)); strasm = r_str_concat (strasm, str); break; case fmtopvAApBBBBBBBB: vA = (int) buf[1]; vB = (int) (buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24)); snprintf (str, sizeof (str), " v%i, 0x%08"PFMT64x, vA, a->pc + vB); // + (vB*2)); strasm = r_str_concat (strasm, str); break; case fmtoptinlineI: vA = (int) (buf[1] & 0x0f); vB = (buf[3] << 8) | buf[2]; *str = 0; switch (vA) { case 1: sprintf (str, " {v%i}", buf[4] & 0x0f); break; case 2: sprintf (str, " {v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4); break; case 3: sprintf (str, " {v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f); break; case 4: sprintf (str, " {v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4); break; default: sprintf (str, " {}"); } strasm = r_str_concat (strasm, str); sprintf (str, ", [%04x]", vB); strasm = r_str_concat (strasm, str); break; case fmtoptinlineIR: case fmtoptinvokeVSR: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; vC = (buf[5] << 8) | buf[4]; sprintf (str, " {v%i..v%i}, [%04x]", vC, vC + vA - 1, vB); strasm = r_str_concat (strasm, str); break; case fmtoptinvokeVS: vA = (int) (buf[1] & 0xf0) >> 4; vB = (buf[3] << 8) | buf[2]; switch (vA) { case 1: sprintf (str, " {v%i}", buf[4] & 0x0f); break; case 2: sprintf (str, " {v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4); break; case 3: sprintf (str, " {v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f); break; case 4: sprintf (str, " {v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4); break; default: sprintf (str, " {}"); break; } strasm = r_str_concat (strasm, str); sprintf (str, ", [%04x]", vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAtBBBB: // "sput-*" vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; if (buf[0] == 0x1a) { offset = R_ASM_GET_OFFSET (a, 's', vB); if (offset == -1) { sprintf (str, " v%i, string+%i", vA, vB); } else { sprintf (str, " v%i, 0x%"PFMT64x, vA, offset); } } else if (buf[0] == 0x1c || buf[0] == 0x1f || buf[0] == 0x22) { flag_str = R_ASM_GET_NAME (a, 'c', vB); if (!flag_str) { sprintf (str, " v%i, class+%i", vA, vB); } else { sprintf (str, " v%i, %s", vA, flag_str); } } else { flag_str = R_ASM_GET_NAME (a, 'f', vB); if (!flag_str) { sprintf (str, " v%i, field+%i", vA, vB); } else { sprintf (str, " v%i, %s", vA, flag_str); } } strasm = r_str_concat (strasm, str); break; case fmtoptopvAvBoCCCC: vA = (buf[1] & 0x0f); vB = (buf[1] & 0xf0) >> 4; vC = (buf[3]<<8) | buf[2]; offset = R_ASM_GET_OFFSET (a, 'o', vC); if (offset == -1) { sprintf (str, " v%i, v%i, [obj+%04x]", vA, vB, vC); } else { sprintf (str, " v%i, v%i, [0x%"PFMT64x"]", vA, vB, offset); } strasm = r_str_concat (strasm, str); break; case fmtopAAtBBBB: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; offset = R_ASM_GET_OFFSET (a, 't', vB); if (offset == -1) { sprintf (str, " v%i, thing+%i", vA, vB); } else { sprintf (str, " v%i, 0x%"PFMT64x, vA, offset); } strasm = r_str_concat (strasm, str); break; case fmtopvAvBtCCCC: vA = (buf[1] & 0x0f); vB = (buf[1] & 0xf0) >> 4; vC = (buf[3] << 8) | buf[2]; if (buf[0] == 0x20 || buf[0] == 0x23) { //instance-of & new-array flag_str = R_ASM_GET_NAME (a, 'c', vC); if (flag_str) { sprintf (str, " v%i, v%i, %s", vA, vB, flag_str); } else { sprintf (str, " v%i, v%i, class+%i", vA, vB, vC); } } else { flag_str = R_ASM_GET_NAME (a, 'f', vC); if (flag_str) { sprintf (str, " v%i, v%i, %s", vA, vB, flag_str); } else { sprintf (str, " v%i, v%i, field+%i", vA, vB, vC); } } strasm = r_str_concat (strasm, str); break; case fmtopvAAtBBBBBBBB: vA = (int) buf[1]; vB = (int) (buf[5] | (buf[4] << 8) | (buf[3] << 16) | (buf[2] << 24)); offset = R_ASM_GET_OFFSET (a, 's', vB); if (offset == -1) { sprintf (str, " v%i, string+%i", vA, vB); } else { sprintf (str, " v%i, 0x%"PFMT64x, vA, offset); } strasm = r_str_concat (strasm, str); break; case fmtopvCCCCmBBBB: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; vC = (buf[5] << 8) | buf[4]; if (buf[0] == 0x25) { // filled-new-array/range flag_str = R_ASM_GET_NAME (a, 'c', vB); if (flag_str) { sprintf (str, " {v%i..v%i}, %s", vC, vC + vA - 1, flag_str); } else { sprintf (str, " {v%i..v%i}, class+%i", vC, vC + vA - 1, vB); } } else { flag_str = R_ASM_GET_NAME (a, 'm', vB); if (flag_str) { sprintf (str, " {v%i..v%i}, %s", vC, vC + vA - 1, flag_str); } else { sprintf (str, " {v%i..v%i}, method+%i", vC, vC + vA - 1, vB); } } strasm = r_str_concat (strasm, str); break; case fmtopvXtBBBB: vA = (int) (buf[1] & 0xf0) >> 4; vB = (buf[3] << 8) | buf[2]; switch (vA) { case 1: sprintf (str, " {v%i}", buf[4] & 0x0f); break; case 2: sprintf (str, " {v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4); break; case 3: sprintf (str, " {v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f); break; case 4: sprintf (str, " {v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4); break; case 5: sprintf (str, " {v%i, v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4, buf[1] & 0x0f); // TOODO: recheck this break; default: sprintf (str, " {}"); } strasm = r_str_concat (strasm, str); if (buf[0] == 0x24) { // filled-new-array flag_str = R_ASM_GET_NAME (a, 'c', vB); if (flag_str) { sprintf (str, ", %s ; 0x%x", flag_str, vB); } else { sprintf (str, ", class+%i", vB); } } else { flag_str = R_ASM_GET_NAME (a, 'm', vB); if (flag_str) { sprintf (str, ", %s ; 0x%x", flag_str, vB); } else { sprintf (str, ", method+%i", vB); } } strasm = r_str_concat (strasm, str); break; case fmtoptinvokeI: // Any opcode has this formats case fmtoptinvokeIR: case fmt00: default: strcpy (op->buf_asm, "invalid "); free (strasm); strasm = NULL; size = 2; } if (strasm) { strncpy (op->buf_asm, strasm, sizeof (op->buf_asm) - 1); op->buf_asm[sizeof (op->buf_asm) - 1] = 0; } else { //op->buf_asm[0] = 0; strcpy (op->buf_asm , "invalid"); } } else if (len > 0) { strcpy (op->buf_asm, "invalid "); op->size = len; size = len; } op->payload = payload; size += payload; // XXX // align to 2 op->size = size; free (strasm); return size; }
nan
null
10,831
15765353407801862567352178106566751113
429
Fix #6885 - oob write in dalvik_disassemble
null
radare2
f17bfd9f1da05f30f23a4dd05e9d2363e1406948
1
static int opmov(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; st64 offset = 0; int mod = 0; int base = 0; int rex = 0; ut64 immediate = 0; if (op->operands[1].type & OT_CONSTANT) { if (!op->operands[1].is_good_flag) { return -1; } if (op->operands[1].immediate == -1) { return -1; } immediate = op->operands[1].immediate * op->operands[1].sign; if (op->operands[0].type & OT_GPREG && !(op->operands[0].type & OT_MEMORY)) { if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD))) { if (!(op->operands[1].type & OT_CONSTANT) && op->operands[1].extended) { data[l++] = 0x49; } else { data[l++] = 0x48; } } else if (op->operands[0].extended) { data[l++] = 0x41; } if (op->operands[0].type & OT_WORD) { if (a->bits > 16) { data[l++] = 0x66; } } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xb0 | op->operands[0].reg; data[l++] = immediate; } else { if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD)) && immediate < UT32_MAX) { data[l++] = 0xc7; data[l++] = 0xc0 | op->operands[0].reg; } else { data[l++] = 0xb8 | op->operands[0].reg; } data[l++] = immediate; data[l++] = immediate >> 8; if (!(op->operands[0].type & OT_WORD)) { data[l++] = immediate >> 16; data[l++] = immediate >> 24; } if (a->bits == 64 && immediate > UT32_MAX) { data[l++] = immediate >> 32; data[l++] = immediate >> 40; data[l++] = immediate >> 48; data[l++] = immediate >> 56; } } } else if (op->operands[0].type & OT_MEMORY) { if (!op->operands[0].explicit_size) { if (op->operands[0].type & OT_GPREG) { ((Opcode *)op)->operands[0].dest_size = op->operands[0].reg_size; } else { return -1; } } int dest_bits = 8 * ((op->operands[0].dest_size & ALL_SIZE) >> OPSIZE_SHIFT); int reg_bits = 8 * ((op->operands[0].reg_size & ALL_SIZE) >> OPSIZE_SHIFT); int offset = op->operands[0].offset * op->operands[0].offset_sign; //addr_size_override prefix bool use_aso = false; if (reg_bits < a->bits) { use_aso = true; } //op_size_override prefix bool use_oso = false; if (dest_bits == 16) { use_oso = true; } bool rip_rel = op->operands[0].regs[0] == X86R_RIP; //rex prefix int rex = 1 << 6; bool use_rex = false; if (dest_bits == 64) { //W field use_rex = true; rex |= 1 << 3; } if (op->operands[0].extended) { //B field use_rex = true; rex |= 1; } //opcode selection int opcode; if (dest_bits == 8) { opcode = 0xc6; } else { opcode = 0xc7; } //modrm and SIB selection int modrm = 0; int mod; int reg = 0; int rm; bool use_sib = false; int sib; //mod if (offset == 0) { mod = 0; } else if (offset < 128 && offset > -129) { mod = 1; } else { mod = 2; } if (reg_bits == 16) { if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) { rm = B0000; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) { rm = B0001; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) { rm = B0010; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) { rm = B0011; } else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) { rm = B0100; } else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) { rm = B0101; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) { rm = B0111; } else { //TODO allow for displacement only when parser is reworked return -1; } modrm = (mod << 6) | (reg << 3) | rm; } else { //rm if (op->operands[0].extended) { rm = op->operands[0].reg; } else { rm = op->operands[0].regs[0]; } //[epb] alone is illegal, so we need to fake a [ebp+0] if (rm == 5 && mod == 0) { mod = 1; } //sib int index = op->operands[0].regs[1]; int scale = getsib(op->operands[0].scale[1]); if (index != -1) { use_sib = true; sib = (scale << 6) | (index << 3) | rm; } else if (rm == 4) { use_sib = true; sib = 0x24; } if (use_sib) { rm = B0100; } if (rip_rel) { modrm = (B0000 << 6) | (reg << 3) | B0101; sib = (scale << 6) | (B0100 << 3) | B0101; } else { modrm = (mod << 6) | (reg << 3) | rm; } } //build the final result if (use_aso) { data[l++] = 0x67; } if (use_oso) { data[l++] = 0x66; } if (use_rex) { data[l++] = rex; } data[l++] = opcode; data[l++] = modrm; if (use_sib) { data[l++] = sib; } //offset if (mod == 1) { data[l++] = offset; } else if (reg_bits == 16 && mod == 2) { data[l++] = offset; data[l++] = offset >> 8; } else if (mod == 2 || rip_rel) { data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } //immediate int byte; for (byte = 0; byte < dest_bits && byte < 32; byte += 8) { data[l++] = (immediate >> byte); } } } else if (op->operands[1].type & OT_REGALL && !(op->operands[1].type & OT_MEMORY)) { if (op->operands[0].type & OT_CONSTANT) { return -1; } if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG && op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { return -1; } // Check reg sizes match if (op->operands[0].type & OT_REGTYPE && op->operands[1].type & OT_REGTYPE) { if (!((op->operands[0].type & ALL_SIZE) & (op->operands[1].type & ALL_SIZE))) { return -1; } } if (a->bits == 64) { if (op->operands[0].extended) { rex = 1; } if (op->operands[1].extended) { rex += 4; } if (op->operands[1].type & OT_QWORD) { if (!(op->operands[0].type & OT_QWORD)) { data[l++] = 0x67; data[l++] = 0x48; } } if (op->operands[1].type & OT_QWORD && op->operands[0].type & OT_QWORD) { data[l++] = 0x48 | rex; } if (op->operands[1].type & OT_DWORD && op->operands[0].type & OT_DWORD) { data[l++] = 0x40 | rex; } } else if (op->operands[0].extended && op->operands[1].extended) { data[l++] = 0x45; } offset = op->operands[0].offset * op->operands[0].offset_sign; if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { data[l++] = 0x8c; } else { if (op->operands[0].type & OT_WORD) { data[l++] = 0x66; } data[l++] = (op->operands[0].type & OT_BYTE) ? 0x88 : 0x89; } if (op->operands[0].scale[0] > 1) { data[l++] = op->operands[1].reg << 3 | 4; data[l++] = getsib (op->operands[0].scale[0]) << 6 | op->operands[0].regs[0] << 3 | 5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; return l; } if (!(op->operands[0].type & OT_MEMORY)) { if (op->operands[0].reg == X86R_UNDEFINED || op->operands[1].reg == X86R_UNDEFINED) { return -1; } mod = 0x3; data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].reg; } else if (op->operands[0].regs[0] == X86R_UNDEFINED) { data[l++] = op->operands[1].reg << 3 | 0x5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } else { if (op->operands[0].type & OT_MEMORY) { if (op->operands[0].regs[1] != X86R_UNDEFINED) { data[l++] = op->operands[1].reg << 3 | 0x4; data[l++] = op->operands[0].regs[1] << 3 | op->operands[0].regs[0]; return l; } if (offset) { mod = (offset > 128 || offset < -129) ? 0x2 : 0x1; } if (op->operands[0].regs[0] == X86R_EBP) { mod = 0x2; } data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].regs[0]; if (op->operands[0].regs[0] == X86R_ESP) { data[l++] = 0x24; } if (offset) { data[l++] = offset; } if (mod == 2) { // warning C4293: '>>': shift count negative or too big, undefined behavior data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } } else if (op->operands[1].type & OT_MEMORY) { if (op->operands[0].type & OT_MEMORY) { return -1; } offset = op->operands[1].offset * op->operands[1].offset_sign; if (op->operands[0].reg == X86R_EAX && op->operands[1].regs[0] == X86R_UNDEFINED) { if (a->bits == 64) { data[l++] = 0x48; } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xa0; } else { data[l++] = 0xa1; } data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; if (a->bits == 64) { data[l++] = offset >> 32; data[l++] = offset >> 40; data[l++] = offset >> 48; data[l++] = offset >> 54; } return l; } if (op->operands[0].type & OT_BYTE && a->bits == 64 && op->operands[1].regs[0]) { if (op->operands[1].regs[0] >= X86R_R8 && op->operands[0].reg < 4) { data[l++] = 0x41; data[l++] = 0x8a; data[l++] = op->operands[0].reg << 3 | (op->operands[1].regs[0] - 8); return l; } return -1; } if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { if (op->operands[1].scale[0] == 0) { return -1; } data[l++] = SEG_REG_PREFIXES[op->operands[1].regs[0]]; data[l++] = 0x8b; data[l++] = op->operands[0].reg << 3 | 0x5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; return l; } if (a->bits == 64) { if (op->operands[0].type & OT_QWORD) { if (!(op->operands[1].type & OT_QWORD)) { if (op->operands[1].regs[0] != -1) { data[l++] = 0x67; } data[l++] = 0x48; } } else if (op->operands[1].type & OT_DWORD) { data[l++] = 0x44; } else if (!(op->operands[1].type & OT_QWORD)) { data[l++] = 0x67; } if (op->operands[1].type & OT_QWORD && op->operands[0].type & OT_QWORD) { data[l++] = 0x48; } } if (op->operands[0].type & OT_WORD) { data[l++] = 0x66; data[l++] = op->operands[1].type & OT_BYTE ? 0x8a : 0x8b; } else { data[l++] = (op->operands[1].type & OT_BYTE || op->operands[0].type & OT_BYTE) ? 0x8a : 0x8b; } if (op->operands[1].regs[0] == X86R_UNDEFINED) { if (a->bits == 64) { data[l++] = op->operands[0].reg << 3 | 0x4; data[l++] = 0x25; } else { data[l++] = op->operands[0].reg << 3 | 0x5; } data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } else { if (op->operands[1].scale[0] > 1) { data[l++] = op->operands[0].reg << 3 | 4; if (op->operands[1].scale[0] >= 2) { base = 5; } if (base) { data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | base; } else { data[l++] = getsib (op->operands[1].scale[0]) << 3 | op->operands[1].regs[0]; } if (offset || base) { data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } return l; } if (op->operands[1].regs[1] != X86R_UNDEFINED) { data[l++] = op->operands[0].reg << 3 | 0x4; data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0]; return l; } if (offset || op->operands[1].regs[0] == X86R_EBP) { mod = 0x2; if (op->operands[1].offset > 127) { mod = 0x4; } } if (a->bits == 64 && offset && op->operands[0].type & OT_QWORD) { if (op->operands[1].regs[0] == X86R_RIP) { data[l++] = 0x5; } else { if (op->operands[1].offset > 127) { data[l++] = 0x80 | op->operands[0].reg << 3 | op->operands[1].regs[0]; } else { data[l++] = 0x40 | op->operands[1].regs[0]; } } if (op->operands[1].offset > 127) { mod = 0x1; } } else { if (op->operands[1].regs[0] == X86R_EIP && (op->operands[0].type & OT_DWORD)) { data[l++] = 0x0d; } else if (op->operands[1].regs[0] == X86R_RIP && (op->operands[0].type & OT_QWORD)) { data[l++] = 0x05; } else { data[l++] = mod << 5 | op->operands[0].reg << 3 | op->operands[1].regs[0]; } } if (op->operands[1].regs[0] == X86R_ESP) { data[l++] = 0x24; } if (mod >= 0x2) { data[l++] = offset; if (op->operands[1].offset > 128 || op->operands[1].regs[0] == X86R_EIP) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } else if (a->bits == 64 && (offset || op->operands[1].regs[0] == X86R_RIP)) { data[l++] = offset; if (op->operands[1].offset > 127 || op->operands[1].regs[0] == X86R_RIP) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } } return l; }
nan
null
10,832
40973769706127207321712838564227350185
476
Fix #12242 - Crash in x86.nz assembler (#12266)
null
php-src
61cdd1255d5b9c8453be71aacbbf682796ac77d4
1
SPL_METHOD(SplObjectStorage, unserialize) { spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis()); char *buf; size_t buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; zval entry, inf; zval *pcount, *pmembers; spl_SplObjectStorageElement *element; zend_long count; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { return; } /* storage */ s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (*p!= 'x' || *++p != ':') { goto outexcept; } ++p; pcount = var_tmp_var(&var_hash); if (!php_var_unserialize(pcount, &p, s + buf_len, &var_hash) || Z_TYPE_P(pcount) != IS_LONG) { goto outexcept; } --p; /* for ';' */ count = Z_LVAL_P(pcount); while (count-- > 0) { spl_SplObjectStorageElement *pelement; zend_string *hash; if (*p != ';') { goto outexcept; } ++p; if(*p != 'O' && *p != 'C' && *p != 'r') { goto outexcept; } /* store reference to allow cross-references between different elements */ if (!php_var_unserialize(&entry, &p, s + buf_len, &var_hash)) { goto outexcept; } if (Z_TYPE(entry) != IS_OBJECT) { zval_ptr_dtor(&entry); goto outexcept; } if (*p == ',') { /* new version has inf */ ++p; if (!php_var_unserialize(&inf, &p, s + buf_len, &var_hash)) { zval_ptr_dtor(&entry); goto outexcept; } } else { ZVAL_UNDEF(&inf); } hash = spl_object_storage_get_hash(intern, getThis(), &entry); if (!hash) { zval_ptr_dtor(&entry); zval_ptr_dtor(&inf); goto outexcept; } pelement = spl_object_storage_get(intern, hash); spl_object_storage_free_hash(intern, hash); if (pelement) { if (!Z_ISUNDEF(pelement->inf)) { var_push_dtor(&var_hash, &pelement->inf); } if (!Z_ISUNDEF(pelement->obj)) { var_push_dtor(&var_hash, &pelement->obj); } } element = spl_object_storage_attach(intern, getThis(), &entry, Z_ISUNDEF(inf)?NULL:&inf); var_replace(&var_hash, &entry, &element->obj); var_replace(&var_hash, &inf, &element->inf); zval_ptr_dtor(&entry); ZVAL_UNDEF(&entry); zval_ptr_dtor(&inf); ZVAL_UNDEF(&inf); } if (*p != ';') { goto outexcept; } ++p; /* members */ if (*p!= 'm' || *++p != ':') { goto outexcept; } ++p; pmembers = var_tmp_var(&var_hash); if (!php_var_unserialize(pmembers, &p, s + buf_len, &var_hash) || Z_TYPE_P(pmembers) != IS_ARRAY) { goto outexcept; } /* copy members */ object_properties_load(&intern->std, Z_ARRVAL_P(pmembers)); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return; outexcept: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Error at offset %pd of %d bytes", (zend_long)((char*)p - buf), buf_len); return; } /* }}} */
nan
null
10,833
91704803847212603569034032105262813044
120
Fix bug #73257 and bug #73258 - SplObjectStorage unserialize allows use of non-object as key
null
libpcap
484d60cbf7ca4ec758c3cbb8a82d68b244a78d58
1
daemon_AuthUserPwd(char *username, char *password, char *errbuf) { #ifdef _WIN32 /* * Warning: the user which launches the process must have the * SE_TCB_NAME right. * This corresponds to have the "Act as part of the Operating System" * turned on (administrative tools, local security settings, local * policies, user right assignment) * However, it seems to me that if you run it as a service, this * right should be provided by default. * * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE, * which merely indicates that the user name or password is * incorrect, not whether it's the user name or the password * that's incorrect, so a client that's trying to brute-force * accounts doesn't know whether it's the user name or the * password that's incorrect, so it doesn't know whether to * stop trying to log in with a given user name and move on * to another user name. */ HANDLE Token; if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "LogonUser() failed"); return -1; } // This call should change the current thread to the selected user. // I didn't test it. if (ImpersonateLoggedOnUser(Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), "ImpersonateLoggedOnUser() failed"); CloseHandle(Token); return -1; } CloseHandle(Token); return 0; #else /* * See * * http://www.unixpapa.com/incnote/passwd.html * * We use the Solaris/Linux shadow password authentication if * we have getspnam(), otherwise we just do traditional * authentication, which, on some platforms, might work, even * with shadow passwords, if we're running as root. Traditional * authenticaion won't work if we're not running as root, as * I think these days all UN*Xes either won't return the password * at all with getpwnam() or will only do so if you're root. * * XXX - perhaps what we *should* be using is PAM, if we have * it. That might hide all the details of username/password * authentication, whether it's done with a visible-to-root- * only password database or some other authentication mechanism, * behind its API. */ struct passwd *user; char *user_password; #ifdef HAVE_GETSPNAM struct spwd *usersp; #endif char *crypt_password; // This call is needed to get the uid if ((user = getpwnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } #ifdef HAVE_GETSPNAM // This call is needed to get the password; otherwise 'x' is returned if ((usersp = getspnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } user_password = usersp->sp_pwdp; #else /* * XXX - what about other platforms? * The unixpapa.com page claims this Just Works on *BSD if you're * running as root - it's from 2000, so it doesn't indicate whether * macOS (which didn't come out until 2001, under the name Mac OS * X) behaves like the *BSDs or not, and might also work on AIX. * HP-UX does something else. * * Again, hopefully PAM hides all that. */ user_password = user->pw_passwd; #endif crypt_password = crypt(password, user_password); if (crypt_password == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed"); return -1; } if (strcmp(user_password, crypt_password) != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect"); return -1; } if (setuid(user->pw_uid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setuid"); return -1; } /* if (setgid(user->pw_gid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setgid"); return -1; } */ return 0; #endif }
nan
null
10,834
143271537862841354895570818884112371953
129
On UN*X, don't tell the client why authentication failed. "no such user" tells the client that the user ID isn't valid and, therefore, that it needn't bother trying to do password cracking for that user ID; just saying that the authentication failed dosn't give them that hint. This resolves the third problem in Include Security issue F11: [libpcap] Remote Packet Capture Daemon Multiple Authentication Improvements. The Windows LogonUser() API returns ERROR_LOGON_FAILURE for both cases, so the Windows code doesn't have this issue. Just return the same "Authentication failed" message on Windows to the user. For various authentication failures *other* than "no such user" and "password not valid", log a message, as there's a problem that may need debugging. We don't need to tell the end user what the problem is, as they may not bother reporting it and, even if they do, they may not give the full error message.
null
qemu
9878d173f574df74bde0ff50b2f81009fbee81bb
1
static void vmxnet3_activate_device(VMXNET3State *s) { int i; static const uint32_t VMXNET3_DEF_TX_THRESHOLD = 1; hwaddr qdescr_table_pa; uint64_t pa; uint32_t size; /* Verify configuration consistency */ if (!vmxnet3_verify_driver_magic(s->drv_shmem)) { VMW_ERPRN("Device configuration received from driver is invalid"); return; } vmxnet3_adjust_by_guest_type(s); vmxnet3_update_features(s); vmxnet3_update_pm_state(s); vmxnet3_setup_rx_filtering(s); /* Cache fields from shared memory */ s->mtu = VMXNET3_READ_DRV_SHARED32(s->drv_shmem, devRead.misc.mtu); VMW_CFPRN("MTU is %u", s->mtu); s->max_rx_frags = VMXNET3_READ_DRV_SHARED16(s->drv_shmem, devRead.misc.maxNumRxSG); if (s->max_rx_frags == 0) { s->max_rx_frags = 1; } VMW_CFPRN("Max RX fragments is %u", s->max_rx_frags); s->event_int_idx = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.eventIntrIdx); assert(vmxnet3_verify_intx(s, s->event_int_idx)); VMW_CFPRN("Events interrupt line is %u", s->event_int_idx); s->auto_int_masking = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.autoMask); VMW_CFPRN("Automatic interrupt masking is %d", (int)s->auto_int_masking); s->txq_num = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numTxQueues); s->rxq_num = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues); VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num); assert(s->txq_num <= VMXNET3_DEVICE_MAX_TX_QUEUES); qdescr_table_pa = VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA); VMW_CFPRN("TX queues descriptors table is at 0x%" PRIx64, qdescr_table_pa); /* * Worst-case scenario is a packet that holds all TX rings space so * we calculate total size of all TX rings for max TX fragments number */ s->max_tx_frags = 0; /* TX queues */ for (i = 0; i < s->txq_num; i++) { hwaddr qdescr_pa = qdescr_table_pa + i * sizeof(struct Vmxnet3_TxQueueDesc); /* Read interrupt number for this TX queue */ s->txq_descr[i].intr_idx = VMXNET3_READ_TX_QUEUE_DESCR8(qdescr_pa, conf.intrIdx); assert(vmxnet3_verify_intx(s, s->txq_descr[i].intr_idx)); VMW_CFPRN("TX Queue %d interrupt: %d", i, s->txq_descr[i].intr_idx); /* Read rings memory locations for TX queues */ pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.txRingBasePA); size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.txRingSize); vmxnet3_ring_init(&s->txq_descr[i].tx_ring, pa, size, sizeof(struct Vmxnet3_TxDesc), false); VMXNET3_RING_DUMP(VMW_CFPRN, "TX", i, &s->txq_descr[i].tx_ring); s->max_tx_frags += size; /* TXC ring */ pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.compRingBasePA); size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.compRingSize); vmxnet3_ring_init(&s->txq_descr[i].comp_ring, pa, size, sizeof(struct Vmxnet3_TxCompDesc), true); VMXNET3_RING_DUMP(VMW_CFPRN, "TXC", i, &s->txq_descr[i].comp_ring); s->txq_descr[i].tx_stats_pa = qdescr_pa + offsetof(struct Vmxnet3_TxQueueDesc, stats); memset(&s->txq_descr[i].txq_stats, 0, sizeof(s->txq_descr[i].txq_stats)); /* Fill device-managed parameters for queues */ VMXNET3_WRITE_TX_QUEUE_DESCR32(qdescr_pa, ctrl.txThreshold, VMXNET3_DEF_TX_THRESHOLD); } /* Preallocate TX packet wrapper */ VMW_CFPRN("Max TX fragments is %u", s->max_tx_frags); vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr); vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr); /* Read rings memory locations for RX queues */ for (i = 0; i < s->rxq_num; i++) { int j; hwaddr qd_pa = qdescr_table_pa + s->txq_num * sizeof(struct Vmxnet3_TxQueueDesc) + i * sizeof(struct Vmxnet3_RxQueueDesc); /* Read interrupt number for this RX queue */ s->rxq_descr[i].intr_idx = VMXNET3_READ_TX_QUEUE_DESCR8(qd_pa, conf.intrIdx); assert(vmxnet3_verify_intx(s, s->rxq_descr[i].intr_idx)); VMW_CFPRN("RX Queue %d interrupt: %d", i, s->rxq_descr[i].intr_idx); /* Read rings memory locations */ for (j = 0; j < VMXNET3_RX_RINGS_PER_QUEUE; j++) { /* RX rings */ pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.rxRingBasePA[j]); size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.rxRingSize[j]); vmxnet3_ring_init(&s->rxq_descr[i].rx_ring[j], pa, size, sizeof(struct Vmxnet3_RxDesc), false); VMW_CFPRN("RX queue %d:%d: Base: %" PRIx64 ", Size: %d", i, j, pa, size); } /* RXC ring */ pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.compRingBasePA); size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.compRingSize); vmxnet3_ring_init(&s->rxq_descr[i].comp_ring, pa, size, sizeof(struct Vmxnet3_RxCompDesc), true); VMW_CFPRN("RXC queue %d: Base: %" PRIx64 ", Size: %d", i, pa, size); s->rxq_descr[i].rx_stats_pa = qd_pa + offsetof(struct Vmxnet3_RxQueueDesc, stats); memset(&s->rxq_descr[i].rxq_stats, 0, sizeof(s->rxq_descr[i].rxq_stats)); } vmxnet3_validate_interrupts(s); /* Make sure everything is in place before device activation */ smp_wmb(); vmxnet3_reset_mac(s); s->device_active = true; }
nan
null
10,835
249334075610751949339901810584484827678
151
vmxnet3: validate queues configuration coming from guest CVE-2013-4544 Signed-off-by: Dmitry Fleytman <dmitry@daynix.com> Reported-by: Michael S. Tsirkin <mst@redhat.com> Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Reviewed-by: Dr. David Alan Gilbert <dgilbert@redhat.com> Message-id: 1396604722-11902-3-git-send-email-dmitry@daynix.com Signed-off-by: Peter Maydell <peter.maydell@linaro.org>
null
Little-CMS
5ca71a7bc18b6897ab21d815d15e218e204581e2
1
void *Type_MLU_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsMLU* mlu; cmsUInt32Number Count, RecLen, NumOfWchar; cmsUInt32Number SizeOfHeader; cmsUInt32Number Len, Offset; cmsUInt32Number i; wchar_t* Block; cmsUInt32Number BeginOfThisString, EndOfThisString, LargestPosition; *nItems = 0; if (!_cmsReadUInt32Number(io, &Count)) return NULL; if (!_cmsReadUInt32Number(io, &RecLen)) return NULL; if (RecLen != 12) { cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "multiLocalizedUnicodeType of len != 12 is not supported."); return NULL; } mlu = cmsMLUalloc(self ->ContextID, Count); if (mlu == NULL) return NULL; mlu ->UsedEntries = Count; SizeOfHeader = 12 * Count + sizeof(_cmsTagBase); LargestPosition = 0; for (i=0; i < Count; i++) { if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Language)) goto Error; if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Country)) goto Error; // Now deal with Len and offset. if (!_cmsReadUInt32Number(io, &Len)) goto Error; if (!_cmsReadUInt32Number(io, &Offset)) goto Error; // Check for overflow if (Offset < (SizeOfHeader + 8)) goto Error; // True begin of the string BeginOfThisString = Offset - SizeOfHeader - 8; // Ajust to wchar_t elements mlu ->Entries[i].Len = (Len * sizeof(wchar_t)) / sizeof(cmsUInt16Number); mlu ->Entries[i].StrW = (BeginOfThisString * sizeof(wchar_t)) / sizeof(cmsUInt16Number); // To guess maximum size, add offset + len EndOfThisString = BeginOfThisString + Len; if (EndOfThisString > LargestPosition) LargestPosition = EndOfThisString; } // Now read the remaining of tag and fill all strings. Subtract the directory SizeOfTag = (LargestPosition * sizeof(wchar_t)) / sizeof(cmsUInt16Number); if (SizeOfTag == 0) { Block = NULL; NumOfWchar = 0; } else { Block = (wchar_t*) _cmsMalloc(self ->ContextID, SizeOfTag); if (Block == NULL) goto Error; NumOfWchar = SizeOfTag / sizeof(wchar_t); if (!_cmsReadWCharArray(io, NumOfWchar, Block)) goto Error; } mlu ->MemPool = Block; mlu ->PoolSize = SizeOfTag; mlu ->PoolUsed = SizeOfTag; *nItems = 1; return (void*) mlu; Error: if (mlu) cmsMLUfree(mlu); return NULL; }
nan
null
10,836
11487822218315489887266449028764992492
80
Added an extra check to MLU bounds Thanks to Ibrahim el-sayed for spotting the bug
null
WavPack
26cb47f99d481ad9b93eeff80d26e6b63bbd7e15
1
int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif // loop through all elements of the wave64 header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); // if it's the format chunk, we want to get some info out of there and // make sure it's a .wav file we can handle if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
nan
null
10,837
52732810850628604270911662724343097776
228
issue #30 issue #31 issue #32: no multiple format chunks in WAV or W64
null
WavPack
26cb47f99d481ad9b93eeff80d26e6b63bbd7e15
1
int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0; int64_t total_samples = 0, infilesize; RiffChunkHeader riff_chunk_header; ChunkHeader chunk_header; WaveHeader WaveHeader; DS64Chunk ds64_chunk; uint32_t bcount; CLEAR (WaveHeader); CLEAR (ds64_chunk); infilesize = DoGetFileSize (infile); if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) { error_line ("can't handle .WAV files larger than 4 GB (non-standard)!"); return WAVPACK_SOFT_ERROR; } memcpy (&riff_chunk_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) || bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } // loop through all elements of the RIFF wav header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) || bcount != sizeof (ChunkHeader)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat); if (!strncmp (chunk_header.ckID, "ds64", 4)) { if (chunk_header.ckSize < sizeof (DS64Chunk) || !DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) || bcount != sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } got_ds64 = 1; WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat); if (debug_logging_mode) error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d", (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64, (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength); if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } while (ds64_chunk.tableLength--) { CS64Chunk cs64_chunk; if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) || bcount != sizeof (CS64Chunk) || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } } } else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and int supported = TRUE, format; // make sure it's a .wav file we can handle if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .WAV format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this WAV file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else if (config->float_norm_exp) error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)", config->float_norm_exp - 126, 150 - config->float_norm_exp); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ? ds64_chunk.dataSize64 : chunk_header.ckSize; if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required) error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) { error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (config->qmode & QMODE_IGNORE_LENGTH) { if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { total_samples = data_chunk_size / WaveHeader.BlockAlign; if (got_ds64 && total_samples != ds64_chunk.sampleCount64) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (!total_samples) { error_line ("this .WAV file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
nan
null
10,838
152045847845484902423902962557831237202
269
issue #30 issue #31 issue #32: no multiple format chunks in WAV or W64
null
FFmpeg
95556e27e2c1d56d9e18f5db34d6f756f3011148
1
static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { //info->num_ind_sub++; avpriv_request_sample(track->par, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } else { if (hdr->substreamid != 0) { avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; }
nan
null
10,839
194781423137917081982644774523493158518
139
avformat/movenc: Do not pass AVCodecParameters in avpriv_request_sample Fixes: out of array read Fixes: ffmpeg_crash_8.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>
null
dbus
954d75b2b64e4799f360d2a6bf9cff6d9fee37e7
1
_dbus_printf_string_upper_bound (const char *format, va_list args) { char static_buf[1024]; int bufsize = sizeof (static_buf); int len; len = vsnprintf (static_buf, bufsize, format, args); /* If vsnprintf() returned non-negative, then either the string fits in * static_buf, or this OS has the POSIX and C99 behaviour where vsnprintf * returns the number of characters that were needed, or this OS returns the * truncated length. * * We ignore the possibility that snprintf might just ignore the length and * overrun the buffer (64-bit Solaris 7), because that's pathological. * If your libc is really that bad, come back when you have a better one. */ if (len == bufsize) { /* This could be the truncated length (Tru64 and IRIX have this bug), * or the real length could be coincidentally the same. Which is it? * If vsnprintf returns the truncated length, we'll go to the slow * path. */ if (vsnprintf (static_buf, 1, format, args) == 1) len = -1; } /* If vsnprintf() returned negative, we have to do more work. * HP-UX returns negative. */ while (len < 0) { char *buf; bufsize *= 2; buf = dbus_malloc (bufsize); if (buf == NULL) return -1; len = vsnprintf (buf, bufsize, format, args); dbus_free (buf); /* If the reported length is exactly the buffer size, round up to the * next size, in case vsnprintf has been returning the truncated * length */ if (len == bufsize) len = -1; } return len; }
nan
null
10,841
222824617731331632330798336236698565961
52
CVE-2013-2168: _dbus_printf_string_upper_bound: copy the va_list for each use Using a va_list more than once is non-portable: it happens to work under the ABI of (for instance) x86 Linux, but not x86-64 Linux. This led to _dbus_printf_string_upper_bound() crashing if it should have returned exactly 1024 bytes. Many system services can be induced to process a caller-controlled string in ways that end up using _dbus_printf_string_upper_bound(), so this is a denial of service. Reviewed-by: Thiago Macieira <thiago@kde.org>
null
samba
b000da128b5fb519d2d3f2e7fd20e4a25b7dae7d
0
static bool check_rodc_critical_attribute(struct ldb_message *msg) { uint32_t schemaFlagsEx, searchFlags, rodc_filtered_flags; schemaFlagsEx = ldb_msg_find_attr_as_uint(msg, "schemaFlagsEx", 0); searchFlags = ldb_msg_find_attr_as_uint(msg, "searchFlags", 0); rodc_filtered_flags = (SEARCH_FLAG_RODC_ATTRIBUTE | SEARCH_FLAG_CONFIDENTIAL); if ((schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) && ((searchFlags & rodc_filtered_flags) == rodc_filtered_flags)) { return true; } else { return false; } }
CWE-264
0
10,842
205557571549339785765100376107361633035
null
null
null
samba
b000da128b5fb519d2d3f2e7fd20e4a25b7dae7d
0
static int samldb_add_entry(struct samldb_ctx *ac) { struct ldb_context *ldb; struct ldb_request *req; int ret; ldb = ldb_module_get_ctx(ac->module); ret = ldb_build_add_req(&req, ldb, ac, ac->msg, ac->req->controls, ac, samldb_add_entry_callback, ac->req); LDB_REQ_SET_LOCATION(req); if (ret != LDB_SUCCESS) { return ret; } return ldb_next_request(ac->module, req); }
CWE-264
1
10,843
204994596923949149676904363438484366261
null
null
null
samba
b000da128b5fb519d2d3f2e7fd20e4a25b7dae7d
0
static int samldb_add_entry_callback(struct ldb_request *req, struct ldb_reply *ares) { struct ldb_context *ldb; struct samldb_ctx *ac; int ret; ac = talloc_get_type(req->context, struct samldb_ctx); ldb = ldb_module_get_ctx(ac->module); if (!ares) { return ldb_module_done(ac->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR); } if (ares->type == LDB_REPLY_REFERRAL) { return ldb_module_send_referral(ac->req, ares->referral); } if (ares->error != LDB_SUCCESS) { return ldb_module_done(ac->req, ares->controls, ares->response, ares->error); } if (ares->type != LDB_REPLY_DONE) { ldb_asprintf_errstring(ldb, "Invalid LDB reply type %d", ares->type); return ldb_module_done(ac->req, NULL, NULL, LDB_ERR_OPERATIONS_ERROR); } /* The caller may wish to get controls back from the add */ ac->ares = talloc_steal(ac, ares); ret = samldb_next_step(ac); if (ret != LDB_SUCCESS) { return ldb_module_done(ac->req, NULL, NULL, ret); } return ret; }
CWE-264
2
10,844
79521508164134761404721670607271694040
null
null
null
samba
b000da128b5fb519d2d3f2e7fd20e4a25b7dae7d
0
static int samldb_add_handle_msDS_IntId(struct samldb_ctx *ac) { int ret; bool id_exists; uint32_t msds_intid; int32_t system_flags; struct ldb_context *ldb; struct ldb_result *ldb_res; struct ldb_dn *schema_dn; struct samldb_msds_intid_persistant *msds_intid_struct; struct dsdb_schema *schema; ldb = ldb_module_get_ctx(ac->module); schema_dn = ldb_get_schema_basedn(ldb); /* replicated update should always go through */ if (ldb_request_get_control(ac->req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) { return LDB_SUCCESS; } /* msDS-IntId is handled by system and should never be * passed by clients */ if (ldb_msg_find_element(ac->msg, "msDS-IntId")) { return LDB_ERR_UNWILLING_TO_PERFORM; } /* do not generate msDS-IntId if Relax control is passed */ if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) { return LDB_SUCCESS; } /* check Functional Level */ if (dsdb_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003) { return LDB_SUCCESS; } /* check systemFlags for SCHEMA_BASE_OBJECT flag */ system_flags = ldb_msg_find_attr_as_int(ac->msg, "systemFlags", 0); if (system_flags & SYSTEM_FLAG_SCHEMA_BASE_OBJECT) { return LDB_SUCCESS; } schema = dsdb_get_schema(ldb, NULL); if (!schema) { ldb_debug_set(ldb, LDB_DEBUG_FATAL, "samldb_schema_info_update: no dsdb_schema loaded"); DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb))); return ldb_operr(ldb); } msds_intid_struct = (struct samldb_msds_intid_persistant*) ldb_get_opaque(ldb, SAMLDB_MSDS_INTID_OPAQUE); if (!msds_intid_struct) { msds_intid_struct = talloc(ldb, struct samldb_msds_intid_persistant); /* Generate new value for msDs-IntId * Value should be in 0x80000000..0xBFFFFFFF range */ msds_intid = generate_random() % 0X3FFFFFFF; msds_intid += 0x80000000; msds_intid_struct->msds_intid = msds_intid; msds_intid_struct->usn = schema->loaded_usn; DEBUG(2, ("No samldb_msds_intid_persistant struct, allocating a new one\n")); } else { msds_intid = msds_intid_struct->msds_intid; } /* probe id values until unique one is found */ do { uint64_t current_usn; msds_intid++; if (msds_intid > 0xBFFFFFFF) { msds_intid = 0x80000001; } /* * Alternative strategy to a costly (even indexed search) to the * database. * We search in the schema if we have already this intid (using dsdb_attribute_by_attributeID_id because * in the range 0x80000000 0xBFFFFFFFF, attributeID is a DSDB_ATTID_TYPE_INTID). * If so generate another random value. * If not check if the highest USN in the database for the schema partition is the * one that we know. * If so it means that's only this ldb context that is touching the schema in the database. * If not it means that's someone else has modified the database while we are doing our changes too * (this case should be very bery rare) in order to be sure do the search in the database. */ if (dsdb_attribute_by_attributeID_id(schema, msds_intid)) { msds_intid = generate_random() % 0X3FFFFFFF; msds_intid += 0x80000000; continue; } ret = dsdb_module_load_partition_usn(ac->module, schema_dn, &current_usn, NULL, NULL); if (ret != LDB_SUCCESS) { ldb_debug_set(ldb, LDB_DEBUG_ERROR, __location__": Searching for schema USN failed: %s\n", ldb_errstring(ldb)); return ldb_operr(ldb); } /* current_usn can be lesser than msds_intid_struct-> if there is * uncommited changes. */ if (current_usn > msds_intid_struct->usn) { /* oups something has changed, someone/something * else is modifying or has modified the schema * we'd better check this intid is the database directly */ DEBUG(2, ("Schema has changed, searching the database for the unicity of %d\n", msds_intid)); ret = dsdb_module_search(ac->module, ac, &ldb_res, schema_dn, LDB_SCOPE_ONELEVEL, NULL, DSDB_FLAG_NEXT_MODULE, ac->req, "(msDS-IntId=%d)", msds_intid); if (ret != LDB_SUCCESS) { ldb_debug_set(ldb, LDB_DEBUG_ERROR, __location__": Searching for msDS-IntId=%d failed - %s\n", msds_intid, ldb_errstring(ldb)); return ldb_operr(ldb); } id_exists = (ldb_res->count > 0); talloc_free(ldb_res); } else { id_exists = 0; } } while(id_exists); msds_intid_struct->msds_intid = msds_intid; ldb_set_opaque(ldb, SAMLDB_MSDS_INTID_OPAQUE, msds_intid_struct); return samdb_msg_add_int(ldb, ac->msg, ac->msg, "msDS-IntId", msds_intid); }
CWE-264
3
10,845
44351705639129033261662185836661642323
null
null
null
samba
b000da128b5fb519d2d3f2e7fd20e4a25b7dae7d
0
static int samldb_add_step(struct samldb_ctx *ac, samldb_step_fn_t fn) { struct samldb_step *step, *stepper; step = talloc_zero(ac, struct samldb_step); if (step == NULL) { return ldb_oom(ldb_module_get_ctx(ac->module)); } step->fn = fn; if (ac->steps == NULL) { ac->steps = step; ac->curstep = step; } else { if (ac->curstep == NULL) return ldb_operr(ldb_module_get_ctx(ac->module)); for (stepper = ac->curstep; stepper->next != NULL; stepper = stepper->next); stepper->next = step; } return LDB_SUCCESS; }
CWE-264
4
10,846
188977747954049503703539706223006713133
null
null
null
samba
b000da128b5fb519d2d3f2e7fd20e4a25b7dae7d
0
static int samldb_check_sAMAccountName(struct samldb_ctx *ac) { struct ldb_context *ldb = ldb_module_get_ctx(ac->module); const char *name; int ret; struct ldb_result *res; const char * const noattrs[] = { NULL }; if (ldb_msg_find_element(ac->msg, "sAMAccountName") == NULL) { ret = samldb_generate_sAMAccountName(ldb, ac->msg); if (ret != LDB_SUCCESS) { return ret; } } name = ldb_msg_find_attr_as_string(ac->msg, "sAMAccountName", NULL); if (name == NULL) { /* The "sAMAccountName" cannot be nothing */ ldb_set_errstring(ldb, "samldb: Empty account names aren't allowed!"); return LDB_ERR_CONSTRAINT_VIOLATION; } ret = dsdb_module_search(ac->module, ac, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_SUBTREE, noattrs, DSDB_FLAG_NEXT_MODULE, ac->req, "(sAMAccountName=%s)", ldb_binary_encode_string(ac, name)); if (ret != LDB_SUCCESS) { return ret; } if (res->count != 0) { ldb_asprintf_errstring(ldb, "samldb: Account name (sAMAccountName) '%s' already in use!", name); talloc_free(res); return LDB_ERR_ENTRY_ALREADY_EXISTS; } talloc_free(res); return samldb_next_step(ac); }
CWE-264
6
10,847
174649580708161684922808803458072048459
null
null
null
samba
b000da128b5fb519d2d3f2e7fd20e4a25b7dae7d
0
static int samldb_check_user_account_control_invariants(struct samldb_ctx *ac, uint32_t user_account_control) { int i, ret = 0; bool need_check = false; const struct uac_to_guid { uint32_t uac; bool never; uint32_t needs; uint32_t not_with; const char *error_string; } map[] = { { .uac = UF_TEMP_DUPLICATE_ACCOUNT, .never = true, .error_string = "Updating the UF_TEMP_DUPLICATE_ACCOUNT flag is never allowed" }, { .uac = UF_PARTIAL_SECRETS_ACCOUNT, .needs = UF_WORKSTATION_TRUST_ACCOUNT, .error_string = "Setting UF_PARTIAL_SECRETS_ACCOUNT only permitted with UF_WORKSTATION_TRUST_ACCOUNT" }, { .uac = UF_TRUSTED_FOR_DELEGATION, .not_with = UF_PARTIAL_SECRETS_ACCOUNT, .error_string = "Setting UF_TRUSTED_FOR_DELEGATION not allowed with UF_PARTIAL_SECRETS_ACCOUNT" }, { .uac = UF_NORMAL_ACCOUNT, .not_with = UF_ACCOUNT_TYPE_MASK & ~UF_NORMAL_ACCOUNT, .error_string = "Setting more than one account type not permitted" }, { .uac = UF_WORKSTATION_TRUST_ACCOUNT, .not_with = UF_ACCOUNT_TYPE_MASK & ~UF_WORKSTATION_TRUST_ACCOUNT, .error_string = "Setting more than one account type not permitted" }, { .uac = UF_INTERDOMAIN_TRUST_ACCOUNT, .not_with = UF_ACCOUNT_TYPE_MASK & ~UF_INTERDOMAIN_TRUST_ACCOUNT, .error_string = "Setting more than one account type not permitted" }, { .uac = UF_SERVER_TRUST_ACCOUNT, .not_with = UF_ACCOUNT_TYPE_MASK & ~UF_SERVER_TRUST_ACCOUNT, .error_string = "Setting more than one account type not permitted" }, { .uac = UF_TRUSTED_FOR_DELEGATION, .not_with = UF_PARTIAL_SECRETS_ACCOUNT, .error_string = "Setting UF_TRUSTED_FOR_DELEGATION not allowed with UF_PARTIAL_SECRETS_ACCOUNT" } }; for (i = 0; i < ARRAY_SIZE(map); i++) { if (user_account_control & map[i].uac) { need_check = true; break; } } if (need_check == false) { return LDB_SUCCESS; } for (i = 0; i < ARRAY_SIZE(map); i++) { uint32_t this_uac = user_account_control & map[i].uac; if (this_uac != 0) { if (map[i].never) { ret = LDB_ERR_OTHER; break; } else if (map[i].needs != 0) { if ((map[i].needs & user_account_control) == 0) { ret = LDB_ERR_OTHER; break; } } else if (map[i].not_with != 0) { if ((map[i].not_with & user_account_control) != 0) { ret = LDB_ERR_OTHER; break; } } } } if (ret != LDB_SUCCESS) { switch (ac->req->operation) { case LDB_ADD: ldb_asprintf_errstring(ldb_module_get_ctx(ac->module), "Failed to add %s: %s", ldb_dn_get_linearized(ac->msg->dn), map[i].error_string); break; case LDB_MODIFY: ldb_asprintf_errstring(ldb_module_get_ctx(ac->module), "Failed to modify %s: %s", ldb_dn_get_linearized(ac->msg->dn), map[i].error_string); break; default: return ldb_module_operr(ac->module); } } return ret; }
CWE-264
7
10,848
54248369882699107764386636670911681513
null
null
null