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
libgit2
3f461902dc1072acb8b7607ee65d0a0458ffac2a
1
int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; if (cmd & 0x01) off = *delta++; if (cmd & 0x02) off |= *delta++ << 8UL; if (cmd & 0x04) off |= *delta++ << 16UL; if (cmd & 0x08) off |= *delta++ << 24UL; if (cmd & 0x10) len = *delta++; if (cmd & 0x20) len |= *delta++ << 8UL; if (cmd & 0x40) len |= *delta++ << 16UL; if (!len) len = 0x10000; if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; }
CWE-125
183,340
4,445
323670314909050669337516246053289737136
null
null
null
mbedtls
5224a7544c95552553e2e6be0b4a789956a6464e
1
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ if( (*p) > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( (*p) + len > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); }
CWE-125
183,341
4,446
9975011487963196269572446501846820243
null
null
null
mbedtls
027f84c69f4ef30c0693832a6c396ef19e563ca1
1
static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) { int ret; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; unsigned char *p = NULL, *end = NULL; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) ); #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) ); ssl->state++; return( 0 ); } ((void) p); ((void) end); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA ) { if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) ); ssl->state++; return( 0 ); } ((void) p); ((void) end); #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server * doesn't use a psk_identity_hint */ if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE ) { if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { /* Current message is probably either * CertificateRequest or ServerHelloDone */ ssl->keep_current_message = 1; goto exit; } MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must " "not be skipped" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); end = ssl->in_msg + ssl->in_hslen; MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p ); #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } /* FALLTROUGH */ #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) ; /* nothing more to do */ else #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ) { if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx, p, end - p ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) ) { size_t sig_len, hashlen; unsigned char hash[64]; mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE; mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE; unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); size_t params_len = p - params; /* * Handle the digitally-signed structure */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { if( ssl_parse_signature_algorithm( ssl, &p, end, &md_alg, &pk_alg ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) { pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ); /* Default hash for ECDSA is SHA-1 */ if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE ) md_alg = MBEDTLS_MD_SHA1; } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Read signature */ if( p > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } sig_len = ( p[0] << 8 ) | p[1]; p += 2; if( end != p + sig_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len ); /* * Compute the hash that has been signed */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( md_alg == MBEDTLS_MD_NONE ) { hashlen = 36; ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params, params_len ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( md_alg != MBEDTLS_MD_NONE ) { /* Info from md_alg will be used instead */ hashlen = 0; ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params, params_len, md_alg ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen : (unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) ); if( ssl->session_negotiate->peer_cert == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* * Verify signature */ if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk, md_alg, hash, hashlen, p, sig_len ) ) != 0 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR ); MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret ); return( ret ); } } #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */ exit: ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) ); return( 0 ); }
CWE-119
183,342
4,447
216299019030539115858114873448491855786
null
null
null
libgit2
3db1af1f370295ad5355b8f64b865a2a357bcac0
1
static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len, last_len, prefix_len, suffix_len, path_len; uintmax_t strip_len; strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); last_len = strlen(last); if (varint_len == 0 || last_len < strip_len) return index_error_invalid("incorrect prefix length"); prefix_len = last_len - strip_len; suffix_len = strlen(path_ptr + varint_len); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; }
CWE-190
183,343
4,448
285266082278998713904854919814475327925
null
null
null
suricata
8357ef3f8ffc7d99ef6571350724160de356158b
1
AppProto AppLayerProtoDetectGetProto(AppLayerProtoDetectThreadCtx *tctx, Flow *f, uint8_t *buf, uint32_t buflen, uint8_t ipproto, uint8_t direction) { SCEnter(); SCLogDebug("buflen %u for %s direction", buflen, (direction & STREAM_TOSERVER) ? "toserver" : "toclient"); AppProto alproto = ALPROTO_UNKNOWN; if (!FLOW_IS_PM_DONE(f, direction)) { AppProto pm_results[ALPROTO_MAX]; uint16_t pm_matches = AppLayerProtoDetectPMGetProto(tctx, f, buf, buflen, direction, ipproto, pm_results); if (pm_matches > 0) { alproto = pm_results[0]; goto end; } } if (!FLOW_IS_PP_DONE(f, direction)) { alproto = AppLayerProtoDetectPPGetProto(f, buf, buflen, ipproto, direction); if (alproto != ALPROTO_UNKNOWN) goto end; } /* Look if flow can be found in expectation list */ if (!FLOW_IS_PE_DONE(f, direction)) { alproto = AppLayerProtoDetectPEGetProto(f, ipproto, direction); } end: SCReturnUInt(alproto); }
CWE-20
183,351
4,452
42797380008853399910828205880874354433
null
null
null
radare2
5411543a310a470b1257fb93273cdd6e8dfcb3af
1
static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) { RBinInfo *info = r_bin_get_info (r->bin); RList *entries = r_bin_get_entries (r->bin); RBinSymbol *symbol; RBinAddr *entry; RListIter *iter; bool firstexp = true; bool printHere = false; int i = 0, lastfs = 's'; bool bin_demangle = r_config_get_i (r->config, "bin.demangle"); if (!info) { return 0; } if (args && *args == '.') { printHere = true; } bool is_arm = info && info->arch && !strncmp (info->arch, "arm", 3); const char *lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL; RList *symbols = r_bin_get_symbols (r->bin); r_spaces_push (&r->anal->meta_spaces, "bin"); if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf ("["); } else if (IS_MODE_SET (mode)) { r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS); } else if (!at && exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf ("fs exports\n"); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? "" : "[Exports]\n"); } } else if (!at && !exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf ("fs symbols\n"); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? "" : "[Symbols]\n"); } } if (IS_MODE_NORMAL (mode)) { r_cons_printf ("Num Paddr Vaddr Bind Type Size Name\n"); } size_t count = 0; r_list_foreach (symbols, iter, symbol) { if (!symbol->name) { continue; } char *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true); ut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va); int len = symbol->size ? symbol->size : 32; SymName sn = {0}; if (exponly && !isAnExport (symbol)) { free (r_symbol_name); continue; } if (name && strcmp (r_symbol_name, name)) { free (r_symbol_name); continue; } if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) { free (r_symbol_name); continue; } if ((printHere && !is_in_range (r->offset, symbol->paddr, len)) && (printHere && !is_in_range (r->offset, addr, len))) { free (r_symbol_name); continue; } count ++; snInit (r, &sn, symbol, lang); if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) { /* * Skip section symbols because they will have their own flag. * Skip also file symbols because not useful for now. */ } else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) { if (is_arm) { handle_arm_special_symbol (r, symbol, va); } } else if (IS_MODE_SET (mode)) { if (is_arm) { handle_arm_symbol (r, symbol, info, va); } select_flag_space (r, symbol); /* If that's a Classed symbol (method or so) */ if (sn.classname) { RFlagItem *fi = r_flag_get (r->flags, sn.methflag); if (r->bin->prefix) { char *prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag); r_name_filter (sn.methflag, -1); free (sn.methflag); sn.methflag = prname; } if (fi) { r_flag_item_set_realname (fi, sn.methname); if ((fi->offset - r->flags->base) == addr) { r_flag_unset (r->flags, fi); } } else { fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size); char *comment = fi->comment ? strdup (fi->comment) : NULL; if (comment) { r_flag_item_set_comment (fi, comment); R_FREE (comment); } } } else { const char *n = sn.demname ? sn.demname : sn.name; const char *fn = sn.demflag ? sn.demflag : sn.nameflag; char *fnp = (r->bin->prefix) ? r_str_newf ("%s.%s", r->bin->prefix, fn): strdup (fn); RFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size); if (fi) { r_flag_item_set_realname (fi, n); fi->demangled = (bool)(size_t)sn.demname; } else { if (fn) { eprintf ("[Warning] Can't find flag (%s)\n", fn); } } free (fnp); } if (sn.demname) { r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, symbol->size, sn.demname); } r_flag_space_pop (r->flags); } else if (IS_MODE_JSON (mode)) { char *str = r_str_escape_utf8_for_json (r_symbol_name, -1); r_cons_printf ("%s{\"name\":\"%s\"," "\"demname\":\"%s\"," "\"flagname\":\"%s\"," "\"ordinal\":%d," "\"bind\":\"%s\"," "\"size\":%d," "\"type\":\"%s\"," "\"vaddr\":%"PFMT64d"," "\"paddr\":%"PFMT64d"}", ((exponly && firstexp) || printHere) ? "" : (iter->p ? "," : ""), str, sn.demname? sn.demname: "", sn.nameflag, symbol->ordinal, symbol->bind, (int)symbol->size, symbol->type, (ut64)addr, (ut64)symbol->paddr); free (str); } else if (IS_MODE_SIMPLE (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf ("0x%08"PFMT64x" %d %s\n", addr, (int)symbol->size, name); } else if (IS_MODE_SIMPLEST (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf ("%s\n", name); } else if (IS_MODE_RAD (mode)) { /* Skip special symbols because we do not flag them and * they shouldn't be printed in the rad format either */ if (is_special_symbol (symbol)) { goto next; } RBinFile *binfile; RBinPlugin *plugin; const char *name = sn.demname? sn.demname: r_symbol_name; if (!name) { goto next; } if (!strncmp (name, "imp.", 4)) { if (lastfs != 'i') { r_cons_printf ("fs imports\n"); } lastfs = 'i'; } else { if (lastfs != 's') { const char *fs = exponly? "exports": "symbols"; r_cons_printf ("fs %s\n", fs); } lastfs = 's'; } if (r->bin->prefix || *name) { // we don't want unnamed symbol flags char *flagname = construct_symbol_flagname ("sym", name, MAXFLAG_LEN_DEFAULT); if (!flagname) { goto next; } r_cons_printf ("\"f %s%s%s %u 0x%08" PFMT64x "\"\n", r->bin->prefix ? r->bin->prefix : "", r->bin->prefix ? "." : "", flagname, symbol->size, addr); free (flagname); } binfile = r_bin_cur (r->bin); plugin = r_bin_file_cur_plugin (binfile); if (plugin && plugin->name) { if (r_str_startswith (plugin->name, "pe")) { char *module = strdup (r_symbol_name); char *p = strstr (module, ".dll_"); if (p && strstr (module, "imp.")) { char *symname = __filterShell (p + 5); char *m = __filterShell (module); *p = 0; if (r->bin->prefix) { r_cons_printf ("k bin/pe/%s/%d=%s.%s\n", module, symbol->ordinal, r->bin->prefix, symname); } else { r_cons_printf ("k bin/pe/%s/%d=%s\n", module, symbol->ordinal, symname); } free (symname); free (m); } free (module); } } } else { const char *bind = symbol->bind? symbol->bind: "NONE"; const char *type = symbol->type? symbol->type: "NONE"; const char *name = r_str_get (sn.demname? sn.demname: r_symbol_name); r_cons_printf ("%03u", symbol->ordinal); if (symbol->paddr == UT64_MAX) { r_cons_printf (" ----------"); } else { r_cons_printf (" 0x%08"PFMT64x, symbol->paddr); } r_cons_printf (" 0x%08"PFMT64x" %6s %6s %4d%s%s\n", addr, bind, type, symbol->size, *name? " ": "", name); } next: snFini (&sn); i++; free (r_symbol_name); if (exponly && firstexp) { firstexp = false; } if (printHere) { break; } } if (count == 0 && IS_MODE_JSON (mode)) { r_cons_printf ("{}"); } if (is_arm) { r_list_foreach (entries, iter, entry) { if (IS_MODE_SET (mode)) { handle_arm_entry (r, entry, info, va); } } } if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf ("]"); } r_spaces_pop (&r->anal->meta_spaces); return true; }
CWE-78
183,358
4,458
135940108812750353388169373596798007511
null
null
null
ImageMagick6
c5d012a46ae22be9444326aa37969a3f75daa3ba
1
MagickExport void *DetachBlob(BlobInfo *blob_info) { void *data; assert(blob_info != (BlobInfo *) NULL); if (blob_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (blob_info->mapped != MagickFalse) { (void) UnmapBlob(blob_info->data,blob_info->length); RelinquishMagickResource(MapResource,blob_info->length); } blob_info->mapped=MagickFalse; blob_info->length=0; blob_info->offset=0; blob_info->eof=MagickFalse; blob_info->error=0; blob_info->exempt=MagickFalse; blob_info->type=UndefinedStream; blob_info->file_info.file=(FILE *) NULL; data=blob_info->data; blob_info->data=(unsigned char *) NULL; blob_info->stream=(StreamHandler) NULL; blob_info->custom_stream=(CustomStreamInfo *) NULL; return(data); }
CWE-416
183,362
4,461
280895254590469133914549422231068378746
null
null
null
linux
072684e8c58d17e853f8e8b9f6d9ce2e58d2b036
1
static ssize_t f_hidg_write(struct file *file, const char __user *buffer, size_t count, loff_t *offp) { struct f_hidg *hidg = file->private_data; struct usb_request *req; unsigned long flags; ssize_t status = -ENOMEM; if (!access_ok(buffer, count)) return -EFAULT; spin_lock_irqsave(&hidg->write_spinlock, flags); #define WRITE_COND (!hidg->write_pending) try_again: /* write queue */ while (!WRITE_COND) { spin_unlock_irqrestore(&hidg->write_spinlock, flags); if (file->f_flags & O_NONBLOCK) return -EAGAIN; if (wait_event_interruptible_exclusive( hidg->write_queue, WRITE_COND)) return -ERESTARTSYS; spin_lock_irqsave(&hidg->write_spinlock, flags); } hidg->write_pending = 1; req = hidg->req; count = min_t(unsigned, count, hidg->report_length); spin_unlock_irqrestore(&hidg->write_spinlock, flags); status = copy_from_user(req->buf, buffer, count); if (status != 0) { ERROR(hidg->func.config->cdev, "copy_from_user error\n"); status = -EINVAL; goto release_write_pending; } spin_lock_irqsave(&hidg->write_spinlock, flags); /* when our function has been disabled by host */ if (!hidg->req) { free_ep_req(hidg->in_ep, req); /* * TODO * Should we fail with error here? */ goto try_again; } req->status = 0; req->zero = 0; req->length = count; req->complete = f_hidg_req_complete; req->context = hidg; status = usb_ep_queue(hidg->in_ep, req, GFP_ATOMIC); if (status < 0) { ERROR(hidg->func.config->cdev, "usb_ep_queue error on int endpoint %zd\n", status); goto release_write_pending_unlocked; } else { status = count; } spin_unlock_irqrestore(&hidg->write_spinlock, flags); return status; release_write_pending: spin_lock_irqsave(&hidg->write_spinlock, flags); release_write_pending_unlocked: hidg->write_pending = 0; spin_unlock_irqrestore(&hidg->write_spinlock, flags); wake_up(&hidg->write_queue); return status; }
CWE-189
183,363
4,462
18722974638875232385929906524846490153
null
null
null
ImageMagick6
1ddcf2e4f28029a888cadef2e757509ef5047ad8
1
MagickExport void RemoveDuplicateLayers(Image **images, ExceptionInfo *exception) { register Image *curr, *next; RectangleInfo bounds; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); curr=GetFirstImageInList(*images); for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next) { if ( curr->columns != next->columns || curr->rows != next->rows || curr->page.x != next->page.x || curr->page.y != next->page.y ) continue; bounds=CompareImagesBounds(curr,next,CompareAnyLayer,exception); if ( bounds.x < 0 ) { /* the two images are the same, merge time delays and delete one. */ size_t time; time = curr->delay*1000/curr->ticks_per_second; time += next->delay*1000/next->ticks_per_second; next->ticks_per_second = 100L; next->delay = time*curr->ticks_per_second/1000; next->iterations = curr->iterations; *images = curr; (void) DeleteImageFromList(images); } } *images = GetFirstImageInList(*images); }
CWE-369
183,364
4,463
310600417952627726451368104076572244229
null
null
null
ImageMagick6
7c2c5ba5b8e3a0b2b82f56c71dfab74ed4006df7
1
MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(images); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]); Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]); Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]); Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); }
CWE-125
183,366
4,465
215062495765014507385339416277312025748
null
null
null
ImageMagick6
4a334bbf5584de37c6f5a47c380a531c8c4b140a
1
WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { const char *option; ImageInfo *mogrify_info; MagickStatusType status; PixelInterpolateMethod interpolate_method; QuantizeInfo *quantize_info; register ssize_t i; ssize_t count, index; /* Apply options to the image list. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image **) NULL); assert((*images)->previous == (Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); if ((argc <= 0) || (*argv == (char *) NULL)) return(MagickTrue); interpolate_method=UndefinedInterpolatePixel; mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); status=MagickTrue; for (i=0; i < (ssize_t) argc; i++) { if (*images == (Image *) NULL) break; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); switch (*(option+1)) { case 'a': { if (LocaleCompare("affinity",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("append",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images,exception); append_image=AppendImages(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (append_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=append_image; break; } if (LocaleCompare("average",option+1) == 0) { Image *average_image; /* Average an image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); average_image=EvaluateImages(*images,MeanEvaluateOperator, exception); if (average_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=average_image; break; } break; } case 'c': { if (LocaleCompare("channel-fx",option+1) == 0) { Image *channel_image; (void) SyncImagesSettings(mogrify_info,*images,exception); channel_image=ChannelFxImage(*images,argv[i+1],exception); if (channel_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=channel_image; break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { status=MagickFalse; break; } (void) ClutImage(image,clut_image,interpolate_method,exception); clut_image=DestroyImage(clut_image); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("coalesce",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images,exception); coalesce_image=CoalesceImages(*images,exception); if (coalesce_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=coalesce_image; break; } if (LocaleCompare("combine",option+1) == 0) { ColorspaceType colorspace; Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images,exception); colorspace=(*images)->colorspace; if ((*images)->number_channels < GetImageListLength(*images)) colorspace=sRGBColorspace; if (*option == '+') colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); combine_image=CombineImages(*images,colorspace,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare("compare",option+1) == 0) { double distortion; Image *difference_image, *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { status=MagickFalse; break; } metric=UndefinedErrorMetric; option=GetImageOption(mogrify_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImages(image,reconstruct_image,metric, &distortion,exception); if (difference_image == (Image *) NULL) break; reconstruct_image=DestroyImage(reconstruct_image); image=DestroyImage(image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=difference_image; break; } if (LocaleCompare("complex",option+1) == 0) { ComplexOperator op; Image *complex_images; (void) SyncImageSettings(mogrify_info,*images,exception); op=(ComplexOperator) ParseCommandOption(MagickComplexOptions, MagickFalse,argv[i+1]); complex_images=ComplexImages(*images,op,exception); if (complex_images == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=complex_images; break; } if (LocaleCompare("composite",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *new_images, *source_image; RectangleInfo geometry; /* Compose value from "-compose" option only */ (void) SyncImageSettings(mogrify_info,*images,exception); value=GetImageOption(mogrify_info,"compose"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Get "clip-to-self" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(mogrify_info,"compose:clip-to-self"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(mogrify_info,"compose:outside-overlay"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(images); source_image=RemoveFirstImageFromList(images); if (source_image == (Image *) NULL) break; /* FUTURE - produce Exception, rather than silent fail */ /* FUTURE: this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity,&geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(clone_image,new_images, OverCompositeOp,clip_to_self,0,0,exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); *images=DestroyImageList(*images); *images=new_images; break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images,exception); (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception); offset.x=geometry.x; offset.y=geometry.y; source_image=(*images); if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,argv[i+1],&geometry, exception); status=CopyImagePixels(*images,source_image,&geometry,&offset, exception); break; } break; } case 'd': { if (LocaleCompare("deconstruct",option+1) == 0) { Image *deconstruct_image; (void) SyncImagesSettings(mogrify_info,*images,exception); deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer, exception); if (deconstruct_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=deconstruct_image; break; } if (LocaleCompare("delete",option+1) == 0) { if (*option == '+') DeleteImages(images,"-1",exception); else DeleteImages(images,argv[i+1],exception); break; } if (LocaleCompare("dither",option+1) == 0) { if (*option == '+') { quantize_info->dither_method=NoDitherMethod; break; } quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare("duplicate",option+1) == 0) { Image *duplicate_images; if (*option == '+') duplicate_images=DuplicateImages(*images,1,"-1",exception); else { const char *p; size_t number_duplicates; number_duplicates=(size_t) StringToLong(argv[i+1]); p=strchr(argv[i+1],','); if (p == (const char *) NULL) duplicate_images=DuplicateImages(*images,number_duplicates, "-1",exception); else duplicate_images=DuplicateImages(*images,number_duplicates,p, exception); } AppendImageToList(images, duplicate_images); (void) SyncImagesSettings(mogrify_info,*images,exception); break; } break; } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images,exception); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); evaluate_image=EvaluateImages(*images,op,exception); if (evaluate_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=evaluate_image; break; } break; } case 'f': { if (LocaleCompare("fft",option+1) == 0) { Image *fourier_image; /* Implements the discrete Fourier transform (DFT). */ (void) SyncImageSettings(mogrify_info,*images,exception); fourier_image=ForwardFourierTransformImage(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("flatten",option+1) == 0) { Image *flatten_image; (void) SyncImagesSettings(mogrify_info,*images,exception); flatten_image=MergeImageLayers(*images,FlattenLayer,exception); if (flatten_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=flatten_image; break; } if (LocaleCompare("fx",option+1) == 0) { Image *fx_image; (void) SyncImagesSettings(mogrify_info,*images,exception); fx_image=FxImage(*images,argv[i+1],exception); if (fx_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=fx_image; break; } break; } case 'h': { if (LocaleCompare("hald-clut",option+1) == 0) { Image *hald_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { status=MagickFalse; break; } (void) HaldClutImage(image,hald_image,exception); hald_image=DestroyImage(hald_image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=image; break; } break; } case 'i': { if (LocaleCompare("ift",option+1) == 0) { Image *fourier_image, *magnitude_image, *phase_image; /* Implements the inverse fourier discrete Fourier transform (DFT). */ (void) SyncImagesSettings(mogrify_info,*images,exception); magnitude_image=RemoveFirstImageFromList(images); phase_image=RemoveFirstImageFromList(images); if (phase_image == (Image *) NULL) { status=MagickFalse; break; } fourier_image=InverseFourierTransformImage(magnitude_image, phase_image,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("insert",option+1) == 0) { Image *p, *q; index=0; if (*option != '+') index=(ssize_t) StringToLong(argv[i+1]); p=RemoveLastImageFromList(images); if (p == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } q=p; if (index == 0) PrependImageToList(images,q); else if (index == (ssize_t) GetImageListLength(*images)) AppendImageToList(images,q); else { q=GetImageFromList(*images,index-1); if (q == (Image *) NULL) { p=DestroyImage(p); (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } InsertImageInList(&q,p); } *images=GetFirstImageInList(q); break; } if (LocaleCompare("interpolate",option+1) == 0) { interpolate_method=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,argv[i+1]); break; } break; } case 'l': { if (LocaleCompare("layers",option+1) == 0) { Image *layers; LayerMethod method; (void) SyncImagesSettings(mogrify_info,*images,exception); layers=(Image *) NULL; method=(LayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImagesLayers(*images,method,exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { layers=MergeImageLayers(*images,method,exception); break; } case DisposeLayer: { layers=DisposeImages(*images,exception); break; } case OptimizeImageLayer: { layers=OptimizeImageLayers(*images,exception); break; } case OptimizePlusLayer: { layers=OptimizePlusImageLayers(*images,exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(*images,exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(images,exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(images,exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ layers=CoalesceImages(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } case CompositeLayer: { CompositeOperator compose; Image *source; RectangleInfo geometry; /* Split image sequence at the first 'NULL:' image. */ source=(*images); while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,"NULL") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"MissingNullSeparator","layers Composite"); status=MagickFalse; break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(*images,&geometry); (void) ParseAbsoluteGeometry((*images)->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry((*images)->page.width != 0 ? (*images)->page.width : (*images)->columns, (*images)->page.height != 0 ? (*images)->page.height : (*images)->rows,(*images)->gravity,&geometry); compose=OverCompositeOp; option=GetImageOption(mogrify_info,"compose"); if (option != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,option); CompositeLayers(*images,compose,source,geometry.x,geometry.y, exception); source=DestroyImageList(source); break; } } if (layers == (Image *) NULL) break; *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare("map",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("maximum",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception); if (maximum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=maximum_image; break; } if (LocaleCompare("minimum",option+1) == 0) { Image *minimum_image; /* Minimum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception); if (minimum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=minimum_image; break; } if (LocaleCompare("morph",option+1) == 0) { Image *morph_image; (void) SyncImagesSettings(mogrify_info,*images,exception); morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]), exception); if (morph_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=morph_image; break; } if (LocaleCompare("mosaic",option+1) == 0) { Image *mosaic_image; (void) SyncImagesSettings(mogrify_info,*images,exception); mosaic_image=MergeImageLayers(*images,MosaicLayer,exception); if (mosaic_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=mosaic_image; break; } break; } case 'p': { if (LocaleCompare("poly",option+1) == 0) { char *args, token[MagickPathExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images,exception); args=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, "MemoryAllocationFailed",(*images)->filename); (void) memset(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImage(*images,number_arguments >> 1, arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; } if (LocaleCompare("print",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images,exception); string=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (string == (char *) NULL) break; (void) FormatLocaleFile(stdout,"%s",string); string=DestroyString(string); } if (LocaleCompare("process",option+1) == 0) { char **arguments; int j, number_arguments; (void) SyncImagesSettings(mogrify_info,*images,exception); arguments=StringToArgv(argv[i+1],&number_arguments); if (arguments == (char **) NULL) break; if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL)) { char breaker, quote, *token; const char *argument; int next, token_status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; argument=argv[i+1]; token_info=AcquireTokenInfo(); token_status=Tokenizer(token_info,0,token,length,argument,"", "=","\"",'\0',&breaker,&next,&quote); token_info=DestroyTokenInfo(token_info); if (token_status == 0) { const char *arg; arg=(&(argument[next])); (void) InvokeDynamicImageFilter(token,&(*images),1,&arg, exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],"-",""); (void) InvokeDynamicImageFilter(arguments[1],&(*images), number_arguments-2,(const char **) arguments+2,exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } break; } case 'r': { if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(images); break; } break; } case 's': { if (LocaleCompare("smush",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images,exception); offset=(ssize_t) StringToLong(argv[i+1]); smush_image=SmushImages(*images,*option == '-' ? MagickTrue : MagickFalse,offset,exception); if (smush_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=smush_image; break; } if (LocaleCompare("swap",option+1) == 0) { Image *p, *q, *u, *v; ssize_t swap_index; index=(-1); swap_index=(-2); if (*option != '+') { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(argv[i+1],&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(*images,index); q=GetImageFromList(*images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",(*images)->filename); status=MagickFalse; break; } if (p == q) break; u=CloneImage(p,0,0,MagickTrue,exception); if (u == (Image *) NULL) break; v=CloneImage(q,0,0,MagickTrue,exception); if (v == (Image *) NULL) { u=DestroyImage(u); break; } ReplaceImageInList(&p,v); ReplaceImageInList(&q,u); *images=GetFirstImageInList(q); break; } break; } case 'w': { if (LocaleCompare("write",option+1) == 0) { char key[MagickPathExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images,exception); (void) FormatLocaleString(key,MagickPathExtent,"cache:%s", argv[i+1]); (void) DeleteImageRegistry(key); write_images=(*images); if (*option == '+') write_images=CloneImageList(*images,exception); write_info=CloneImageInfo(mogrify_info); status&=WriteImages(write_info,write_images,argv[i+1],exception); write_info=DestroyImageInfo(write_info); if (*option == '+') write_images=DestroyImageList(write_images); break; } break; } default: break; } i+=count; } quantize_info=DestroyQuantizeInfo(quantize_info); mogrify_info=DestroyImageInfo(mogrify_info); status&=MogrifyImageInfo(image_info,argc,argv,exception); return(status != 0 ? MagickTrue : MagickFalse); }
CWE-399
183,367
4,466
261737277868569690361589965024162675954
null
null
null
ImageMagick6
5f21230b657ccd65452dd3d94c5b5401ba691a2d
1
WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { const char *option; ImageInfo *mogrify_info; MagickStatusType status; PixelInterpolateMethod interpolate_method; QuantizeInfo *quantize_info; register ssize_t i; ssize_t count, index; /* Apply options to the image list. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image **) NULL); assert((*images)->previous == (Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); if ((argc <= 0) || (*argv == (char *) NULL)) return(MagickTrue); interpolate_method=UndefinedInterpolatePixel; mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); status=MagickTrue; for (i=0; i < (ssize_t) argc; i++) { if (*images == (Image *) NULL) break; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); switch (*(option+1)) { case 'a': { if (LocaleCompare("affinity",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("append",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images,exception); append_image=AppendImages(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (append_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=append_image; break; } if (LocaleCompare("average",option+1) == 0) { Image *average_image; /* Average an image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); average_image=EvaluateImages(*images,MeanEvaluateOperator, exception); if (average_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=average_image; break; } break; } case 'c': { if (LocaleCompare("channel-fx",option+1) == 0) { Image *channel_image; (void) SyncImagesSettings(mogrify_info,*images,exception); channel_image=ChannelFxImage(*images,argv[i+1],exception); if (channel_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=channel_image; break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { status=MagickFalse; break; } (void) ClutImage(image,clut_image,interpolate_method,exception); clut_image=DestroyImage(clut_image); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("coalesce",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images,exception); coalesce_image=CoalesceImages(*images,exception); if (coalesce_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=coalesce_image; break; } if (LocaleCompare("combine",option+1) == 0) { ColorspaceType colorspace; Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images,exception); colorspace=(*images)->colorspace; if ((*images)->number_channels < GetImageListLength(*images)) colorspace=sRGBColorspace; if (*option == '+') colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); combine_image=CombineImages(*images,colorspace,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare("compare",option+1) == 0) { double distortion; Image *difference_image, *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { status=MagickFalse; break; } metric=UndefinedErrorMetric; option=GetImageOption(mogrify_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImages(image,reconstruct_image,metric, &distortion,exception); if (difference_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=difference_image; break; } if (LocaleCompare("complex",option+1) == 0) { ComplexOperator op; Image *complex_images; (void) SyncImageSettings(mogrify_info,*images,exception); op=(ComplexOperator) ParseCommandOption(MagickComplexOptions, MagickFalse,argv[i+1]); complex_images=ComplexImages(*images,op,exception); if (complex_images == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=complex_images; break; } if (LocaleCompare("composite",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *new_images, *source_image; RectangleInfo geometry; /* Compose value from "-compose" option only */ (void) SyncImageSettings(mogrify_info,*images,exception); value=GetImageOption(mogrify_info,"compose"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Get "clip-to-self" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(mogrify_info,"compose:clip-to-self"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(mogrify_info,"compose:outside-overlay"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(images); source_image=RemoveFirstImageFromList(images); if (source_image == (Image *) NULL) break; /* FUTURE - produce Exception, rather than silent fail */ /* FUTURE: this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity,&geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(clone_image,new_images, OverCompositeOp,clip_to_self,0,0,exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); *images=DestroyImageList(*images); *images=new_images; break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images,exception); (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception); offset.x=geometry.x; offset.y=geometry.y; source_image=(*images); if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,argv[i+1],&geometry, exception); status=CopyImagePixels(*images,source_image,&geometry,&offset, exception); break; } break; } case 'd': { if (LocaleCompare("deconstruct",option+1) == 0) { Image *deconstruct_image; (void) SyncImagesSettings(mogrify_info,*images,exception); deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer, exception); if (deconstruct_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=deconstruct_image; break; } if (LocaleCompare("delete",option+1) == 0) { if (*option == '+') DeleteImages(images,"-1",exception); else DeleteImages(images,argv[i+1],exception); break; } if (LocaleCompare("dither",option+1) == 0) { if (*option == '+') { quantize_info->dither_method=NoDitherMethod; break; } quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare("duplicate",option+1) == 0) { Image *duplicate_images; if (*option == '+') duplicate_images=DuplicateImages(*images,1,"-1",exception); else { const char *p; size_t number_duplicates; number_duplicates=(size_t) StringToLong(argv[i+1]); p=strchr(argv[i+1],','); if (p == (const char *) NULL) duplicate_images=DuplicateImages(*images,number_duplicates, "-1",exception); else duplicate_images=DuplicateImages(*images,number_duplicates,p, exception); } AppendImageToList(images, duplicate_images); (void) SyncImagesSettings(mogrify_info,*images,exception); break; } break; } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images,exception); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); evaluate_image=EvaluateImages(*images,op,exception); if (evaluate_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=evaluate_image; break; } break; } case 'f': { if (LocaleCompare("fft",option+1) == 0) { Image *fourier_image; /* Implements the discrete Fourier transform (DFT). */ (void) SyncImageSettings(mogrify_info,*images,exception); fourier_image=ForwardFourierTransformImage(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("flatten",option+1) == 0) { Image *flatten_image; (void) SyncImagesSettings(mogrify_info,*images,exception); flatten_image=MergeImageLayers(*images,FlattenLayer,exception); if (flatten_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=flatten_image; break; } if (LocaleCompare("fx",option+1) == 0) { Image *fx_image; (void) SyncImagesSettings(mogrify_info,*images,exception); fx_image=FxImage(*images,argv[i+1],exception); if (fx_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=fx_image; break; } break; } case 'h': { if (LocaleCompare("hald-clut",option+1) == 0) { Image *hald_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { status=MagickFalse; break; } (void) HaldClutImage(image,hald_image,exception); hald_image=DestroyImage(hald_image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=image; break; } break; } case 'i': { if (LocaleCompare("ift",option+1) == 0) { Image *fourier_image, *magnitude_image, *phase_image; /* Implements the inverse fourier discrete Fourier transform (DFT). */ (void) SyncImagesSettings(mogrify_info,*images,exception); magnitude_image=RemoveFirstImageFromList(images); phase_image=RemoveFirstImageFromList(images); if (phase_image == (Image *) NULL) { status=MagickFalse; break; } fourier_image=InverseFourierTransformImage(magnitude_image, phase_image,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("insert",option+1) == 0) { Image *p, *q; index=0; if (*option != '+') index=(ssize_t) StringToLong(argv[i+1]); p=RemoveLastImageFromList(images); if (p == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } q=p; if (index == 0) PrependImageToList(images,q); else if (index == (ssize_t) GetImageListLength(*images)) AppendImageToList(images,q); else { q=GetImageFromList(*images,index-1); if (q == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } InsertImageInList(&q,p); } *images=GetFirstImageInList(q); break; } if (LocaleCompare("interpolate",option+1) == 0) { interpolate_method=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,argv[i+1]); break; } break; } case 'l': { if (LocaleCompare("layers",option+1) == 0) { Image *layers; LayerMethod method; (void) SyncImagesSettings(mogrify_info,*images,exception); layers=(Image *) NULL; method=(LayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImagesLayers(*images,method,exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { layers=MergeImageLayers(*images,method,exception); break; } case DisposeLayer: { layers=DisposeImages(*images,exception); break; } case OptimizeImageLayer: { layers=OptimizeImageLayers(*images,exception); break; } case OptimizePlusLayer: { layers=OptimizePlusImageLayers(*images,exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(*images,exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(images,exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(images,exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ layers=CoalesceImages(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } case CompositeLayer: { CompositeOperator compose; Image *source; RectangleInfo geometry; /* Split image sequence at the first 'NULL:' image. */ source=(*images); while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,"NULL") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"MissingNullSeparator","layers Composite"); status=MagickFalse; break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(*images,&geometry); (void) ParseAbsoluteGeometry((*images)->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry((*images)->page.width != 0 ? (*images)->page.width : (*images)->columns, (*images)->page.height != 0 ? (*images)->page.height : (*images)->rows,(*images)->gravity,&geometry); compose=OverCompositeOp; option=GetImageOption(mogrify_info,"compose"); if (option != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,option); CompositeLayers(*images,compose,source,geometry.x,geometry.y, exception); source=DestroyImageList(source); break; } } if (layers == (Image *) NULL) break; *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare("map",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("maximum",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception); if (maximum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=maximum_image; break; } if (LocaleCompare("minimum",option+1) == 0) { Image *minimum_image; /* Minimum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception); if (minimum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=minimum_image; break; } if (LocaleCompare("morph",option+1) == 0) { Image *morph_image; (void) SyncImagesSettings(mogrify_info,*images,exception); morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]), exception); if (morph_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=morph_image; break; } if (LocaleCompare("mosaic",option+1) == 0) { Image *mosaic_image; (void) SyncImagesSettings(mogrify_info,*images,exception); mosaic_image=MergeImageLayers(*images,MosaicLayer,exception); if (mosaic_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=mosaic_image; break; } break; } case 'p': { if (LocaleCompare("poly",option+1) == 0) { char *args, token[MagickPathExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images,exception); args=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, "MemoryAllocationFailed",(*images)->filename); (void) memset(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImage(*images,number_arguments >> 1, arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; } if (LocaleCompare("print",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images,exception); string=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (string == (char *) NULL) break; (void) FormatLocaleFile(stdout,"%s",string); string=DestroyString(string); } if (LocaleCompare("process",option+1) == 0) { char **arguments; int j, number_arguments; (void) SyncImagesSettings(mogrify_info,*images,exception); arguments=StringToArgv(argv[i+1],&number_arguments); if (arguments == (char **) NULL) break; if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL)) { char breaker, quote, *token; const char *argument; int next, token_status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; argument=argv[i+1]; token_info=AcquireTokenInfo(); token_status=Tokenizer(token_info,0,token,length,argument,"", "=","\"",'\0',&breaker,&next,&quote); token_info=DestroyTokenInfo(token_info); if (token_status == 0) { const char *arg; arg=(&(argument[next])); (void) InvokeDynamicImageFilter(token,&(*images),1,&arg, exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],"-",""); (void) InvokeDynamicImageFilter(arguments[1],&(*images), number_arguments-2,(const char **) arguments+2,exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } break; } case 'r': { if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(images); break; } break; } case 's': { if (LocaleCompare("smush",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images,exception); offset=(ssize_t) StringToLong(argv[i+1]); smush_image=SmushImages(*images,*option == '-' ? MagickTrue : MagickFalse,offset,exception); if (smush_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=smush_image; break; } if (LocaleCompare("swap",option+1) == 0) { Image *p, *q, *u, *v; ssize_t swap_index; index=(-1); swap_index=(-2); if (*option != '+') { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(argv[i+1],&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(*images,index); q=GetImageFromList(*images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",(*images)->filename); status=MagickFalse; break; } if (p == q) break; u=CloneImage(p,0,0,MagickTrue,exception); if (u == (Image *) NULL) break; v=CloneImage(q,0,0,MagickTrue,exception); if (v == (Image *) NULL) { u=DestroyImage(u); break; } ReplaceImageInList(&p,v); ReplaceImageInList(&q,u); *images=GetFirstImageInList(q); break; } break; } case 'w': { if (LocaleCompare("write",option+1) == 0) { char key[MagickPathExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images,exception); (void) FormatLocaleString(key,MagickPathExtent,"cache:%s", argv[i+1]); (void) DeleteImageRegistry(key); write_images=(*images); if (*option == '+') write_images=CloneImageList(*images,exception); write_info=CloneImageInfo(mogrify_info); status&=WriteImages(write_info,write_images,argv[i+1],exception); write_info=DestroyImageInfo(write_info); if (*option == '+') write_images=DestroyImageList(write_images); break; } break; } default: break; } i+=count; } quantize_info=DestroyQuantizeInfo(quantize_info); mogrify_info=DestroyImageInfo(mogrify_info); status&=MogrifyImageInfo(image_info,argc,argv,exception); return(status != 0 ? MagickTrue : MagickFalse); }
CWE-399
183,369
4,468
56586835940470490143501479593568136056
null
null
null
ImageMagick6
5f21230b657ccd65452dd3d94c5b5401ba691a2d
1
WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand, const char *option,const char *arg1n,const char *arg2n) { const char /* percent escaped versions of the args */ *arg1, *arg2; Image *new_images; MagickStatusType status; ssize_t parse; #define _image_info (cli_wand->wand.image_info) #define _images (cli_wand->wand.images) #define _exception (cli_wand->wand.exception) #define _draw_info (cli_wand->draw_info) #define _quantize_info (cli_wand->quantize_info) #define _process_flags (cli_wand->process_flags) #define _option_type ((CommandOptionFlags) cli_wand->command->flags) #define IfNormalOp (*option=='-') #define IfPlusOp (*option!='-') #define IsNormalOp IfNormalOp ? MagickTrue : MagickFalse assert(cli_wand != (MagickCLI *) NULL); assert(cli_wand->signature == MagickWandSignature); assert(cli_wand->wand.signature == MagickWandSignature); assert(_images != (Image *) NULL); /* _images must be present */ if (cli_wand->wand.debug != MagickFalse) (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), "- List Operator: %s \"%s\" \"%s\"", option, arg1n == (const char *) NULL ? "null" : arg1n, arg2n == (const char *) NULL ? "null" : arg2n); arg1 = arg1n; arg2 = arg2n; /* Interpret Percent Escapes in Arguments - using first image */ if ( (((_process_flags & ProcessInterpretProperities) != 0 ) || ((_option_type & AlwaysInterpretArgsFlag) != 0) ) && ((_option_type & NeverInterpretArgsFlag) == 0) ) { /* Interpret Percent escapes in argument 1 */ if (arg1n != (char *) NULL) { arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception); if (arg1 == (char *) NULL) { CLIWandException(OptionWarning,"InterpretPropertyFailure",option); arg1=arg1n; /* use the given argument as is */ } } if (arg2n != (char *) NULL) { arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception); if (arg2 == (char *) NULL) { CLIWandException(OptionWarning,"InterpretPropertyFailure",option); arg2=arg2n; /* use the given argument as is */ } } } #undef _process_flags #undef _option_type status=MagickTrue; new_images=NewImageList(); switch (*(option+1)) { case 'a': { if (LocaleCompare("append",option+1) == 0) { new_images=AppendImages(_images,IsNormalOp,_exception); break; } if (LocaleCompare("average",option+1) == 0) { CLIWandWarnReplaced("-evaluate-sequence Mean"); (void) CLIListOperatorImages(cli_wand,"-evaluate-sequence","Mean", NULL); break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } case 'c': { if (LocaleCompare("channel-fx",option+1) == 0) { new_images=ChannelFxImage(_images,arg1,_exception); break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image; /* FUTURE - make this a compose option, and thus can be used with layers compose or even compose last image over all other _images. */ new_images=RemoveFirstImageFromList(&_images); clut_image=RemoveLastImageFromList(&_images); /* FUTURE - produce Exception, rather than silent fail */ if (clut_image == (Image *) NULL) break; (void) ClutImage(new_images,clut_image,new_images->interpolate, _exception); clut_image=DestroyImage(clut_image); break; } if (LocaleCompare("coalesce",option+1) == 0) { new_images=CoalesceImages(_images,_exception); break; } if (LocaleCompare("combine",option+1) == 0) { parse=(ssize_t) _images->colorspace; if (_images->number_channels < GetImageListLength(_images)) parse=sRGBColorspace; if ( IfPlusOp ) parse=ParseCommandOption(MagickColorspaceOptions,MagickFalse,arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,"UnrecognizedColorspace",option, arg1); new_images=CombineImages(_images,(ColorspaceType) parse,_exception); break; } if (LocaleCompare("compare",option+1) == 0) { double distortion; Image *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ image=RemoveFirstImageFromList(&_images); reconstruct_image=RemoveFirstImageFromList(&_images); /* FUTURE - produce Exception, rather than silent fail */ if (reconstruct_image == (Image *) NULL) { image=DestroyImage(image); break; } metric=UndefinedErrorMetric; option=GetImageOption(_image_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); new_images=CompareImages(image,reconstruct_image,metric,&distortion, _exception); (void) distortion; reconstruct_image=DestroyImage(reconstruct_image); image=DestroyImage(image); break; } if (LocaleCompare("complex",option+1) == 0) { parse=ParseCommandOption(MagickComplexOptions,MagickFalse,arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,"UnrecognizedEvaluateOperator", option,arg1); new_images=ComplexImages(_images,(ComplexOperator) parse,_exception); break; } if (LocaleCompare("composite",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *source_image; RectangleInfo geometry; /* Compose value from "-compose" option only */ value=GetImageOption(_image_info,"compose"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,value); /* Get "clip-to-self" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(_image_info,"compose:clip-to-self"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(_image_info,"compose:outside-overlay"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(&_images); source_image=RemoveFirstImageFromList(&_images); if (source_image == (Image *) NULL) break; /* FUTURE - produce Exception, rather than silent fail */ /* FUTURE - this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,_exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,_exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity, &geometry); mask_image=RemoveFirstImageFromList(&_images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose,clip_to_self, geometry.x,geometry.y,_exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,_exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,_exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,_exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,_exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,_exception); status&=CompositeImage(clone_image,new_images,OverCompositeOp, clip_to_self,0,0,_exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1); if (IsGeometry(arg2) == MagickFalse) CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1); (void) ParsePageGeometry(_images,arg2,&geometry,_exception); offset.x=geometry.x; offset.y=geometry.y; source_image=_images; if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,arg1,&geometry,_exception); (void) CopyImagePixels(_images,source_image,&geometry,&offset, _exception); break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } case 'd': { if (LocaleCompare("deconstruct",option+1) == 0) { CLIWandWarnReplaced("-layer CompareAny"); (void) CLIListOperatorImages(cli_wand,"-layer","CompareAny",NULL); break; } if (LocaleCompare("delete",option+1) == 0) { if (IfNormalOp) DeleteImages(&_images,arg1,_exception); else DeleteImages(&_images,"-1",_exception); break; } if (LocaleCompare("duplicate",option+1) == 0) { if (IfNormalOp) { const char *p; size_t number_duplicates; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,"InvalidArgument",option, arg1); number_duplicates=(size_t) StringToLong(arg1); p=strchr(arg1,','); if (p == (const char *) NULL) new_images=DuplicateImages(_images,number_duplicates,"-1", _exception); else new_images=DuplicateImages(_images,number_duplicates,p, _exception); } else new_images=DuplicateImages(_images,1,"-1",_exception); AppendImageToList(&_images, new_images); new_images=(Image *) NULL; break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { parse=ParseCommandOption(MagickEvaluateOptions,MagickFalse,arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,"UnrecognizedEvaluateOperator", option,arg1); new_images=EvaluateImages(_images,(MagickEvaluateOperator) parse, _exception); break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } case 'f': { if (LocaleCompare("fft",option+1) == 0) { new_images=ForwardFourierTransformImage(_images,IsNormalOp, _exception); break; } if (LocaleCompare("flatten",option+1) == 0) { /* REDIRECTED to use -layers flatten instead */ (void) CLIListOperatorImages(cli_wand,"-layers",option+1,NULL); break; } if (LocaleCompare("fx",option+1) == 0) { new_images=FxImage(_images,arg1,_exception); break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } case 'h': { if (LocaleCompare("hald-clut",option+1) == 0) { /* FUTURE - make this a compose option (and thus layers compose ) or perhaps compose last image over all other _images. */ Image *hald_image; new_images=RemoveFirstImageFromList(&_images); hald_image=RemoveLastImageFromList(&_images); if (hald_image == (Image *) NULL) break; (void) HaldClutImage(new_images,hald_image,_exception); hald_image=DestroyImage(hald_image); break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } case 'i': { if (LocaleCompare("ift",option+1) == 0) { Image *magnitude_image, *phase_image; magnitude_image=RemoveFirstImageFromList(&_images); phase_image=RemoveFirstImageFromList(&_images); /* FUTURE - produce Exception, rather than silent fail */ if (phase_image == (Image *) NULL) break; new_images=InverseFourierTransformImage(magnitude_image,phase_image, IsNormalOp,_exception); magnitude_image=DestroyImage(magnitude_image); phase_image=DestroyImage(phase_image); break; } if (LocaleCompare("insert",option+1) == 0) { Image *insert_image, *index_image; ssize_t index; if (IfNormalOp && (IsGeometry(arg1) == MagickFalse)) CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1); index=0; insert_image=RemoveLastImageFromList(&_images); if (IfNormalOp) index=(ssize_t) StringToLong(arg1); index_image=insert_image; if (index == 0) PrependImageToList(&_images,insert_image); else if (index == (ssize_t) GetImageListLength(_images)) AppendImageToList(&_images,insert_image); else { index_image=GetImageFromList(_images,index-1); if (index_image == (Image *) NULL) CLIWandExceptArgBreak(OptionError,"NoSuchImage",option,arg1); InsertImageInList(&index_image,insert_image); } _images=GetFirstImageInList(index_image); break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } case 'l': { if (LocaleCompare("layers",option+1) == 0) { parse=ParseCommandOption(MagickLayerOptions,MagickFalse,arg1); if ( parse < 0 ) CLIWandExceptArgBreak(OptionError,"UnrecognizedLayerMethod", option,arg1); switch ((LayerMethod) parse) { case CoalesceLayer: { new_images=CoalesceImages(_images,_exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { new_images=CompareImagesLayers(_images,(LayerMethod) parse, _exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { new_images=MergeImageLayers(_images,(LayerMethod) parse, _exception); break; } case DisposeLayer: { new_images=DisposeImages(_images,_exception); break; } case OptimizeImageLayer: { new_images=OptimizeImageLayers(_images,_exception); break; } case OptimizePlusLayer: { new_images=OptimizePlusImageLayers(_images,_exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(_images,_exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(&_images,_exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(&_images,_exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ new_images=CoalesceImages(_images,_exception); if (new_images == (Image *) NULL) break; _images=DestroyImageList(_images); _images=OptimizeImageLayers(new_images,_exception); if (_images == (Image *) NULL) break; new_images=DestroyImageList(new_images); OptimizeImageTransparency(_images,_exception); (void) RemapImages(_quantize_info,_images,(Image *) NULL, _exception); break; } case CompositeLayer: { Image *source; RectangleInfo geometry; CompositeOperator compose; const char* value; value=GetImageOption(_image_info,"compose"); compose=OverCompositeOp; /* Default to Over */ if (value != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Split image sequence at the first 'NULL:' image. */ source=_images; while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,"NULL") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(_exception,GetMagickModule(), OptionError,"MissingNullSeparator","layers Composite"); break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(_images,&geometry); (void) ParseAbsoluteGeometry(_images->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry(_images->page.width != 0 ? _images->page.width : _images->columns, _images->page.height != 0 ? _images->page.height : _images->rows,_images->gravity,&geometry); /* Compose the two image sequences together */ CompositeLayers(_images,compose,source,geometry.x,geometry.y, _exception); source=DestroyImageList(source); break; } } break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } case 'm': { if (LocaleCompare("map",option+1) == 0) { CLIWandWarnReplaced("+remap"); (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception); break; } if (LocaleCompare("metric",option+1) == 0) { (void) SetImageOption(_image_info,option+1,arg1); break; } if (LocaleCompare("morph",option+1) == 0) { Image *morph_image; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1); morph_image=MorphImages(_images,StringToUnsignedLong(arg1), _exception); if (morph_image == (Image *) NULL) break; _images=DestroyImageList(_images); _images=morph_image; break; } if (LocaleCompare("mosaic",option+1) == 0) { /* REDIRECTED to use -layers mosaic instead */ (void) CLIListOperatorImages(cli_wand,"-layers",option+1,NULL); break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } case 'p': { if (LocaleCompare("poly",option+1) == 0) { double *args; ssize_t count; /* convert argument string into an array of doubles */ args = StringToArrayOfDoubles(arg1,&count,_exception); if (args == (double *) NULL ) CLIWandExceptArgBreak(OptionError,"InvalidNumberList",option,arg1); new_images=PolynomialImage(_images,(size_t) (count >> 1),args, _exception); args=(double *) RelinquishMagickMemory(args); break; } if (LocaleCompare("process",option+1) == 0) { /* FUTURE: better parsing using ScriptToken() from string ??? */ char **arguments; int j, number_arguments; arguments=StringToArgv(arg1,&number_arguments); if (arguments == (char **) NULL) break; if (strchr(arguments[1],'=') != (char *) NULL) { char breaker, quote, *token; const char *arguments; int next, status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg1". */ assert(arg1 != (const char *) NULL); length=strlen(arg1); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; arguments=arg1; token_info=AcquireTokenInfo(); status=Tokenizer(token_info,0,token,length,arguments,"","=", "\"",'\0',&breaker,&next,&quote); token_info=DestroyTokenInfo(token_info); if (status == 0) { const char *argv; argv=(&(arguments[next])); (void) InvokeDynamicImageFilter(token,&_images,1,&argv, _exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],"-",""); (void) InvokeDynamicImageFilter(arguments[1],&_images, number_arguments-2,(const char **) arguments+2,_exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } case 'r': { if (LocaleCompare("remap",option+1) == 0) { (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception); break; } if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(&_images); break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } case 's': { if (LocaleCompare("smush",option+1) == 0) { /* FUTURE: this option needs more work to make better */ ssize_t offset; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1); offset=(ssize_t) StringToLong(arg1); new_images=SmushImages(_images,IsNormalOp,offset,_exception); break; } if (LocaleCompare("subimage",option+1) == 0) { Image *base_image, *compare_image; const char *value; MetricType metric; double similarity; RectangleInfo offset; base_image=GetImageFromList(_images,0); compare_image=GetImageFromList(_images,1); /* Comparision Metric */ metric=UndefinedErrorMetric; value=GetImageOption(_image_info,"metric"); if (value != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,value); new_images=SimilarityImage(base_image,compare_image,metric,0.0, &offset,&similarity,_exception); if (new_images != (Image *) NULL) { char result[MagickPathExtent]; (void) FormatLocaleString(result,MagickPathExtent,"%lf", similarity); (void) SetImageProperty(new_images,"subimage:similarity",result, _exception); (void) FormatLocaleString(result,MagickPathExtent,"%+ld",(long) offset.x); (void) SetImageProperty(new_images,"subimage:x",result, _exception); (void) FormatLocaleString(result,MagickPathExtent,"%+ld",(long) offset.y); (void) SetImageProperty(new_images,"subimage:y",result, _exception); (void) FormatLocaleString(result,MagickPathExtent, "%lux%lu%+ld%+ld",(unsigned long) offset.width,(unsigned long) offset.height,(long) offset.x,(long) offset.y); (void) SetImageProperty(new_images,"subimage:offset",result, _exception); } break; } if (LocaleCompare("swap",option+1) == 0) { Image *p, *q, *swap; ssize_t index, swap_index; index=(-1); swap_index=(-2); if (IfNormalOp) { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(_images,index); q=GetImageFromList(_images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { if (IfNormalOp) CLIWandExceptArgBreak(OptionError,"InvalidImageIndex",option,arg1) else CLIWandExceptionBreak(OptionError,"TwoOrMoreImagesRequired",option); } if (p == q) CLIWandExceptArgBreak(OptionError,"InvalidImageIndex",option,arg1); swap=CloneImage(p,0,0,MagickTrue,_exception); if (swap == (Image *) NULL) CLIWandExceptArgBreak(ResourceLimitError,"MemoryAllocationFailed", option,GetExceptionMessage(errno)); ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,_exception)); ReplaceImageInList(&q,swap); _images=GetFirstImageInList(q); break; } CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } default: CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option); } /* clean up percent escape interpreted strings */ if (arg1 != arg1n ) arg1=DestroyString((char *)arg1); if (arg2 != arg2n ) arg2=DestroyString((char *)arg2); /* if new image list generated, replace existing image list */ if (new_images == (Image *) NULL) return(status == 0 ? MagickFalse : MagickTrue); _images=DestroyImageList(_images); _images=GetFirstImageInList(new_images); return(status == 0 ? MagickFalse : MagickTrue); #undef _image_info #undef _images #undef _exception #undef _draw_info #undef _quantize_info #undef IfNormalOp #undef IfPlusOp #undef IsNormalOp }
CWE-399
183,370
4,469
154589151942532489394039059083891633686
null
null
null
ImageMagick6
61135001a625364e29bdce83832f043eebde7b5a
1
MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y, MagickMax(Ar_image->columns,Cr_image->columns),1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y, MagickMax(Ai_image->columns,Ci_image->columns),1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y, MagickMax(Br_image->columns,Cr_image->columns),1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y, MagickMax(Bi_image->columns,Ci_image->columns),1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(images); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]); Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]); Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]); Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); }
CWE-119
183,371
4,470
19704003200428535121740134227099544030
null
null
null
ImageMagick6
025e77fcb2f45b21689931ba3bf74eac153afa48
1
static PixelChannels **AcquirePixelThreadSet(const Image *images) { const Image *next; PixelChannels **pixels; register ssize_t i; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); }
CWE-119
183,373
4,472
278819893071001947026859904304037240528
null
null
null
ImageMagick6
a906fe9298bf89e01d5272023db687935068849a
1
static PixelChannels **AcquirePixelThreadSet(const Image *image) { PixelChannels **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); }
CWE-119
183,377
4,473
62466630452413277921138939347793692008
null
null
null
ImageMagick6
604588fc35c7585abb7a9e71f69bb82e4389fefc
1
MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (width == 0) return(threshold_image); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); }
CWE-125
183,378
4,474
212875349161019120790655407119857312387
null
null
null
ImageMagick
55e6dc49f1a381d9d511ee2f888fdc3e3c3e3953
1
MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const ssize_t offset, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType number_pixels; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse) { InheritException(exception,&threshold_image->exception); threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Local adaptive threshold. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); number_pixels=(MagickRealType) (width*height); image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket channel_bias, channel_sum; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p, *magick_restrict r; register IndexPacket *magick_restrict threshold_indexes; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) height/2L,image->columns+width,height,exception); q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view); channel_bias=zero; channel_sum=zero; r=p; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) { channel_bias.red+=r[u].red; channel_bias.green+=r[u].green; channel_bias.blue+=r[u].blue; channel_bias.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } channel_sum.red+=r[u].red; channel_sum.green+=r[u].green; channel_sum.blue+=r[u].blue; channel_sum.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } r+=image->columns+width; } for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket mean; mean=zero; r=p; channel_sum.red-=channel_bias.red; channel_sum.green-=channel_bias.green; channel_sum.blue-=channel_bias.blue; channel_sum.opacity-=channel_bias.opacity; channel_sum.index-=channel_bias.index; channel_bias=zero; for (v=0; v < (ssize_t) height; v++) { channel_bias.red+=r[0].red; channel_bias.green+=r[0].green; channel_bias.blue+=r[0].blue; channel_bias.opacity+=r[0].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0); channel_sum.red+=r[width-1].red; channel_sum.green+=r[width-1].green; channel_sum.blue+=r[width-1].blue; channel_sum.opacity+=r[width-1].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+ width-1); r+=image->columns+width; } mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset); mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset); mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset); mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset); if (image->colorspace == CMYKColorspace) mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset); SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ? 0 : QuantumRange); SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ? 0 : QuantumRange); SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ? 0 : QuantumRange); SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ? 0 : QuantumRange); if (image->colorspace == CMYKColorspace) SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex( threshold_indexes+x) <= mean.index) ? 0 : QuantumRange)); p++; q++; } sync=SyncCacheViewAuthenticPixels(threshold_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); }
CWE-125
183,379
4,475
327060304646736815174857176952894624574
null
null
null
ImageMagick
1e59b29e520d2beab73e8c78aacd5f1c0d76196d
1
static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowCUTReaderException(severity,tag) \ { \ if (palette != NULL) \ palette=DestroyImage(palette); \ if (clone_info != NULL) \ clone_info=DestroyImageInfo(clone_info); \ ThrowReaderException(severity,tag); \ } Image *image,*palette; ImageInfo *clone_info; MagickBooleanType status; MagickOffsetType offset; size_t EncodedByte; unsigned char RunCount,RunValue,RunCountMasked; CUTHeader Header; CUTPalHeader PalHeader; ssize_t depth; ssize_t i,j; ssize_t ldblk; unsigned char *BImgBuff=NULL,*ptrB; PixelPacket *q; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read CUT image. */ palette=NULL; clone_info=NULL; Header.Width=ReadBlobLSBShort(image); Header.Height=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0) CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader"); /*---This code checks first line of image---*/ EncodedByte=ReadBlobLSBShort(image); RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; ldblk=0; while((int) RunCountMasked!=0) /*end of line?*/ { i=1; if((int) RunCount<0x80) i=(ssize_t) RunCountMasked; offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET); if (offset < 0) ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/ EncodedByte-=i+1; ldblk+=(ssize_t) RunCountMasked; RunCount=(unsigned char) ReadBlobByte(image); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/ RunCountMasked=RunCount & 0x7F; } if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/ i=0; /*guess a number of bit planes*/ if(ldblk==(int) Header.Width) i=8; if(2*ldblk==(int) Header.Width) i=4; if(8*ldblk==(int) Header.Width) i=1; if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/ depth=i; image->columns=Header.Width; image->rows=Header.Height; image->depth=8; image->colors=(size_t) (GetQuantumRange(1UL*i)+1); if (image_info->ping != MagickFalse) goto Finish; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* ----- Do something with palette ----- */ if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette; i=(ssize_t) strlen(clone_info->filename); j=i; while(--i>0) { if(clone_info->filename[i]=='.') { break; } if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' || clone_info->filename[i]==':' ) { i=j; break; } } (void) CopyMagickString(clone_info->filename+i,".PAL",(size_t) (MaxTextExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { (void) CopyMagickString(clone_info->filename+i,".pal",(size_t) (MaxTextExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info->filename[i]='\0'; if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info=DestroyImageInfo(clone_info); clone_info=NULL; goto NoPalette; } } } if( (palette=AcquireImage(clone_info))==NULL ) goto NoPalette; status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ErasePalette: palette=DestroyImage(palette); palette=NULL; goto NoPalette; } if(palette!=NULL) { (void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId); if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette; PalHeader.Version=ReadBlobLSBShort(palette); PalHeader.Size=ReadBlobLSBShort(palette); PalHeader.FileType=(char) ReadBlobByte(palette); PalHeader.SubType=(char) ReadBlobByte(palette); PalHeader.BoardID=ReadBlobLSBShort(palette); PalHeader.GraphicsMode=ReadBlobLSBShort(palette); PalHeader.MaxIndex=ReadBlobLSBShort(palette); PalHeader.MaxRed=ReadBlobLSBShort(palette); PalHeader.MaxGreen=ReadBlobLSBShort(palette); PalHeader.MaxBlue=ReadBlobLSBShort(palette); (void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId); if (EOFBlob(image)) ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile"); if(PalHeader.MaxIndex<1) goto ErasePalette; image->colors=PalHeader.MaxIndex+1; if (AcquireImageColormap(image,image->colors) == MagickFalse) goto NoMemory; if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/ if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange; if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange; for(i=0;i<=(int) PalHeader.MaxIndex;i++) { /*this may be wrong- I don't know why is palette such strange*/ j=(ssize_t) TellBlob(palette); if((j % 512)>512-6) { j=((j / 512)+1)*512; offset=SeekBlob(palette,j,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxRed) { image->colormap[i].red=ClampToQuantum(((double) image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/ PalHeader.MaxRed); } image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxGreen) { image->colormap[i].green=ClampToQuantum (((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen); } image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxBlue) { image->colormap[i].blue=ClampToQuantum (((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue); } } if (EOFBlob(image)) ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile"); } NoPalette: if(palette==NULL) { image->colors=256; if (AcquireImageColormap(image,image->colors) == MagickFalse) { NoMemory: ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t)image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } } /* ----- Load RLE compressed raster ----- */ BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/ if(BImgBuff==NULL) goto NoMemory; offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET); if (offset < 0) { if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } for (i=0; i < (int) Header.Height; i++) { EncodedByte=ReadBlobLSBShort(image); ptrB=BImgBuff; j=ldblk; RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; while ((int) RunCountMasked != 0) { if((ssize_t) RunCountMasked>j) { /*Wrong Data*/ RunCountMasked=(unsigned char) j; if(j==0) { break; } } if((int) RunCount>0x80) { RunValue=(unsigned char) ReadBlobByte(image); (void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked); } else { (void) ReadBlob(image,(size_t) RunCountMasked,ptrB); } ptrB+=(int) RunCountMasked; j-=(int) RunCountMasked; if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */ RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; } InsertRow(depth,BImgBuff,i,image); } (void) SyncImage(image); /*detect monochrome image*/ if(palette==NULL) { /*attempt to detect binary (black&white) images*/ if ((image->storage_class == PseudoClass) && (SetImageGray(image,&image->exception) != MagickFalse)) { if(GetCutColors(image)==2) { for (i=0; i < (ssize_t)image->colors; i++) { register Quantum sample; sample=ScaleCharToQuantum((unsigned char) i); if(image->colormap[i].red!=sample) goto Finish; if(image->colormap[i].green!=sample) goto Finish; if(image->colormap[i].blue!=sample) goto Finish; } image->colormap[1].red=image->colormap[1].green= image->colormap[1].blue=QuantumRange; for (i=0; i < (ssize_t)image->rows; i++) { q=QueueAuthenticPixels(image,0,i,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (j=0; j < (ssize_t)image->columns; j++) { if (GetPixelRed(q) == ScaleCharToQuantum(1)) { SetPixelRed(q,QuantumRange); SetPixelGreen(q,QuantumRange); SetPixelBlue(q,QuantumRange); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish; } } } } Finish: if (BImgBuff != NULL) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
CWE-20
183,381
4,476
261271325794813798645993342796786859648
null
null
null
miniupnp
86030db849260dd8fb2ed975b9890aef1b62b692
1
GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns) { int r; static const char resp[] = "<u:%sResponse " "xmlns:u=\"%s\">" "<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>" "</u:%sResponse>"; char body[512]; int bodylen; struct NameValueParserData data; char * int_ip, * int_port, * rem_host, * rem_port, * protocol; int opt=0; /*int proto=0;*/ unsigned short iport, rport; if (GETFLAG(IPV6FCFWDISABLEDMASK)) { SoapError(h, 702, "FirewallDisabled"); return; } ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data); int_ip = GetValueFromNameValueList(&data, "InternalClient"); int_port = GetValueFromNameValueList(&data, "InternalPort"); rem_host = GetValueFromNameValueList(&data, "RemoteHost"); rem_port = GetValueFromNameValueList(&data, "RemotePort"); protocol = GetValueFromNameValueList(&data, "Protocol"); if (!int_port || !ext_port || !protocol) { ClearNameValueList(&data); SoapError(h, 402, "Invalid Args"); return; } rport = (unsigned short)atoi(rem_port); iport = (unsigned short)atoi(int_port); /*proto = atoi(protocol);*/ syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol); /* TODO */ r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/ switch(r) { case 1: /* success */ bodylen = snprintf(body, sizeof(body), resp, action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/, opt, action); BuildSendAndCloseSoapResp(h, body, bodylen); break; case -5: /* Protocol not supported */ SoapError(h, 705, "ProtocolNotSupported"); break; default: SoapError(h, 501, "ActionFailed"); } ClearNameValueList(&data); }
CWE-476
183,388
4,482
189077583638678528813673180073531648085
null
null
null
linux
6b3a707736301c2128ca85ce85fb13f60b5e350a
1
static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags) { unsigned nbuf; unsigned idx; struct pipe_buffer *bufs; struct fuse_copy_state cs; struct fuse_dev *fud; size_t rem; ssize_t ret; fud = fuse_get_dev(out); if (!fud) return -EPERM; pipe_lock(pipe); bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer), GFP_KERNEL); if (!bufs) { pipe_unlock(pipe); return -ENOMEM; } nbuf = 0; rem = 0; for (idx = 0; idx < pipe->nrbufs && rem < len; idx++) rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len; ret = -EINVAL; if (rem < len) { pipe_unlock(pipe); goto out; } rem = len; while (rem) { struct pipe_buffer *ibuf; struct pipe_buffer *obuf; BUG_ON(nbuf >= pipe->buffers); BUG_ON(!pipe->nrbufs); ibuf = &pipe->bufs[pipe->curbuf]; obuf = &bufs[nbuf]; if (rem >= ibuf->len) { *obuf = *ibuf; ibuf->ops = NULL; pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1); pipe->nrbufs--; } else { pipe_buf_get(pipe, ibuf); *obuf = *ibuf; obuf->flags &= ~PIPE_BUF_FLAG_GIFT; obuf->len = rem; ibuf->offset += obuf->len; ibuf->len -= obuf->len; } nbuf++; rem -= obuf->len; } pipe_unlock(pipe); fuse_copy_init(&cs, 0, NULL); cs.pipebufs = bufs; cs.nr_segs = nbuf; cs.pipe = pipe; if (flags & SPLICE_F_MOVE) cs.move_pages = 1; ret = fuse_dev_do_write(fud, &cs, len); pipe_lock(pipe); for (idx = 0; idx < nbuf; idx++) pipe_buf_release(pipe, &bufs[idx]); pipe_unlock(pipe); out: kvfree(bufs); return ret; }
CWE-416
183,389
4,483
86844860026443000747795770990831071823
null
null
null
linux
6b3a707736301c2128ca85ce85fb13f60b5e350a
1
void generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { get_page(buf->page); }
CWE-416
183,390
4,484
312685732251810881268650069187153534949
null
null
null
linux
6b3a707736301c2128ca85ce85fb13f60b5e350a
1
static void buffer_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct buffer_ref *ref = (struct buffer_ref *)buf->private; ref->ref++; }
CWE-416
183,393
4,487
60451291240657922891364233045329665091
null
null
null
FFmpeg
1f686d023b95219db933394a7704ad9aa5f01cbb
1
static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->partitioned_frame = 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; }
CWE-125
183,404
4,496
204823687192060739482785663195126643318
null
null
null
ImageMagick
07eebcd72f45c8fd7563d3f9ec5d2bed48f65f36
1
MagickExport int LocaleLowercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l(c,c_locale)); #endif return(tolower(c)); }
CWE-125
183,405
4,497
44140332928912333842950720030218163550
null
null
null
ImageMagick
58d9c46929ca0828edde34d263700c3a5fe8dc3c
1
MagickExport int LocaleLowercase(const int c) { if (c < 0) return(c); #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); }
CWE-125
183,407
4,499
281269707960595026750786236645639829157
null
null
null
openjpeg
5d00b719f4b93b1445e6fb4c766b9a9883c57949
1
void opj_get_all_encoding_parameters( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions ) { /* loop*/ OPJ_UINT32 compno, resno; /* pointers*/ const opj_tcp_t *tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* to store l_dx, l_dy, w and h for each resolution and component.*/ OPJ_UINT32 * lResolutionPtr; /* position in x and y of tile*/ OPJ_UINT32 p, q; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(tileno < p_cp->tw * p_cp->th); /* initializations*/ tcp = &p_cp->tcps [tileno]; l_tccp = tcp->tccps; l_img_comp = p_image->comps; /* position in x and y of tile*/ p = tileno % p_cp->tw; q = tileno / p_cp->tw; /* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */ *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); /* max precision and resolution is 0 (can only grow)*/ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min*/ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* aritmetic variables to calculate*/ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; OPJ_UINT32 l_pdx, l_pdy , l_pw , l_ph; lResolutionPtr = p_resolutions[compno]; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts*/ l_level_no = l_tccp->numresolutions - 1; for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height*/ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; *lResolutionPtr++ = l_pdx; *lResolutionPtr++ = l_pdy; l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no)); /* take the minimum size for l_dx for each comp and resolution*/ *p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dx_min, (OPJ_INT32)l_dx); *p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dy_min, (OPJ_INT32)l_dy); /* various calculations of extents*/ l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); *lResolutionPtr++ = l_pw; *lResolutionPtr++ = l_ph; l_product = l_pw * l_ph; /* update precision*/ if (l_product > *p_max_prec) { *p_max_prec = l_product; } --l_level_no; } ++l_tccp; ++l_img_comp; } }
CWE-190
183,418
4,510
279071337625763916652705127645278808590
null
null
null
linux
5c25f65fd1e42685f7ccd80e0621829c105785d9
1
static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct tun_struct *tun; struct tun_file *tfile = file->private_data; struct net_device *dev; int err; if (tfile->detached) return -EINVAL; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != !!(tun->flags & IFF_MULTI_QUEUE)) return -EINVAL; if (tun_not_capable(tun)) return -EPERM; err = security_tun_dev_open(tun->security); if (err < 0) return err; err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); if (err < 0) return err; if (tun->flags & IFF_MULTI_QUEUE && (tun->numqueues + tun->numdisabled > 1)) { /* One or more queue has already been attached, no need * to initialize the device again. */ return 0; } } else { char *name; unsigned long flags = 0; int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? MAX_TAP_QUEUES : 1; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= IFF_TUN; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= IFF_TAP; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, NET_NAME_UNKNOWN, tun_setup, queues, queues); if (!dev) return -ENOMEM; err = dev_get_valid_name(net, dev, name); if (err) goto err_free_dev; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; dev->ifindex = tfile->ifindex; dev->sysfs_groups[0] = &tun_attr_group; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); tun->align = NET_SKB_PAD; tun->filter_attached = false; tun->sndbuf = tfile->socket.sk->sk_sndbuf; tun->rx_batched = 0; tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); if (!tun->pcpu_stats) { err = -ENOMEM; goto err_free_dev; } spin_lock_init(&tun->lock); err = security_tun_dev_alloc_security(&tun->security); if (err < 0) goto err_free_stat; tun_net_init(dev); tun_flow_init(tun); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX; dev->features = dev->hw_features | NETIF_F_LLTX; dev->vlan_features = dev->features & ~(NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX); INIT_LIST_HEAD(&tun->disabled); err = tun_attach(tun, file, false); if (err < 0) goto err_free_flow; err = register_netdevice(tun->dev); if (err < 0) goto err_detach; } netif_carrier_on(tun->dev); tun_debug(KERN_INFO, tun, "tun_set_iff\n"); tun->flags = (tun->flags & ~TUN_FEATURES) | (ifr->ifr_flags & TUN_FEATURES); /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_tx_wake_all_queues(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_detach: tun_detach_all(dev); /* register_netdevice() already called tun_free_netdev() */ goto err_free_dev; err_free_flow: tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); err_free_stat: free_percpu(tun->pcpu_stats); err_free_dev: free_netdev(dev); return err; }
CWE-476
183,419
4,511
55157606478905351088416785190600943342
null
null
null
Chrome
befb46ae3385fa13975521e9a2281e35805b339e
1
void FrameLoader::receivedFirstData() { begin(m_workingURL, false); dispatchDidCommitLoad(); dispatchWindowObjectAvailable(); if (m_documentLoader) { String ptitle = m_documentLoader->title(); if (!ptitle.isNull()) m_client->dispatchDidReceiveTitle(ptitle); } m_workingURL = KURL(); double delay; String url; if (!m_documentLoader) return; if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField("Refresh"), false, delay, url)) return; if (url.isEmpty()) url = m_URL.string(); else url = m_frame->document()->completeURL(url).string(); m_frame->redirectScheduler()->scheduleRedirect(delay, url); }
183,424
4,515
205899044910149510582162125809640835040
null
null
null
Chrome
1a5af201a654bf80ce1bd6721b31a97311ae67a6
1
void PageClickTracker::handleEvent(const WebDOMEvent& event) { last_node_clicked_.reset(); DCHECK(event.isMouseEvent()); const WebDOMMouseEvent mouse_event = event.toConst<WebDOMMouseEvent>(); DCHECK(mouse_event.buttonDown()); if (mouse_event.button() != 0) return; // We are only interested in left clicks. last_node_clicked_ = mouse_event.target(); was_focused_ = (GetFocusedNode() == last_node_clicked_); }
183,430
4,521
302350681237982947939244439638556339510
null
null
null
Chrome
59f5e0204cbc0e524b2687fb1beddda82047d16d
1
void AutoFillManager::FormSubmitted(const FormData& form) { if (!IsAutoFillEnabled()) return; if (tab_contents_->profile()->IsOffTheRecord()) return; upload_form_structure_.reset(new FormStructure(form)); if (!upload_form_structure_->IsAutoFillable()) return; DeterminePossibleFieldTypes(upload_form_structure_.get()); HandleSubmit(); }
183,431
4,522
94810593785846535943546230214391739041
null
null
null
Chrome
5041f984669fe3a989a84c348eb838c8f7233f6b
1
void RenderView::willClose(WebFrame* frame) { if (!frame->parent()) { const GURL& url = frame->url(); if (url.SchemeIs("http") || url.SchemeIs("https")) DumpLoadHistograms(); } WebDataSource* ds = frame->dataSource(); NavigationState* navigation_state = NavigationState::FromDataSource(ds); navigation_state->user_script_idle_scheduler()->Cancel(); autofill_helper_.FrameWillClose(frame); }
183,432
4,523
16220807621299258109480242793635336435
null
null
null
Chrome
26917dc40fb9dc7ef74fa9e0e8fd221e9b857993
1
void LayerTilerChromium::resizeLayer(const IntSize& size) { if (m_layerSize == size) return; int width = (size.width() + m_tileSize.width() - 1) / m_tileSize.width(); int height = (size.height() + m_tileSize.height() - 1) / m_tileSize.height(); Vector<OwnPtr<Tile> > newTiles; newTiles.resize(width * height); for (int j = 0; j < m_layerTileSize.height(); ++j) for (int i = 0; i < m_layerTileSize.width(); ++i) newTiles[i + j * width].swap(m_tiles[i + j * m_layerTileSize.width()]); m_tiles.swap(newTiles); m_layerSize = size; m_layerTileSize = IntSize(width, height); }
183,439
4,530
215476668720938221199136287510165623553
null
null
null
Chrome
647c3a9f217a9236052e18c7b032669863dd1734
1
void USBMountObserver::MountChanged(chromeos::MountLibrary* obj, chromeos::MountEventType evt, const std::string& path) { if (evt == chromeos::DISK_ADDED) { const chromeos::MountLibrary::DiskVector& disks = obj->disks(); for (size_t i = 0; i < disks.size(); ++i) { chromeos::MountLibrary::Disk disk = disks[i]; if (disk.device_path == path) { if (disk.is_parent) { if (!disk.has_media) { RemoveBrowserFromVector(disk.system_path); } } else if (!obj->MountPath(path.c_str())) { RemoveBrowserFromVector(disk.system_path); } } } LOG(INFO) << "Got added mount:" << path; } else if (evt == chromeos::DISK_REMOVED || evt == chromeos::DEVICE_REMOVED) { RemoveBrowserFromVector(path); } else if (evt == chromeos::DISK_CHANGED) { BrowserIterator iter = FindBrowserForPath(path); LOG(INFO) << "Got changed mount:" << path; if (iter == browsers_.end() && iter->browser) { const chromeos::MountLibrary::DiskVector& disks = obj->disks(); for (size_t i = 0; i < disks.size(); ++i) { if (disks[i].device_path == path) { if (!disks[i].mount_path.empty()) { iter = FindBrowserForPath(disks[i].system_path); if (iter != browsers_.end() && iter->browser) { std::string url = kFilebrowseURLHash; url += disks[i].mount_path; TabContents* tab = iter->browser->GetSelectedTabContents(); iter->browser->window()->SetBounds(gfx::Rect( 0, 0, FileBrowseUI::kPopupWidth, FileBrowseUI::kPopupHeight)); tab->OpenURL(GURL(url), GURL(), CURRENT_TAB, PageTransition::LINK); tab->NavigateToPendingEntry(NavigationController::RELOAD); iter->device_path = path; } else { OpenFileBrowse(disks[i].mount_path, disks[i].device_path, false); } } return; } } } } else if (evt == chromeos::DEVICE_ADDED) { LOG(INFO) << "Got device added" << path; OpenFileBrowse(kFilebrowseScanning, path, true); } else if (evt == chromeos::DEVICE_SCANNED) { LOG(INFO) << "Got device scanned:" << path; } }
183,490
4,574
301925784993327327281571038504275339875
null
null
null
Chrome
acae973ac6297404fe3c9b389b69bf3c7e62cd19
1
v8::Handle<v8::Value> V8DOMWrapper::convertEventToV8Object(Event* event) { if (!event) return v8::Null(); v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(event); if (!wrapper.IsEmpty()) return wrapper; V8ClassIndex::V8WrapperType type = V8ClassIndex::EVENT; if (event->isUIEvent()) { if (event->isKeyboardEvent()) type = V8ClassIndex::KEYBOARDEVENT; else if (event->isTextEvent()) type = V8ClassIndex::TEXTEVENT; else if (event->isMouseEvent()) type = V8ClassIndex::MOUSEEVENT; else if (event->isWheelEvent()) type = V8ClassIndex::WHEELEVENT; #if ENABLE(SVG) else if (event->isSVGZoomEvent()) type = V8ClassIndex::SVGZOOMEVENT; #endif else type = V8ClassIndex::UIEVENT; } else if (event->isMutationEvent()) type = V8ClassIndex::MUTATIONEVENT; else if (event->isOverflowEvent()) type = V8ClassIndex::OVERFLOWEVENT; else if (event->isMessageEvent()) type = V8ClassIndex::MESSAGEEVENT; else if (event->isProgressEvent()) { if (event->isXMLHttpRequestProgressEvent()) type = V8ClassIndex::XMLHTTPREQUESTPROGRESSEVENT; else type = V8ClassIndex::PROGRESSEVENT; } else if (event->isWebKitAnimationEvent()) type = V8ClassIndex::WEBKITANIMATIONEVENT; else if (event->isWebKitTransitionEvent()) type = V8ClassIndex::WEBKITTRANSITIONEVENT; v8::Handle<v8::Object> result = instantiateV8Object(type, V8ClassIndex::EVENT, event); if (result.IsEmpty()) { return v8::Null(); } event->ref(); // fast ref setJSWrapperForDOMObject(event, v8::Persistent<v8::Object>::New(result)); return result; }
183,497
4,580
15378929504066594532098227499148230262
null
null
null
Chrome
7473b624aff7e1db5b22d7a856d1f21509fa04bc
1
void ResourceMessageFilter::OnClipboardWriteObjectsAsync( const Clipboard::ObjectMap& objects) { Clipboard::ObjectMap* long_living_objects = new Clipboard::ObjectMap(objects); ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, new WriteClipboardTask(long_living_objects)); }
183,512
4,592
55852204926604759670570320186049612200
null
null
null
Chrome
019c7acc36b8893d060684fb3b5deb6156c92b9e
1
void NotificationService::RemoveObserver(NotificationObserver* observer, NotificationType type, const NotificationSource& source) { DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT); DCHECK(HasKey(observers_[type.value], source)); NotificationObserverList* observer_list = observers_[type.value][source.map_key()]; if (observer_list) { observer_list->RemoveObserver(observer); #ifndef NDEBUG --observer_counts_[type.value]; #endif } }
183,605
4,671
302473336758104063057131933053452231213
null
null
null
Chrome
482628d8157ded5d6124bcf39c8b5afc7906f72d
1
void setSharedTimerFireTime(double fireTime) { ASSERT(sharedTimerFiredFunction); double interval = fireTime - currentTime(); guint intervalInMS; if (interval < 0) intervalInMS = 0; else { interval *= 1000; intervalInMS = (guint)interval; } stopSharedTimer(); if (intervalInMS == 0) sharedTimer = g_idle_add_full(G_PRIORITY_DEFAULT, timeout_cb, NULL, NULL); else sharedTimer = g_timeout_add_full(G_PRIORITY_DEFAULT, intervalInMS, timeout_cb, NULL, NULL); }
183,606
4,672
89438215178905091120216754121600007201
null
null
null
Chrome
223c449d19eb5d889bc828e011c1a23e5d52b4c9
1
FilePath GetSuggestedFilename(const GURL& url, const std::string& content_disposition, const std::string& referrer_charset, const FilePath& default_name) { static const FilePath::CharType kFinalFallbackName[] = FILE_PATH_LITERAL("download"); if (url.SchemeIs("about") || url.SchemeIs("data")) { return default_name.empty() ? FilePath(kFinalFallbackName) : default_name; } const std::string filename_from_cd = GetFileNameFromCD(content_disposition, referrer_charset); #if defined(OS_WIN) FilePath::StringType filename = UTF8ToWide(filename_from_cd); #elif defined(OS_POSIX) FilePath::StringType filename = filename_from_cd; #endif if (!filename.empty()) { filename = FilePath(filename).BaseName().value(); TrimString(filename, FILE_PATH_LITERAL("."), &filename); } if (filename.empty()) { if (url.is_valid()) { const std::string unescaped_url_filename = UnescapeURLComponent( url.ExtractFileName(), UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS); #if defined(OS_WIN) filename = UTF8ToWide(unescaped_url_filename); #elif defined(OS_POSIX) filename = unescaped_url_filename; #endif } } TrimString(filename, FILE_PATH_LITERAL("."), &filename); if (filename.empty()) { if (!default_name.empty()) { filename = default_name.value(); } else if (url.is_valid()) { filename = url.host().empty() ? kFinalFallbackName : #if defined(OS_WIN) UTF8ToWide(url.host()); #elif defined(OS_POSIX) url.host(); #endif } else { NOTREACHED(); } } file_util::ReplaceIllegalCharactersInPath(&filename, '-'); return FilePath(filename); }
183,607
4,673
220682606199448402671757351203534326856
null
null
null
Chrome
8d4d589fc7d0a8f2fbb7a468e00f264fe54c7981
1
CachedCSSStyleSheet* Cache::requestUserCSSStyleSheet(DocLoader* docLoader, const String& url, const String& charset) { CachedCSSStyleSheet* userSheet = new CachedCSSStyleSheet(url, charset); userSheet->setInCache(true); userSheet->load(docLoader, false, true, false); if (!disabled()) m_resources.set(url, userSheet); else userSheet->setInCache(false); return userSheet; }
183,622
4,686
263818733458563921754155615789322462605
null
null
null
Chrome
690d0a9175790c4bd3abd066932bc08203c164ca
1
bool ChildProcessSecurityPolicy::CanRequestURL( int renderer_id, const GURL& url) { if (!url.is_valid()) return false; // Can't request invalid URLs. if (IsWebSafeScheme(url.scheme())) return true; // The scheme has been white-listed for every renderer. if (IsPseudoScheme(url.scheme())) { if (url.SchemeIs(chrome::kViewSourceScheme) || url.SchemeIs(chrome::kPrintScheme)) { return CanRequestURL(renderer_id, GURL(url.path())); } if (LowerCaseEqualsASCII(url.spec(), chrome::kAboutBlankURL)) return true; // Every renderer can request <about:blank>. return false; } if (!URLRequest::IsHandledURL(url)) return true; // This URL request is destined for ShellExecute. { AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(renderer_id); if (state == security_state_.end()) return false; return state->second->CanRequestURL(url); } }
183,623
4,687
329310846951076897153858583387308582008
null
null
null
Chrome
3290c948762c47292fb388de8318859ee22b6688
1
void MenuGtk::BuildMenuIn(GtkWidget* menu, const MenuCreateMaterial* menu_data, GtkAccelGroup* accel_group) { GtkWidget* last_menu_item = NULL; for (; menu_data->type != MENU_END; ++menu_data) { GtkWidget* menu_item = NULL; std::string label; if (menu_data->label_argument) { label = l10n_util::GetStringFUTF8( menu_data->label_id, l10n_util::GetStringUTF16(menu_data->label_argument)); } else if (menu_data->label_id) { label = l10n_util::GetStringUTF8(menu_data->label_id); } else if (menu_data->type != MENU_SEPARATOR) { label = delegate_->GetLabel(menu_data->id); DCHECK(!label.empty()); } label = ConvertAcceleratorsFromWindowsStyle(label); switch (menu_data->type) { case MENU_RADIO: if (GTK_IS_RADIO_MENU_ITEM(last_menu_item)) { menu_item = gtk_radio_menu_item_new_with_mnemonic_from_widget( GTK_RADIO_MENU_ITEM(last_menu_item), label.c_str()); } else { menu_item = gtk_radio_menu_item_new_with_mnemonic( NULL, label.c_str()); } break; case MENU_CHECKBOX: menu_item = gtk_check_menu_item_new_with_mnemonic(label.c_str()); break; case MENU_SEPARATOR: menu_item = gtk_separator_menu_item_new(); break; case MENU_NORMAL: default: menu_item = gtk_menu_item_new_with_mnemonic(label.c_str()); break; } if (menu_data->submenu) { GtkWidget* submenu = gtk_menu_new(); BuildMenuIn(submenu, menu_data->submenu, accel_group); gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu); } else if (menu_data->custom_submenu) { gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), menu_data->custom_submenu->menu_.get()); submenus_we_own_.push_back(menu_data->custom_submenu); } if ((menu_data->only_show || accel_group) && menu_data->accel_key) { gtk_widget_add_accelerator(menu_item, "activate", menu_data->only_show ? dummy_accel_group_ : accel_group, menu_data->accel_key, GdkModifierType(menu_data->accel_modifiers), GTK_ACCEL_VISIBLE); } g_object_set_data(G_OBJECT(menu_item), "menu-data", const_cast<MenuCreateMaterial*>(menu_data)); g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(OnMenuItemActivated), this); gtk_widget_show(menu_item); gtk_menu_append(menu, menu_item); last_menu_item = menu_item; } }
183,624
4,688
158135429307847965906919411130373733508
null
null
null
Chrome
3eb1f512d8646db3a70aaef108a8f5ad8b3f013d
1
PassRefPtr<CSSRuleList> CSSStyleSheet::cssRules(bool omitCharsetRules) { if (doc() && !doc()->securityOrigin()->canRequest(baseURL())) return 0; return CSSRuleList::create(this, omitCharsetRules); }
183,627
4,691
14427476023254648635294502104795630997
null
null
null
Chrome
7d8cefdf6d0e457b7a855c9503684f1058c2a356
1
WebGLObject::WebGLObject(WebGLRenderingContext* context) : m_object(0) , m_attachmentCount(0) , m_deleted(false) { }
CWE-119
183,631
4,694
113581393010610799217508960162567347666
null
null
null
Chrome
77b498aa18e610ed8ac3863ae048573d4f943b16
1
InotifyReaderTask(InotifyReader* reader, int inotify_fd, int shutdown_fd) : reader_(reader), inotify_fd_(inotify_fd), shutdown_fd_(shutdown_fd) { }
183,645
4,707
297574273698580522437879368471330078494
null
null
null
Chrome
f1a142d29ad1dfaecd3b609051b476440289ec72
1
bool PrintWebViewHelper::PrintPreviewContext::CreatePreviewDocument( PrintMsg_Print_Params* print_params, const std::vector<int>& pages) { DCHECK_EQ(INITIALIZED, state_); state_ = RENDERING; print_params_.reset(new PrintMsg_Print_Params(*print_params)); metafile_.reset(new printing::PreviewMetafile); if (!metafile_->Init()) { set_error(PREVIEW_ERROR_METAFILE_INIT_FAILED); LOG(ERROR) << "PreviewMetafile Init failed"; return false; } prep_frame_view_.reset(new PrepareFrameAndViewForPrint(*print_params, frame(), node())); UpdatePrintableSizeInPrintParameters(frame_, node_, prep_frame_view_.get(), print_params); total_page_count_ = prep_frame_view_->GetExpectedPageCount(); if (total_page_count_ == 0) { LOG(ERROR) << "CreatePreviewDocument got 0 page count"; set_error(PREVIEW_ERROR_ZERO_PAGES); return false; } int selected_page_count = pages.size(); current_page_index_ = 0; print_ready_metafile_page_count_ = selected_page_count; pages_to_render_ = pages; if (selected_page_count == 0) { print_ready_metafile_page_count_ = total_page_count_; for (int i = 0; i < total_page_count_; ++i) pages_to_render_.push_back(i); } else if (generate_draft_pages_) { int pages_index = 0; for (int i = 0; i < total_page_count_; ++i) { if (pages_index < selected_page_count && i == pages[pages_index]) { pages_index++; continue; } pages_to_render_.push_back(i); } } document_render_time_ = base::TimeDelta(); begin_time_ = base::TimeTicks::Now(); return true; }
183,687
4,743
278638495242452476968410636441591663260
null
null
null
Chrome
d662b905d30cec7899bbb15140dcfacd73506167
1
BlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate( TabContents* tab_contents, const string16& utf16_name) : PluginInfoBarDelegate(tab_contents, utf16_name) { UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Shown")); std::string name = UTF16ToUTF8(utf16_name); if (name == webkit::npapi::PluginGroup::kJavaGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.Java")); else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.QuickTime")); else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.Shockwave")); else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.RealPlayer")); }
CWE-264
183,756
4,803
129354267864543594181509919973717611216
null
null
null
Chrome
d304b5ec1b16766ea2cb552a27dc14df848d6a0e
1
void FFmpegVideoDecodeEngine::Initialize( MessageLoop* message_loop, VideoDecodeEngine::EventHandler* event_handler, VideoDecodeContext* context, const VideoDecoderConfig& config) { static const int kDecodeThreads = 2; static const int kMaxDecodeThreads = 16; codec_context_ = avcodec_alloc_context(); codec_context_->pix_fmt = PIX_FMT_YUV420P; codec_context_->codec_type = AVMEDIA_TYPE_VIDEO; codec_context_->codec_id = VideoCodecToCodecID(config.codec()); codec_context_->coded_width = config.width(); codec_context_->coded_height = config.height(); frame_rate_numerator_ = config.frame_rate_numerator(); frame_rate_denominator_ = config.frame_rate_denominator(); if (config.extra_data() != NULL) { codec_context_->extradata_size = config.extra_data_size(); codec_context_->extradata = reinterpret_cast<uint8_t*>(av_malloc(config.extra_data_size())); memcpy(codec_context_->extradata, config.extra_data(), config.extra_data_size()); } codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK; codec_context_->error_recognition = FF_ER_CAREFUL; AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id); int decode_threads = (codec_context_->codec_id == CODEC_ID_THEORA) ? 1 : kDecodeThreads; const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads)); if ((!threads.empty() && !base::StringToInt(threads, &decode_threads)) || decode_threads < 0 || decode_threads > kMaxDecodeThreads) { decode_threads = kDecodeThreads; } av_frame_.reset(avcodec_alloc_frame()); VideoCodecInfo info; info.success = false; info.provides_buffers = true; info.stream_info.surface_type = VideoFrame::TYPE_SYSTEM_MEMORY; info.stream_info.surface_format = GetSurfaceFormat(); info.stream_info.surface_width = config.surface_width(); info.stream_info.surface_height = config.surface_height(); bool buffer_allocated = true; frame_queue_available_.clear(); for (size_t i = 0; i < Limits::kMaxVideoFrames; ++i) { scoped_refptr<VideoFrame> video_frame; VideoFrame::CreateFrame(VideoFrame::YV12, config.width(), config.height(), kNoTimestamp, kNoTimestamp, &video_frame); if (!video_frame.get()) { buffer_allocated = false; break; } frame_queue_available_.push_back(video_frame); } if (codec && avcodec_thread_init(codec_context_, decode_threads) >= 0 && avcodec_open(codec_context_, codec) >= 0 && av_frame_.get() && buffer_allocated) { info.success = true; } event_handler_ = event_handler; event_handler_->OnInitializeComplete(info); }
CWE-119
183,761
4,807
158059457852489333212445240191770897439
null
null
null
Chrome
52dac009556881941c60d378e34867cdb2fd00a0
1
FilePath ExtensionPrefs::GetExtensionPath(const std::string& extension_id) { const DictionaryValue* dict = GetExtensionPref(extension_id); std::string path; if (!dict->GetString(kPrefPath, &path)) return FilePath(); return install_directory_.Append(FilePath::FromWStringHack(UTF8ToWide(path))); }
CWE-119
183,766
4,811
39958822954184996922358699327568838503
null
null
null
Chrome
7155d7caafd2aa1fb822dc5672c90ea446247e8d
1
void ScaleYUVToRGB32(const uint8* y_buf, const uint8* u_buf, const uint8* v_buf, uint8* rgb_buf, int source_width, int source_height, int width, int height, int y_pitch, int uv_pitch, int rgb_pitch, YUVType yuv_type, Rotate view_rotate, ScaleFilter filter) { const int kFilterBufferSize = 4096; if (source_width > kFilterBufferSize || view_rotate) filter = FILTER_NONE; unsigned int y_shift = yuv_type; if ((view_rotate == ROTATE_180) || (view_rotate == ROTATE_270) || (view_rotate == MIRROR_ROTATE_0) || (view_rotate == MIRROR_ROTATE_90)) { y_buf += source_width - 1; u_buf += source_width / 2 - 1; v_buf += source_width / 2 - 1; source_width = -source_width; } if ((view_rotate == ROTATE_90) || (view_rotate == ROTATE_180) || (view_rotate == MIRROR_ROTATE_90) || (view_rotate == MIRROR_ROTATE_180)) { y_buf += (source_height - 1) * y_pitch; u_buf += ((source_height >> y_shift) - 1) * uv_pitch; v_buf += ((source_height >> y_shift) - 1) * uv_pitch; source_height = -source_height; } if (width == 0 || height == 0) return; int source_dx = source_width * kFractionMax / width; int source_dy = source_height * kFractionMax / height; #if USE_MMX && defined(_MSC_VER) int source_dx_uv = source_dx; #endif if ((view_rotate == ROTATE_90) || (view_rotate == ROTATE_270)) { int tmp = height; height = width; width = tmp; tmp = source_height; source_height = source_width; source_width = tmp; int original_dx = source_dx; int original_dy = source_dy; source_dx = ((original_dy >> kFractionBits) * y_pitch) << kFractionBits; #if USE_MMX && defined(_MSC_VER) source_dx_uv = ((original_dy >> kFractionBits) * uv_pitch) << kFractionBits; #endif source_dy = original_dx; if (view_rotate == ROTATE_90) { y_pitch = -1; uv_pitch = -1; source_height = -source_height; } else { y_pitch = 1; uv_pitch = 1; } } uint8 yuvbuf[16 + kFilterBufferSize * 3 + 16]; uint8* ybuf = reinterpret_cast<uint8*>(reinterpret_cast<uintptr_t>(yuvbuf + 15) & ~15); uint8* ubuf = ybuf + kFilterBufferSize; uint8* vbuf = ubuf + kFilterBufferSize; int yscale_fixed = (source_height << kFractionBits) / height; for (int y = 0; y < height; ++y) { uint8* dest_pixel = rgb_buf + y * rgb_pitch; int source_y_subpixel = (y * yscale_fixed); if (yscale_fixed >= (kFractionMax * 2)) { source_y_subpixel += kFractionMax / 2; // For 1/2 or less, center filter. } int source_y = source_y_subpixel >> kFractionBits; const uint8* y0_ptr = y_buf + source_y * y_pitch; const uint8* y1_ptr = y0_ptr + y_pitch; const uint8* u0_ptr = u_buf + (source_y >> y_shift) * uv_pitch; const uint8* u1_ptr = u0_ptr + uv_pitch; const uint8* v0_ptr = v_buf + (source_y >> y_shift) * uv_pitch; const uint8* v1_ptr = v0_ptr + uv_pitch; int source_y_fraction = (source_y_subpixel & kFractionMask) >> 8; int source_uv_fraction = ((source_y_subpixel >> y_shift) & kFractionMask) >> 8; const uint8* y_ptr = y0_ptr; const uint8* u_ptr = u0_ptr; const uint8* v_ptr = v0_ptr; if (filter & media::FILTER_BILINEAR_V) { if (yscale_fixed != kFractionMax && source_y_fraction && ((source_y + 1) < source_height)) { FilterRows(ybuf, y0_ptr, y1_ptr, source_width, source_y_fraction); } else { memcpy(ybuf, y0_ptr, source_width); } y_ptr = ybuf; ybuf[source_width] = ybuf[source_width-1]; int uv_source_width = (source_width + 1) / 2; if (yscale_fixed != kFractionMax && source_uv_fraction && (((source_y >> y_shift) + 1) < (source_height >> y_shift))) { FilterRows(ubuf, u0_ptr, u1_ptr, uv_source_width, source_uv_fraction); FilterRows(vbuf, v0_ptr, v1_ptr, uv_source_width, source_uv_fraction); } else { memcpy(ubuf, u0_ptr, uv_source_width); memcpy(vbuf, v0_ptr, uv_source_width); } u_ptr = ubuf; v_ptr = vbuf; ubuf[uv_source_width] = ubuf[uv_source_width - 1]; vbuf[uv_source_width] = vbuf[uv_source_width - 1]; } if (source_dx == kFractionMax) { // Not scaled FastConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, width); } else { if (filter & FILTER_BILINEAR_H) { LinearScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, width, source_dx); } else { #if USE_MMX && defined(_MSC_VER) if (width == (source_width * 2)) { DoubleYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, width); } else if ((source_dx & kFractionMask) == 0) { ConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, width, source_dx >> kFractionBits); } else if (source_dx_uv == source_dx) { // Not rotated. ScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, width, source_dx); } else { RotateConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, width, source_dx >> kFractionBits, source_dx_uv >> kFractionBits); } #else ScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, width, source_dx); #endif } } } EMMS(); }
CWE-119
183,771
4,816
253694277743522014414394997272058500478
null
null
null
Chrome
d82e91c46938520466e9d7c695e0bc638fc70970
1
NativeBrowserFrame* NativeBrowserFrame::CreateNativeBrowserFrame( BrowserFrame* browser_frame, BrowserView* browser_view) { if (views::Widget::IsPureViews()) return new BrowserFrameViews(browser_frame, browser_view); return new BrowserFrameGtk(browser_frame, browser_view); }
CWE-399
183,772
4,817
284461539438023946011195335554908292067
null
null
null
Chrome
061ddbae1ee31476b57ea44a953970ab2fe8aca1
1
void DocumentWriter::setDecoder(TextResourceDecoder* decoder) { m_decoder = decoder; }
CWE-399
183,775
4,819
124821018363863959940142884484083488316
null
null
null
Chrome
3a766e0115e9799db766a88554b9ab12ee5bf2a4
1
xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op) { int total = 0; int equal, ret; xmlXPathCompExprPtr comp; xmlXPathObjectPtr arg1, arg2; xmlNodePtr bak; xmlDocPtr bakd; int pp; int cs; CHECK_ERROR0; comp = ctxt->comp; switch (op->op) { case XPATH_OP_END: return (0); case XPATH_OP_AND: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 0)) return (total); arg2 = valuePop(ctxt); ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); arg1 = valuePop(ctxt); arg1->boolval &= arg2->boolval; valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_OR: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 1)) return (total); arg2 = valuePop(ctxt); ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); arg1 = valuePop(ctxt); arg1->boolval |= arg2->boolval; valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_EQUAL: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value) equal = xmlXPathEqualValues(ctxt); else equal = xmlXPathNotEqualValues(ctxt); valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, equal)); return (total); case XPATH_OP_CMP: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; ret = xmlXPathCompareValues(ctxt, op->value, op->value2); valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, ret)); return (total); case XPATH_OP_PLUS: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) { ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); } CHECK_ERROR0; if (op->value == 0) xmlXPathSubValues(ctxt); else if (op->value == 1) xmlXPathAddValues(ctxt); else if (op->value == 2) xmlXPathValueFlipSign(ctxt); else if (op->value == 3) { CAST_TO_NUMBER; CHECK_TYPE0(XPATH_NUMBER); } return (total); case XPATH_OP_MULT: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value == 0) xmlXPathMultValues(ctxt); else if (op->value == 1) xmlXPathDivValues(ctxt); else if (op->value == 2) xmlXPathModValues(ctxt); return (total); case XPATH_OP_UNION: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; CHECK_TYPE0(XPATH_NODESET); arg2 = valuePop(ctxt); CHECK_TYPE0(XPATH_NODESET); arg1 = valuePop(ctxt); if ((arg1->nodesetval == NULL) || ((arg2->nodesetval != NULL) && (arg2->nodesetval->nodeNr != 0))) { arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval, arg2->nodesetval); } valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_ROOT: xmlXPathRoot(ctxt); return (total); case XPATH_OP_NODE: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node)); return (total); case XPATH_OP_RESET: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; ctxt->context->node = NULL; return (total); case XPATH_OP_COLLECT:{ if (op->ch1 == -1) return (total); total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, NULL, 0); return (total); } case XPATH_OP_VALUE: valuePush(ctxt, xmlXPathCacheObjectCopy(ctxt->context, (xmlXPathObjectPtr) op->value4)); return (total); case XPATH_OP_VARIABLE:{ xmlXPathObjectPtr val; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (op->value5 == NULL) { val = xmlXPathVariableLookup(ctxt->context, op->value4); if (val == NULL) { ctxt->error = XPATH_UNDEF_VARIABLE_ERROR; return(0); } valuePush(ctxt, val); } else { const xmlChar *URI; URI = xmlXPathNsLookup(ctxt->context, op->value5); if (URI == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: variable %s bound to undefined prefix %s\n", (char *) op->value4, (char *)op->value5); return (total); } val = xmlXPathVariableLookupNS(ctxt->context, op->value4, URI); if (val == NULL) { ctxt->error = XPATH_UNDEF_VARIABLE_ERROR; return(0); } valuePush(ctxt, val); } return (total); } case XPATH_OP_FUNCTION:{ xmlXPathFunction func; const xmlChar *oldFunc, *oldFuncURI; int i; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (ctxt->valueNr < op->value) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: parameter error\n"); ctxt->error = XPATH_INVALID_OPERAND; return (total); } for (i = 0; i < op->value; i++) if (ctxt->valueTab[(ctxt->valueNr - 1) - i] == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: parameter error\n"); ctxt->error = XPATH_INVALID_OPERAND; return (total); } if (op->cache != NULL) XML_CAST_FPTR(func) = op->cache; else { const xmlChar *URI = NULL; if (op->value5 == NULL) func = xmlXPathFunctionLookup(ctxt->context, op->value4); else { URI = xmlXPathNsLookup(ctxt->context, op->value5); if (URI == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: function %s bound to undefined prefix %s\n", (char *)op->value4, (char *)op->value5); return (total); } func = xmlXPathFunctionLookupNS(ctxt->context, op->value4, URI); } if (func == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: function %s not found\n", (char *)op->value4); XP_ERROR0(XPATH_UNKNOWN_FUNC_ERROR); } op->cache = XML_CAST_FPTR(func); op->cacheURI = (void *) URI; } oldFunc = ctxt->context->function; oldFuncURI = ctxt->context->functionURI; ctxt->context->function = op->value4; ctxt->context->functionURI = op->cacheURI; func(ctxt, op->value); ctxt->context->function = oldFunc; ctxt->context->functionURI = oldFuncURI; return (total); } case XPATH_OP_ARG: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); ctxt->context->contextSize = cs; ctxt->context->proximityPosition = pp; ctxt->context->node = bak; ctxt->context->doc = bakd; CHECK_ERROR0; if (op->ch2 != -1) { total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); ctxt->context->doc = bakd; ctxt->context->node = bak; CHECK_ERROR0; } return (total); case XPATH_OP_PREDICATE: case XPATH_OP_FILTER:{ xmlXPathObjectPtr res; xmlXPathObjectPtr obj, tmp; xmlNodeSetPtr newset = NULL; xmlNodeSetPtr oldset; xmlNodePtr oldnode; xmlDocPtr oldDoc; int i; /* * Optimization for ()[1] selection i.e. the first elem */ if ((op->ch1 != -1) && (op->ch2 != -1) && #ifdef XP_OPTIMIZED_FILTER_FIRST /* * FILTER TODO: Can we assume that the inner processing * will result in an ordered list if we have an * XPATH_OP_FILTER? * What about an additional field or flag on * xmlXPathObject like @sorted ? This way we wouln'd need * to assume anything, so it would be more robust and * easier to optimize. */ ((comp->steps[op->ch1].op == XPATH_OP_SORT) || /* 18 */ (comp->steps[op->ch1].op == XPATH_OP_FILTER)) && /* 17 */ #else (comp->steps[op->ch1].op == XPATH_OP_SORT) && #endif (comp->steps[op->ch2].op == XPATH_OP_VALUE)) { /* 12 */ xmlXPathObjectPtr val; val = comp->steps[op->ch2].value4; if ((val != NULL) && (val->type == XPATH_NUMBER) && (val->floatval == 1.0)) { xmlNodePtr first = NULL; total += xmlXPathCompOpEvalFirst(ctxt, &comp->steps[op->ch1], &first); CHECK_ERROR0; /* * The nodeset should be in document order, * Keep only the first value */ if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) ctxt->value->nodesetval->nodeNr = 1; return (total); } } /* * Optimization for ()[last()] selection i.e. the last elem */ if ((op->ch1 != -1) && (op->ch2 != -1) && (comp->steps[op->ch1].op == XPATH_OP_SORT) && (comp->steps[op->ch2].op == XPATH_OP_SORT)) { int f = comp->steps[op->ch2].ch1; if ((f != -1) && (comp->steps[f].op == XPATH_OP_FUNCTION) && (comp->steps[f].value5 == NULL) && (comp->steps[f].value == 0) && (comp->steps[f].value4 != NULL) && (xmlStrEqual (comp->steps[f].value4, BAD_CAST "last"))) { xmlNodePtr last = NULL; total += xmlXPathCompOpEvalLast(ctxt, &comp->steps[op->ch1], &last); CHECK_ERROR0; /* * The nodeset should be in document order, * Keep only the last value */ if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeTab != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) { ctxt->value->nodesetval->nodeTab[0] = ctxt->value->nodesetval->nodeTab[ctxt-> value-> nodesetval-> nodeNr - 1]; ctxt->value->nodesetval->nodeNr = 1; } return (total); } } /* * Process inner predicates first. * Example "index[parent::book][1]": * ... * PREDICATE <-- we are here "[1]" * PREDICATE <-- process "[parent::book]" first * SORT * COLLECT 'parent' 'name' 'node' book * NODE * ELEM Object is a number : 1 */ if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 == -1) return (total); if (ctxt->value == NULL) return (total); oldnode = ctxt->context->node; #ifdef LIBXML_XPTR_ENABLED /* * Hum are we filtering the result of an XPointer expression */ if (ctxt->value->type == XPATH_LOCATIONSET) { xmlLocationSetPtr newlocset = NULL; xmlLocationSetPtr oldlocset; /* * Extract the old locset, and then evaluate the result of the * expression for all the element in the locset. use it to grow * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); obj = valuePop(ctxt); oldlocset = obj->user; ctxt->context->node = NULL; if ((oldlocset == NULL) || (oldlocset->locNr == 0)) { ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); res = valuePop(ctxt); if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } valuePush(ctxt, obj); CHECK_ERROR0; return (total); } newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { /* * Run the evaluation with a node list made of a * single item in the nodelocset. */ ctxt->context->node = oldlocset->locTab[i]->user; ctxt->context->contextSize = oldlocset->locNr; ctxt->context->proximityPosition = i + 1; tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } /* * The result of the evaluation need to be tested to * decided whether the filter succeeded or not */ res = valuePop(ctxt); if (xmlXPathEvaluatePredicateResult(ctxt, res)) { xmlXPtrLocationSetAdd(newlocset, xmlXPathObjectCopy (oldlocset->locTab[i])); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } /* * The result is used as the new evaluation locset. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); ctxt->context->node = oldnode; return (total); } #endif /* LIBXML_XPTR_ENABLED */ /* * Extract the old set, and then evaluate the result of the * expression for all the element in the set. use it to grow * up a new set. */ CHECK_TYPE0(XPATH_NODESET); obj = valuePop(ctxt); oldset = obj->nodesetval; oldnode = ctxt->context->node; oldDoc = ctxt->context->doc; ctxt->context->node = NULL; if ((oldset == NULL) || (oldset->nodeNr == 0)) { ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; /* if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; res = valuePop(ctxt); if (res != NULL) xmlXPathFreeObject(res); */ valuePush(ctxt, obj); ctxt->context->node = oldnode; CHECK_ERROR0; } else { tmp = NULL; /* * Initialize the new set. * Also set the xpath document in case things like * key() evaluation are attempted on the predicate */ newset = xmlXPathNodeSetCreate(NULL); /* * SPEC XPath 1.0: * "For each node in the node-set to be filtered, the * PredicateExpr is evaluated with that node as the * context node, with the number of nodes in the * node-set as the context size, and with the proximity * position of the node in the node-set with respect to * the axis as the context position;" * @oldset is the node-set" to be filtered. * * SPEC XPath 1.0: * "only predicates change the context position and * context size (see [2.4 Predicates])." * Example: * node-set context pos * nA 1 * nB 2 * nC 3 * After applying predicate [position() > 1] : * node-set context pos * nB 1 * nC 2 * * removed the first node in the node-set, then * the context position of the */ for (i = 0; i < oldset->nodeNr; i++) { /* * Run the evaluation with a node list made of * a single item in the nodeset. */ ctxt->context->node = oldset->nodeTab[i]; if ((oldset->nodeTab[i]->type != XML_NAMESPACE_DECL) && (oldset->nodeTab[i]->doc != NULL)) ctxt->context->doc = oldset->nodeTab[i]->doc; if (tmp == NULL) { tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); } else { xmlXPathNodeSetAddUnique(tmp->nodesetval, ctxt->context->node); } valuePush(ctxt, tmp); ctxt->context->contextSize = oldset->nodeNr; ctxt->context->proximityPosition = i + 1; /* * Evaluate the predicate against the context node. * Can/should we optimize position() predicates * here (e.g. "[1]")? */ if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeNodeSet(newset); xmlXPathFreeObject(obj); return(0); } /* * The result of the evaluation needs to be tested to * decide whether the filter succeeded or not */ /* * OPTIMIZE TODO: Can we use * xmlXPathNodeSetAdd*Unique()* instead? */ res = valuePop(ctxt); if (xmlXPathEvaluatePredicateResult(ctxt, res)) { xmlXPathNodeSetAdd(newset, oldset->nodeTab[i]); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { valuePop(ctxt); xmlXPathNodeSetClear(tmp->nodesetval, 1); /* * Don't free the temporary nodeset * in order to avoid massive recreation inside this * loop. */ } else tmp = NULL; ctxt->context->node = NULL; } if (tmp != NULL) xmlXPathReleaseObject(ctxt->context, tmp); /* * The result is used as the new evaluation set. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; /* may want to move this past the '}' later */ ctxt->context->doc = oldDoc; valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, newset)); } ctxt->context->node = oldnode; return (total); } case XPATH_OP_SORT: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) { xmlXPathNodeSetSort(ctxt->value->nodesetval); } return (total); #ifdef LIBXML_XPTR_ENABLED case XPATH_OP_RANGETO:{ xmlXPathObjectPtr range; xmlXPathObjectPtr res, obj; xmlXPathObjectPtr tmp; xmlLocationSetPtr newlocset = NULL; xmlLocationSetPtr oldlocset; xmlNodeSetPtr oldset; int i, j; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (op->ch2 == -1) return (total); if (ctxt->value->type == XPATH_LOCATIONSET) { /* * Extract the old locset, and then evaluate the result of the * expression for all the element in the locset. use it to grow * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); obj = valuePop(ctxt); oldlocset = obj->user; if ((oldlocset == NULL) || (oldlocset->locNr == 0)) { ctxt->context->node = NULL; ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; total += xmlXPathCompOpEval(ctxt,&comp->steps[op->ch2]); res = valuePop(ctxt); if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } valuePush(ctxt, obj); CHECK_ERROR0; return (total); } newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { /* * Run the evaluation with a node list made of a * single item in the nodelocset. */ ctxt->context->node = oldlocset->locTab[i]->user; ctxt->context->contextSize = oldlocset->locNr; ctxt->context->proximityPosition = i + 1; tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } res = valuePop(ctxt); if (res->type == XPATH_LOCATIONSET) { xmlLocationSetPtr rloc = (xmlLocationSetPtr)res->user; for (j=0; j<rloc->locNr; j++) { range = xmlXPtrNewRange( oldlocset->locTab[i]->user, oldlocset->locTab[i]->index, rloc->locTab[j]->user2, rloc->locTab[j]->index2); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset, range); } } } else { range = xmlXPtrNewRangeNodeObject( (xmlNodePtr)oldlocset->locTab[i]->user, res); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset,range); } } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } } else { /* Not a location set */ CHECK_TYPE0(XPATH_NODESET); obj = valuePop(ctxt); oldset = obj->nodesetval; ctxt->context->node = NULL; newlocset = xmlXPtrLocationSetCreate(NULL); if (oldset != NULL) { for (i = 0; i < oldset->nodeNr; i++) { /* * Run the evaluation with a node list made of a single item * in the nodeset. */ ctxt->context->node = oldset->nodeTab[i]; /* * OPTIMIZE TODO: Avoid recreation for every iteration. */ tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } res = valuePop(ctxt); range = xmlXPtrNewRangeNodeObject(oldset->nodeTab[i], res); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset, range); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } } } /* * The result is used as the new evaluation set. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); return (total); } #endif /* LIBXML_XPTR_ENABLED */ }
CWE-399
183,776
4,820
152834258874192353926323433575025865787
null
null
null
Chrome
454434f6100cb6a529652a25b5fc181caa7c7f32
1
bool ExtensionService::IsDownloadFromGallery(const GURL& download_url, const GURL& referrer_url) { if (IsDownloadFromMiniGallery(download_url) && StartsWithASCII(referrer_url.spec(), extension_urls::kMiniGalleryBrowsePrefix, false)) { return true; } const Extension* download_extension = GetExtensionByWebExtent(download_url); const Extension* referrer_extension = GetExtensionByWebExtent(referrer_url); const Extension* webstore_app = GetWebStoreApp(); bool referrer_valid = (referrer_extension == webstore_app); bool download_valid = (download_extension == webstore_app); GURL store_url = GURL(CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kAppsGalleryURL)); if (!store_url.is_empty()) { std::string store_tld = net::RegistryControlledDomainService::GetDomainAndRegistry(store_url); if (!referrer_valid) { std::string referrer_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( referrer_url); referrer_valid = referrer_url.is_empty() || (referrer_tld == store_tld); } if (!download_valid) { std::string download_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( download_url); download_valid = (download_tld == store_tld); } } return (referrer_valid && download_valid); }
CWE-264
183,777
4,821
110603712723080352315486319066350894667
null
null
null
Chrome
6c390601f9ee3436bb32f84772977570265982ea
1
bool ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode& ec, bool shouldLazyAttach) { ASSERT(refCount() || parentOrHostNode()); RefPtr<Node> protect(this); ec = 0; if (oldChild == newChild) // nothing to do return true; checkReplaceChild(newChild.get(), oldChild, ec); if (ec) return false; if (!oldChild || oldChild->parentNode() != this) { ec = NOT_FOUND_ERR; return false; } #if ENABLE(MUTATION_OBSERVERS) ChildListMutationScope mutation(this); #endif RefPtr<Node> next = oldChild->nextSibling(); RefPtr<Node> removedChild = oldChild; removeChild(oldChild, ec); if (ec) return false; if (next && (next->previousSibling() == newChild || next == newChild)) // nothing to do return true; checkReplaceChild(newChild.get(), oldChild, ec); if (ec) return false; NodeVector targets; collectChildrenAndRemoveFromOldParent(newChild.get(), targets, ec); if (ec) return false; InspectorInstrumentation::willInsertDOMNode(document(), this); for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) { Node* child = it->get(); if (next && next->parentNode() != this) break; if (child->parentNode()) break; treeScope()->adoptIfNeeded(child); forbidEventDispatch(); if (next) insertBeforeCommon(next.get(), child); else appendChildToContainer(child, this); allowEventDispatch(); updateTreeAfterInsertion(this, child, shouldLazyAttach); } dispatchSubtreeModifiedEvent(); return true; }
CWE-399
183,778
4,822
226083901999659326184309321163029658658
null
null
null
Chrome
5b65968b6c64fa02e74ca6b965bf5998b911e826
1
bool SubsetterImpl::ResolveCompositeGlyphs(const unsigned int* glyph_ids, size_t glyph_count, IntegerSet* glyph_id_processed) { if (glyph_ids == NULL || glyph_count == 0 || glyph_id_processed == NULL) { return false; } GlyphTablePtr glyph_table = down_cast<GlyphTable*>(font_->GetTable(Tag::glyf)); LocaTablePtr loca_table = down_cast<LocaTable*>(font_->GetTable(Tag::loca)); if (glyph_table == NULL || loca_table == NULL) { return false; } IntegerSet glyph_id_remaining; glyph_id_remaining.insert(0); // Always include glyph id 0. for (size_t i = 0; i < glyph_count; ++i) { glyph_id_remaining.insert(glyph_ids[i]); } while (!glyph_id_remaining.empty()) { IntegerSet comp_glyph_id; for (IntegerSet::iterator i = glyph_id_remaining.begin(), e = glyph_id_remaining.end(); i != e; ++i) { if (*i < 0 || *i >= loca_table->NumGlyphs()) { continue; } int32_t length = loca_table->GlyphLength(*i); if (length == 0) { continue; } int32_t offset = loca_table->GlyphOffset(*i); GlyphPtr glyph; glyph.Attach(glyph_table->GetGlyph(offset, length)); if (glyph == NULL) { continue; } if (glyph->GlyphType() == GlyphType::kComposite) { Ptr<GlyphTable::CompositeGlyph> comp_glyph = down_cast<GlyphTable::CompositeGlyph*>(glyph.p_); for (int32_t j = 0; j < comp_glyph->NumGlyphs(); ++j) { int32_t glyph_id = comp_glyph->GlyphIndex(j); if (glyph_id_processed->find(glyph_id) == glyph_id_processed->end() && glyph_id_remaining.find(glyph_id) == glyph_id_remaining.end()) { comp_glyph_id.insert(comp_glyph->GlyphIndex(j)); } } } glyph_id_processed->insert(*i); } glyph_id_remaining.clear(); glyph_id_remaining = comp_glyph_id; } }
CWE-119
183,786
4,829
88383665204444789027565399248350148456
null
null
null
Chrome
a64c3cf0ab6da24a9a010a45ebe4794422d40c71
1
GURL URLFixerUpper::FixupRelativeFile(const FilePath& base_dir, const FilePath& text) { FilePath old_cur_directory; if (!base_dir.empty()) { file_util::GetCurrentDirectory(&old_cur_directory); file_util::SetCurrentDirectory(base_dir); } FilePath::StringType trimmed; PrepareStringForFileOps(text, &trimmed); bool is_file = true; FilePath full_path; if (!ValidPathForFile(trimmed, &full_path)) { #if defined(OS_WIN) std::wstring unescaped = UTF8ToWide(UnescapeURLComponent( WideToUTF8(trimmed), UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS)); #elif defined(OS_POSIX) std::string unescaped = UnescapeURLComponent( trimmed, UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS); #endif if (!ValidPathForFile(unescaped, &full_path)) is_file = false; } if (!base_dir.empty()) file_util::SetCurrentDirectory(old_cur_directory); if (is_file) { GURL file_url = net::FilePathToFileURL(full_path); if (file_url.is_valid()) return GURL(UTF16ToUTF8(net::FormatUrl(file_url, std::string(), net::kFormatUrlOmitUsernamePassword, UnescapeRule::NORMAL, NULL, NULL, NULL))); } #if defined(OS_WIN) std::string text_utf8 = WideToUTF8(text.value()); #elif defined(OS_POSIX) std::string text_utf8 = text.value(); #endif return FixupURL(text_utf8, std::string()); }
CWE-20
183,821
4,860
102425623880400521812311579065078851143
null
null
null
Chrome
c9911bc93097a5df5518f5b88e1d5ed5ef275a4d
1
xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op, xmlNodeSetPtr set, int contextSize, int minPos, int maxPos, int hasNsNodes) { if (op->ch1 != -1) { xmlXPathCompExprPtr comp = ctxt->comp; if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) { /* * TODO: raise an internal error. */ } contextSize = xmlXPathCompOpEvalPredicate(ctxt, &comp->steps[op->ch1], set, contextSize, hasNsNodes); CHECK_ERROR0; if (contextSize <= 0) return(0); } /* * Check if the node set contains a sufficient number of nodes for * the requested range. */ if (contextSize < minPos) { xmlXPathNodeSetClear(set, hasNsNodes); return(0); } if (op->ch2 == -1) { /* * TODO: Can this ever happen? */ return (contextSize); } else { xmlDocPtr oldContextDoc; int i, pos = 0, newContextSize = 0, contextPos = 0, res; xmlXPathStepOpPtr exprOp; xmlXPathObjectPtr contextObj = NULL, exprRes = NULL; xmlNodePtr oldContextNode, contextNode = NULL; xmlXPathContextPtr xpctxt = ctxt->context; #ifdef LIBXML_XPTR_ENABLED /* * URGENT TODO: Check the following: * We don't expect location sets if evaluating prediates, right? * Only filters should expect location sets, right? */ #endif /* LIBXML_XPTR_ENABLED */ /* * Save old context. */ oldContextNode = xpctxt->node; oldContextDoc = xpctxt->doc; /* * Get the expression of this predicate. */ exprOp = &ctxt->comp->steps[op->ch2]; for (i = 0; i < set->nodeNr; i++) { if (set->nodeTab[i] == NULL) continue; contextNode = set->nodeTab[i]; xpctxt->node = contextNode; xpctxt->contextSize = contextSize; xpctxt->proximityPosition = ++contextPos; /* * Initialize the new set. * Also set the xpath document in case things like * key() evaluation are attempted on the predicate */ if ((contextNode->type != XML_NAMESPACE_DECL) && (contextNode->doc != NULL)) xpctxt->doc = contextNode->doc; /* * Evaluate the predicate expression with 1 context node * at a time; this node is packaged into a node set; this * node set is handed over to the evaluation mechanism. */ if (contextObj == NULL) contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode); else xmlXPathNodeSetAddUnique(contextObj->nodesetval, contextNode); valuePush(ctxt, contextObj); res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1); if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) { xmlXPathObjectPtr tmp; /* pop the result if any */ tmp = valuePop(ctxt); if (tmp != contextObj) /* * Free up the result * then pop off contextObj, which will be freed later */ xmlXPathReleaseObject(xpctxt, tmp); valuePop(ctxt); goto evaluation_error; } if (res) pos++; if (res && (pos >= minPos) && (pos <= maxPos)) { /* * Fits in the requested range. */ newContextSize++; if (minPos == maxPos) { /* * Only 1 node was requested. */ if (contextNode->type == XML_NAMESPACE_DECL) { /* * As always: take care of those nasty * namespace nodes. */ set->nodeTab[i] = NULL; } xmlXPathNodeSetClear(set, hasNsNodes); set->nodeNr = 1; set->nodeTab[0] = contextNode; goto evaluation_exit; } if (pos == maxPos) { /* * We are done. */ xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes); goto evaluation_exit; } } else { /* * Remove the entry from the initial node set. */ set->nodeTab[i] = NULL; if (contextNode->type == XML_NAMESPACE_DECL) xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode); } if (exprRes != NULL) { xmlXPathReleaseObject(ctxt->context, exprRes); exprRes = NULL; } if (ctxt->value == contextObj) { /* * Don't free the temporary XPath object holding the * context node, in order to avoid massive recreation * inside this loop. */ valuePop(ctxt); xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes); } else { /* * The object was lost in the evaluation machinery. * Can this happen? Maybe in case of internal-errors. */ contextObj = NULL; } } goto evaluation_exit; evaluation_error: xmlXPathNodeSetClear(set, hasNsNodes); newContextSize = 0; evaluation_exit: if (contextObj != NULL) { if (ctxt->value == contextObj) valuePop(ctxt); xmlXPathReleaseObject(xpctxt, contextObj); } if (exprRes != NULL) xmlXPathReleaseObject(ctxt->context, exprRes); /* * Reset/invalidate the context. */ xpctxt->node = oldContextNode; xpctxt->doc = oldContextDoc; xpctxt->contextSize = -1; xpctxt->proximityPosition = -1; return(newContextSize); } return(contextSize); }
CWE-399
183,822
4,861
195728010268250493191626746733027958160
null
null
null
Chrome
01e4ee2fda0a5e57a8d0c8cb829022eb84fdff12
1
static PassRefPtr<CSSValue> getPositionOffsetValue(RenderStyle* style, CSSPropertyID propertyID, RenderView* renderView) { if (!style) return 0; Length l; switch (propertyID) { case CSSPropertyLeft: l = style->left(); break; case CSSPropertyRight: l = style->right(); break; case CSSPropertyTop: l = style->top(); break; case CSSPropertyBottom: l = style->bottom(); break; default: return 0; } if (style->position() == AbsolutePosition || style->position() == FixedPosition) { if (l.type() == WebCore::Fixed) return zoomAdjustedPixelValue(l.value(), style); else if (l.isViewportPercentage()) return zoomAdjustedPixelValue(valueForLength(l, 0, renderView), style); return cssValuePool().createValue(l); } if (style->position() == RelativePosition) return cssValuePool().createValue(l); return cssValuePool().createIdentifierValue(CSSValueAuto); }
CWE-119
183,823
4,862
261655135801417652570416538845654492312
null
null
null
Chrome
a4b20ed4917f1f6fc83b6375a48e2c3895d43a8a
1
void BindSkiaToInProcessGL() { static bool host_StubGL_installed = false; if (!host_StubGL_installed) { GrGLBinding binding; switch (gfx::GetGLImplementation()) { case gfx::kGLImplementationNone: NOTREACHED(); return; case gfx::kGLImplementationDesktopGL: binding = kDesktop_GrGLBinding; break; case gfx::kGLImplementationOSMesaGL: binding = kDesktop_GrGLBinding; break; case gfx::kGLImplementationEGLGLES2: binding = kES2_GrGLBinding; break; case gfx::kGLImplementationMockGL: NOTREACHED(); return; } static GrGLInterface host_gl_interface = { binding, kProbe_GrGLCapability, // NPOTRenderTargetSupport kProbe_GrGLCapability, // MinRenderTargetHeight kProbe_GrGLCapability, // MinRenderTargetWidth StubGLActiveTexture, StubGLAttachShader, StubGLBindAttribLocation, StubGLBindBuffer, StubGLBindTexture, StubGLBlendColor, StubGLBlendFunc, StubGLBufferData, StubGLBufferSubData, StubGLClear, StubGLClearColor, StubGLClearStencil, NULL, // glClientActiveTexture NULL, // glColor4ub StubGLColorMask, NULL, // glColorPointer StubGLCompileShader, StubGLCompressedTexImage2D, StubGLCreateProgram, StubGLCreateShader, StubGLCullFace, StubGLDeleteBuffers, StubGLDeleteProgram, StubGLDeleteShader, StubGLDeleteTextures, StubGLDepthMask, StubGLDisable, NULL, // glDisableClientState StubGLDisableVertexAttribArray, StubGLDrawArrays, StubGLDrawElements, StubGLEnable, NULL, // glEnableClientState StubGLEnableVertexAttribArray, StubGLFrontFace, StubGLGenBuffers, StubGLGenTextures, StubGLGetBufferParameteriv, StubGLGetError, StubGLGetIntegerv, StubGLGetProgramInfoLog, StubGLGetProgramiv, StubGLGetShaderInfoLog, StubGLGetShaderiv, StubGLGetString, StubGLGetUniformLocation, StubGLLineWidth, StubGLLinkProgram, NULL, // glLoadMatrixf NULL, // glMatrixMode StubGLPixelStorei, NULL, // glPointSize StubGLReadPixels, StubGLScissor, NULL, // glShadeModel StubGLShaderSource, StubGLStencilFunc, StubGLStencilFuncSeparate, StubGLStencilMask, StubGLStencilMaskSeparate, StubGLStencilOp, StubGLStencilOpSeparate, NULL, // glTexCoordPointer NULL, // glTexEnvi StubGLTexImage2D, StubGLTexParameteri, StubGLTexSubImage2D, StubGLUniform1f, StubGLUniform1i, StubGLUniform1fv, StubGLUniform1iv, StubGLUniform2f, StubGLUniform2i, StubGLUniform2fv, StubGLUniform2iv, StubGLUniform3f, StubGLUniform3i, StubGLUniform3fv, StubGLUniform3iv, StubGLUniform4f, StubGLUniform4i, StubGLUniform4fv, StubGLUniform4iv, StubGLUniformMatrix2fv, StubGLUniformMatrix3fv, StubGLUniformMatrix4fv, StubGLUseProgram, StubGLVertexAttrib4fv, StubGLVertexAttribPointer, NULL, // glVertexPointer StubGLViewport, StubGLBindFramebuffer, StubGLBindRenderbuffer, StubGLCheckFramebufferStatus, StubGLDeleteFramebuffers, StubGLDeleteRenderbuffers, StubGLFramebufferRenderbuffer, StubGLFramebufferTexture2D, StubGLGenFramebuffers, StubGLGenRenderbuffers, StubGLRenderBufferStorage, StubGLRenderbufferStorageMultisample, StubGLBlitFramebuffer, NULL, // glResolveMultisampleFramebuffer StubGLMapBuffer, StubGLUnmapBuffer, NULL, // glBindFragDataLocationIndexed GrGLInterface::kStaticInitEndGuard, }; GrGLSetGLInterface(&host_gl_interface); host_StubGL_installed = true; } }
CWE-189
183,828
4,867
151739885399519347923344836427117640129
null
null
null
Chrome
20d1c99d9b53a0b2b419aae0075494a9d0b86daf
1
bool NavigationController::RendererDidNavigate( const ViewHostMsg_FrameNavigate_Params& params, int extra_invalidate_flags, LoadCommittedDetails* details) { if (GetLastCommittedEntry()) { details->previous_url = GetLastCommittedEntry()->url(); details->previous_entry_index = last_committed_entry_index(); } else { details->previous_url = GURL(); details->previous_entry_index = -1; } if (pending_entry_index_ >= 0 && !pending_entry_->site_instance()) { DCHECK(pending_entry_->restore_type() != NavigationEntry::RESTORE_NONE); pending_entry_->set_site_instance(tab_contents_->GetSiteInstance()); pending_entry_->set_restore_type(NavigationEntry::RESTORE_NONE); } details->is_in_page = IsURLInPageNavigation(params.url); details->type = ClassifyNavigation(params); switch (details->type) { case NavigationType::NEW_PAGE: RendererDidNavigateToNewPage(params, &(details->did_replace_entry)); break; case NavigationType::EXISTING_PAGE: RendererDidNavigateToExistingPage(params); break; case NavigationType::SAME_PAGE: RendererDidNavigateToSamePage(params); break; case NavigationType::IN_PAGE: RendererDidNavigateInPage(params, &(details->did_replace_entry)); break; case NavigationType::NEW_SUBFRAME: RendererDidNavigateNewSubframe(params); break; case NavigationType::AUTO_SUBFRAME: if (!RendererDidNavigateAutoSubframe(params)) return false; break; case NavigationType::NAV_IGNORE: return false; default: NOTREACHED(); } DCHECK(!params.content_state.empty()); NavigationEntry* active_entry = GetActiveEntry(); active_entry->set_content_state(params.content_state); DCHECK(active_entry->site_instance() == tab_contents_->GetSiteInstance()); details->is_auto = (PageTransition::IsRedirect(params.transition) && !pending_entry()) || params.gesture == NavigationGestureAuto; details->entry = active_entry; details->is_main_frame = PageTransition::IsMainFrame(params.transition); details->serialized_security_info = params.security_info; details->http_status_code = params.http_status_code; NotifyNavigationEntryCommitted(details, extra_invalidate_flags); return true; }
CWE-264
183,863
4,898
310335884979475080961264708772351648450
null
null
null
Chrome
697cd7e2ce2535696f1b9e5cfb474cc36a734747
1
bool Extension::InitFromValue(const DictionaryValue& source, int flags, std::string* error) { URLPattern::ParseOption parse_strictness = (flags & STRICT_ERROR_CHECKS ? URLPattern::PARSE_STRICT : URLPattern::PARSE_LENIENT); if (source.HasKey(keys::kPublicKey)) { std::string public_key_bytes; if (!source.GetString(keys::kPublicKey, &public_key_) || !ParsePEMKeyBytes(public_key_, &public_key_bytes) || !GenerateId(public_key_bytes, &id_)) { *error = errors::kInvalidKey; return false; } } else if (flags & REQUIRE_KEY) { *error = errors::kInvalidKey; return false; } else { id_ = Extension::GenerateIdForPath(path()); if (id_.empty()) { NOTREACHED() << "Could not create ID from path."; return false; } } manifest_value_.reset(source.DeepCopy()); extension_url_ = Extension::GetBaseURLFromExtensionId(id()); std::string version_str; if (!source.GetString(keys::kVersion, &version_str)) { *error = errors::kInvalidVersion; return false; } version_.reset(Version::GetVersionFromString(version_str)); if (!version_.get() || version_->components().size() > 4) { *error = errors::kInvalidVersion; return false; } string16 localized_name; if (!source.GetString(keys::kName, &localized_name)) { *error = errors::kInvalidName; return false; } base::i18n::AdjustStringForLocaleDirection(&localized_name); name_ = UTF16ToUTF8(localized_name); if (source.HasKey(keys::kDescription)) { if (!source.GetString(keys::kDescription, &description_)) { *error = errors::kInvalidDescription; return false; } } if (source.HasKey(keys::kHomepageURL)) { std::string tmp; if (!source.GetString(keys::kHomepageURL, &tmp)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidHomepageURL, ""); return false; } homepage_url_ = GURL(tmp); if (!homepage_url_.is_valid()) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidHomepageURL, tmp); return false; } } if (source.HasKey(keys::kUpdateURL)) { std::string tmp; if (!source.GetString(keys::kUpdateURL, &tmp)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidUpdateURL, ""); return false; } update_url_ = GURL(tmp); if (!update_url_.is_valid() || update_url_.has_ref()) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidUpdateURL, tmp); return false; } } if (source.HasKey(keys::kMinimumChromeVersion)) { std::string minimum_version_string; if (!source.GetString(keys::kMinimumChromeVersion, &minimum_version_string)) { *error = errors::kInvalidMinimumChromeVersion; return false; } scoped_ptr<Version> minimum_version( Version::GetVersionFromString(minimum_version_string)); if (!minimum_version.get()) { *error = errors::kInvalidMinimumChromeVersion; return false; } chrome::VersionInfo current_version_info; if (!current_version_info.is_valid()) { NOTREACHED(); return false; } scoped_ptr<Version> current_version( Version::GetVersionFromString(current_version_info.Version())); if (!current_version.get()) { DCHECK(false); return false; } if (current_version->CompareTo(*minimum_version) < 0) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kChromeVersionTooLow, l10n_util::GetStringUTF8(IDS_PRODUCT_NAME), minimum_version_string); return false; } } source.GetBoolean(keys::kConvertedFromUserScript, &converted_from_user_script_); if (source.HasKey(keys::kIcons)) { DictionaryValue* icons_value = NULL; if (!source.GetDictionary(keys::kIcons, &icons_value)) { *error = errors::kInvalidIcons; return false; } for (size_t i = 0; i < arraysize(kIconSizes); ++i) { std::string key = base::IntToString(kIconSizes[i]); if (icons_value->HasKey(key)) { std::string icon_path; if (!icons_value->GetString(key, &icon_path)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidIconPath, key); return false; } if (!icon_path.empty() && icon_path[0] == '/') icon_path = icon_path.substr(1); if (icon_path.empty()) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidIconPath, key); return false; } icons_.Add(kIconSizes[i], icon_path); } } } is_theme_ = false; if (source.HasKey(keys::kTheme)) { if (ContainsNonThemeKeys(source)) { *error = errors::kThemesCannotContainExtensions; return false; } DictionaryValue* theme_value = NULL; if (!source.GetDictionary(keys::kTheme, &theme_value)) { *error = errors::kInvalidTheme; return false; } is_theme_ = true; DictionaryValue* images_value = NULL; if (theme_value->GetDictionary(keys::kThemeImages, &images_value)) { for (DictionaryValue::key_iterator iter = images_value->begin_keys(); iter != images_value->end_keys(); ++iter) { std::string val; if (!images_value->GetString(*iter, &val)) { *error = errors::kInvalidThemeImages; return false; } } theme_images_.reset(images_value->DeepCopy()); } DictionaryValue* colors_value = NULL; if (theme_value->GetDictionary(keys::kThemeColors, &colors_value)) { for (DictionaryValue::key_iterator iter = colors_value->begin_keys(); iter != colors_value->end_keys(); ++iter) { ListValue* color_list = NULL; double alpha = 0.0; int color = 0; if (!colors_value->GetListWithoutPathExpansion(*iter, &color_list) || ((color_list->GetSize() != 3) && ((color_list->GetSize() != 4) || !color_list->GetDouble(3, &alpha))) || !color_list->GetInteger(0, &color) || !color_list->GetInteger(1, &color) || !color_list->GetInteger(2, &color)) { *error = errors::kInvalidThemeColors; return false; } } theme_colors_.reset(colors_value->DeepCopy()); } DictionaryValue* tints_value = NULL; if (theme_value->GetDictionary(keys::kThemeTints, &tints_value)) { for (DictionaryValue::key_iterator iter = tints_value->begin_keys(); iter != tints_value->end_keys(); ++iter) { ListValue* tint_list = NULL; double v = 0.0; if (!tints_value->GetListWithoutPathExpansion(*iter, &tint_list) || tint_list->GetSize() != 3 || !tint_list->GetDouble(0, &v) || !tint_list->GetDouble(1, &v) || !tint_list->GetDouble(2, &v)) { *error = errors::kInvalidThemeTints; return false; } } theme_tints_.reset(tints_value->DeepCopy()); } DictionaryValue* display_properties_value = NULL; if (theme_value->GetDictionary(keys::kThemeDisplayProperties, &display_properties_value)) { theme_display_properties_.reset( display_properties_value->DeepCopy()); } return true; } if (source.HasKey(keys::kPlugins)) { ListValue* list_value = NULL; if (!source.GetList(keys::kPlugins, &list_value)) { *error = errors::kInvalidPlugins; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* plugin_value = NULL; std::string path_str; bool is_public = false; if (!list_value->GetDictionary(i, &plugin_value)) { *error = errors::kInvalidPlugins; return false; } if (!plugin_value->GetString(keys::kPluginsPath, &path_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPluginsPath, base::IntToString(i)); return false; } if (plugin_value->HasKey(keys::kPluginsPublic)) { if (!plugin_value->GetBoolean(keys::kPluginsPublic, &is_public)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPluginsPublic, base::IntToString(i)); return false; } } #if !defined(OS_CHROMEOS) plugins_.push_back(PluginInfo()); plugins_.back().path = path().AppendASCII(path_str); plugins_.back().is_public = is_public; #endif } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kNaClModules)) { ListValue* list_value = NULL; if (!source.GetList(keys::kNaClModules, &list_value)) { *error = errors::kInvalidNaClModules; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* module_value = NULL; std::string path_str; std::string mime_type; if (!list_value->GetDictionary(i, &module_value)) { *error = errors::kInvalidNaClModules; return false; } if (!module_value->GetString(keys::kNaClModulesPath, &path_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidNaClModulesPath, base::IntToString(i)); return false; } if (!module_value->GetString(keys::kNaClModulesMIMEType, &mime_type)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidNaClModulesMIMEType, base::IntToString(i)); return false; } nacl_modules_.push_back(NaClModuleInfo()); nacl_modules_.back().url = GetResourceURL(path_str); nacl_modules_.back().mime_type = mime_type; } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kToolstrips)) { ListValue* list_value = NULL; if (!source.GetList(keys::kToolstrips, &list_value)) { *error = errors::kInvalidToolstrips; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { GURL toolstrip; DictionaryValue* toolstrip_value = NULL; std::string toolstrip_path; if (list_value->GetString(i, &toolstrip_path)) { toolstrip = GetResourceURL(toolstrip_path); } else if (list_value->GetDictionary(i, &toolstrip_value)) { if (!toolstrip_value->GetString(keys::kToolstripPath, &toolstrip_path)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidToolstrip, base::IntToString(i)); return false; } toolstrip = GetResourceURL(toolstrip_path); } else { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidToolstrip, base::IntToString(i)); return false; } toolstrips_.push_back(toolstrip); } } if (source.HasKey(keys::kContentScripts)) { ListValue* list_value; if (!source.GetList(keys::kContentScripts, &list_value)) { *error = errors::kInvalidContentScriptsList; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* content_script = NULL; if (!list_value->GetDictionary(i, &content_script)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidContentScript, base::IntToString(i)); return false; } UserScript script; if (!LoadUserScriptHelper(content_script, i, flags, error, &script)) return false; // Failed to parse script context definition. script.set_extension_id(id()); if (converted_from_user_script_) { script.set_emulate_greasemonkey(true); script.set_match_all_frames(true); // Greasemonkey matches all frames. } content_scripts_.push_back(script); } } DictionaryValue* page_action_value = NULL; if (source.HasKey(keys::kPageActions)) { ListValue* list_value = NULL; if (!source.GetList(keys::kPageActions, &list_value)) { *error = errors::kInvalidPageActionsList; return false; } size_t list_value_length = list_value->GetSize(); if (list_value_length == 0u) { } else if (list_value_length == 1u) { if (!list_value->GetDictionary(0, &page_action_value)) { *error = errors::kInvalidPageAction; return false; } } else { // list_value_length > 1u. *error = errors::kInvalidPageActionsListSize; return false; } } else if (source.HasKey(keys::kPageAction)) { if (!source.GetDictionary(keys::kPageAction, &page_action_value)) { *error = errors::kInvalidPageAction; return false; } } if (page_action_value) { page_action_.reset( LoadExtensionActionHelper(page_action_value, error)); if (!page_action_.get()) return false; // Failed to parse page action definition. } if (source.HasKey(keys::kBrowserAction)) { DictionaryValue* browser_action_value = NULL; if (!source.GetDictionary(keys::kBrowserAction, &browser_action_value)) { *error = errors::kInvalidBrowserAction; return false; } browser_action_.reset( LoadExtensionActionHelper(browser_action_value, error)); if (!browser_action_.get()) return false; // Failed to parse browser action definition. } if (source.HasKey(keys::kFileBrowserHandlers)) { ListValue* file_browser_handlers_value = NULL; if (!source.GetList(keys::kFileBrowserHandlers, &file_browser_handlers_value)) { *error = errors::kInvalidFileBrowserHandler; return false; } file_browser_handlers_.reset( LoadFileBrowserHandlers(file_browser_handlers_value, error)); if (!file_browser_handlers_.get()) return false; // Failed to parse file browser actions definition. } if (!LoadIsApp(manifest_value_.get(), error) || !LoadExtent(manifest_value_.get(), keys::kWebURLs, &extent_, errors::kInvalidWebURLs, errors::kInvalidWebURL, parse_strictness, error) || !EnsureNotHybridApp(manifest_value_.get(), error) || !LoadLaunchURL(manifest_value_.get(), error) || !LoadLaunchContainer(manifest_value_.get(), error) || !LoadAppIsolation(manifest_value_.get(), error)) { return false; } if (source.HasKey(keys::kOptionsPage)) { std::string options_str; if (!source.GetString(keys::kOptionsPage, &options_str)) { *error = errors::kInvalidOptionsPage; return false; } if (is_hosted_app()) { GURL options_url(options_str); if (!options_url.is_valid() || !(options_url.SchemeIs("http") || options_url.SchemeIs("https"))) { *error = errors::kInvalidOptionsPageInHostedApp; return false; } options_url_ = options_url; } else { GURL absolute(options_str); if (absolute.is_valid()) { *error = errors::kInvalidOptionsPageExpectUrlInPackage; return false; } options_url_ = GetResourceURL(options_str); if (!options_url_.is_valid()) { *error = errors::kInvalidOptionsPage; return false; } } } if (source.HasKey(keys::kPermissions)) { ListValue* permissions = NULL; if (!source.GetList(keys::kPermissions, &permissions)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermissions, ""); return false; } for (size_t i = 0; i < permissions->GetSize(); ++i) { std::string permission_str; if (!permissions->GetString(i, &permission_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermission, base::IntToString(i)); return false; } if (!IsComponentOnlyPermission(permission_str) #ifndef NDEBUG && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kExposePrivateExtensionApi) #endif ) { continue; } if (permission_str == kOldUnlimitedStoragePermission) permission_str = kUnlimitedStoragePermission; if (web_extent().is_empty() || location() == Extension::COMPONENT) { if (IsAPIPermission(permission_str)) { if (permission_str == Extension::kExperimentalPermission && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && location() != Extension::COMPONENT) { *error = errors::kExperimentalFlagRequired; return false; } api_permissions_.insert(permission_str); continue; } } else { if (IsHostedAppPermission(permission_str)) { api_permissions_.insert(permission_str); continue; } } URLPattern pattern = URLPattern(CanExecuteScriptEverywhere() ? URLPattern::SCHEME_ALL : kValidHostPermissionSchemes); URLPattern::ParseResult parse_result = pattern.Parse(permission_str, parse_strictness); if (parse_result == URLPattern::PARSE_SUCCESS) { if (!CanSpecifyHostPermission(pattern)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermissionScheme, base::IntToString(i)); return false; } pattern.SetPath("/*"); if (pattern.MatchesScheme(chrome::kFileScheme) && !CanExecuteScriptEverywhere()) { wants_file_access_ = true; if (!(flags & ALLOW_FILE_ACCESS)) pattern.set_valid_schemes( pattern.valid_schemes() & ~URLPattern::SCHEME_FILE); } host_permissions_.push_back(pattern); } } } if (source.HasKey(keys::kBackground)) { std::string background_str; if (!source.GetString(keys::kBackground, &background_str)) { *error = errors::kInvalidBackground; return false; } if (is_hosted_app()) { if (api_permissions_.find(kBackgroundPermission) == api_permissions_.end()) { *error = errors::kBackgroundPermissionNeeded; return false; } GURL bg_page(background_str); if (!bg_page.is_valid()) { *error = errors::kInvalidBackgroundInHostedApp; return false; } if (!(bg_page.SchemeIs("https") || (CommandLine::ForCurrentProcess()->HasSwitch( switches::kAllowHTTPBackgroundPage) && bg_page.SchemeIs("http")))) { *error = errors::kInvalidBackgroundInHostedApp; return false; } background_url_ = bg_page; } else { background_url_ = GetResourceURL(background_str); } } if (source.HasKey(keys::kDefaultLocale)) { if (!source.GetString(keys::kDefaultLocale, &default_locale_) || !l10n_util::IsValidLocaleSyntax(default_locale_)) { *error = errors::kInvalidDefaultLocale; return false; } } if (source.HasKey(keys::kChromeURLOverrides)) { DictionaryValue* overrides = NULL; if (!source.GetDictionary(keys::kChromeURLOverrides, &overrides)) { *error = errors::kInvalidChromeURLOverrides; return false; } for (DictionaryValue::key_iterator iter = overrides->begin_keys(); iter != overrides->end_keys(); ++iter) { std::string page = *iter; std::string val; if ((page != chrome::kChromeUINewTabHost && #if defined(TOUCH_UI) page != chrome::kChromeUIKeyboardHost && #endif #if defined(OS_CHROMEOS) page != chrome::kChromeUIActivationMessageHost && #endif page != chrome::kChromeUIBookmarksHost && page != chrome::kChromeUIHistoryHost) || !overrides->GetStringWithoutPathExpansion(*iter, &val)) { *error = errors::kInvalidChromeURLOverrides; return false; } chrome_url_overrides_[page] = GetResourceURL(val); } if (overrides->size() > 1) { *error = errors::kMultipleOverrides; return false; } } if (source.HasKey(keys::kOmnibox)) { if (!source.GetString(keys::kOmniboxKeyword, &omnibox_keyword_) || omnibox_keyword_.empty()) { *error = errors::kInvalidOmniboxKeyword; return false; } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kContentSecurityPolicy)) { std::string content_security_policy; if (!source.GetString(keys::kContentSecurityPolicy, &content_security_policy)) { *error = errors::kInvalidContentSecurityPolicy; return false; } const char kBadCSPCharacters[] = {'\r', '\n', '\0'}; if (content_security_policy.find_first_of(kBadCSPCharacters, 0, arraysize(kBadCSPCharacters)) != std::string::npos) { *error = errors::kInvalidContentSecurityPolicy; return false; } content_security_policy_ = content_security_policy; } if (source.HasKey(keys::kDevToolsPage)) { std::string devtools_str; if (!source.GetString(keys::kDevToolsPage, &devtools_str)) { *error = errors::kInvalidDevToolsPage; return false; } if (!HasApiPermission(Extension::kExperimentalPermission)) { *error = errors::kDevToolsExperimental; return false; } devtools_url_ = GetResourceURL(devtools_str); } if (source.HasKey(keys::kSidebar)) { DictionaryValue* sidebar_value = NULL; if (!source.GetDictionary(keys::kSidebar, &sidebar_value)) { *error = errors::kInvalidSidebar; return false; } if (!HasApiPermission(Extension::kExperimentalPermission)) { *error = errors::kSidebarExperimental; return false; } sidebar_defaults_.reset(LoadExtensionSidebarDefaults(sidebar_value, error)); if (!sidebar_defaults_.get()) return false; // Failed to parse sidebar definition. } if (source.HasKey(keys::kTts)) { DictionaryValue* tts_dict = NULL; if (!source.GetDictionary(keys::kTts, &tts_dict)) { *error = errors::kInvalidTts; return false; } if (tts_dict->HasKey(keys::kTtsVoices)) { ListValue* tts_voices = NULL; if (!tts_dict->GetList(keys::kTtsVoices, &tts_voices)) { *error = errors::kInvalidTtsVoices; return false; } for (size_t i = 0; i < tts_voices->GetSize(); i++) { DictionaryValue* one_tts_voice = NULL; if (!tts_voices->GetDictionary(i, &one_tts_voice)) { *error = errors::kInvalidTtsVoices; return false; } TtsVoice voice_data; if (one_tts_voice->HasKey(keys::kTtsVoicesVoiceName)) { if (!one_tts_voice->GetString( keys::kTtsVoicesVoiceName, &voice_data.voice_name)) { *error = errors::kInvalidTtsVoicesVoiceName; return false; } } if (one_tts_voice->HasKey(keys::kTtsVoicesLocale)) { if (!one_tts_voice->GetString( keys::kTtsVoicesLocale, &voice_data.locale) || !l10n_util::IsValidLocaleSyntax(voice_data.locale)) { *error = errors::kInvalidTtsVoicesLocale; return false; } } if (one_tts_voice->HasKey(keys::kTtsVoicesGender)) { if (!one_tts_voice->GetString( keys::kTtsVoicesGender, &voice_data.gender) || (voice_data.gender != keys::kTtsGenderMale && voice_data.gender != keys::kTtsGenderFemale)) { *error = errors::kInvalidTtsVoicesGender; return false; } } tts_voices_.push_back(voice_data); } } } incognito_split_mode_ = is_app(); if (source.HasKey(keys::kIncognito)) { std::string value; if (!source.GetString(keys::kIncognito, &value)) { *error = errors::kInvalidIncognitoBehavior; return false; } if (value == values::kIncognitoSpanning) { incognito_split_mode_ = false; } else if (value == values::kIncognitoSplit) { incognito_split_mode_ = true; } else { *error = errors::kInvalidIncognitoBehavior; return false; } } if (HasMultipleUISurfaces()) { *error = errors::kOneUISurfaceOnly; return false; } InitEffectiveHostPermissions(); DCHECK(source.Equals(manifest_value_.get())); return true; }
CWE-20
183,866
4,901
109017237804472748773685496359978813060
null
null
null
Chrome
9400c64565586091f67d4131850fd0836b18b511
1
void GpuDataManager::UpdateGpuInfo(const GPUInfo& gpu_info) { { base::AutoLock auto_lock(gpu_info_lock_); if (!gpu_info_.Merge(gpu_info)) return; RunGpuInfoUpdateCallbacks(); content::GetContentClient()->SetGpuInfo(gpu_info_); } UpdateGpuFeatureFlags(); }
CWE-399
183,867
4,902
96182624877678014608467662575288459365
null
null
null
Chrome
f837b6744eb9ca9d8e4f2e93d9118bf787ca5e24
1
bool TypedUrlModelAssociator::AssociateModels() { VLOG(1) << "Associating TypedUrl Models"; DCHECK(expected_loop_ == MessageLoop::current()); std::vector<history::URLRow> typed_urls; if (!history_backend_->GetAllTypedURLs(&typed_urls)) { LOG(ERROR) << "Could not get the typed_url entries."; return false; } std::map<history::URLID, history::VisitVector> visit_vectors; for (std::vector<history::URLRow>::iterator ix = typed_urls.begin(); ix != typed_urls.end(); ++ix) { if (!history_backend_->GetVisitsForURL(ix->id(), &(visit_vectors[ix->id()]))) { LOG(ERROR) << "Could not get the url's visits."; return false; } if (visit_vectors[ix->id()].empty()) { history::VisitRow visit( ix->id(), ix->last_visit(), 0, PageTransition::TYPED, 0); visit_vectors[ix->id()].push_back(visit); } } TypedUrlTitleVector titles; TypedUrlVector new_urls; TypedUrlVisitVector new_visits; TypedUrlUpdateVector updated_urls; { sync_api::WriteTransaction trans(sync_service_->GetUserShare()); sync_api::ReadNode typed_url_root(&trans); if (!typed_url_root.InitByTagLookup(kTypedUrlTag)) { LOG(ERROR) << "Server did not create the top-level typed_url node. We " << "might be running against an out-of-date server."; return false; } std::set<std::string> current_urls; for (std::vector<history::URLRow>::iterator ix = typed_urls.begin(); ix != typed_urls.end(); ++ix) { std::string tag = ix->url().spec(); history::VisitVector& visits = visit_vectors[ix->id()]; sync_api::ReadNode node(&trans); if (node.InitByClientTagLookup(syncable::TYPED_URLS, tag)) { const sync_pb::TypedUrlSpecifics& typed_url( node.GetTypedUrlSpecifics()); DCHECK_EQ(tag, typed_url.url()); history::URLRow new_url(*ix); std::vector<history::VisitInfo> added_visits; int difference = MergeUrls(typed_url, *ix, &visits, &new_url, &added_visits); if (difference & DIFF_UPDATE_NODE) { sync_api::WriteNode write_node(&trans); if (!write_node.InitByClientTagLookup(syncable::TYPED_URLS, tag)) { LOG(ERROR) << "Failed to edit typed_url sync node."; return false; } if (typed_url.visits_size() > 0) { base::Time earliest_visit = base::Time::FromInternalValue(typed_url.visits(0)); for (history::VisitVector::iterator it = visits.begin(); it != visits.end() && it->visit_time < earliest_visit; ) { it = visits.erase(it); } DCHECK(visits.size() > 0); } else { NOTREACHED() << "Syncing typed URL with no visits: " << typed_url.url(); } WriteToSyncNode(new_url, visits, &write_node); } if (difference & DIFF_LOCAL_TITLE_CHANGED) { titles.push_back(std::pair<GURL, string16>(new_url.url(), new_url.title())); } if (difference & DIFF_LOCAL_ROW_CHANGED) { updated_urls.push_back( std::pair<history::URLID, history::URLRow>(ix->id(), new_url)); } if (difference & DIFF_LOCAL_VISITS_ADDED) { new_visits.push_back( std::pair<GURL, std::vector<history::VisitInfo> >(ix->url(), added_visits)); } Associate(&tag, node.GetId()); } else { sync_api::WriteNode node(&trans); if (!node.InitUniqueByCreation(syncable::TYPED_URLS, typed_url_root, tag)) { LOG(ERROR) << "Failed to create typed_url sync node."; return false; } node.SetTitle(UTF8ToWide(tag)); WriteToSyncNode(*ix, visits, &node); Associate(&tag, node.GetId()); } current_urls.insert(tag); } int64 sync_child_id = typed_url_root.GetFirstChildId(); while (sync_child_id != sync_api::kInvalidId) { sync_api::ReadNode sync_child_node(&trans); if (!sync_child_node.InitByIdLookup(sync_child_id)) { LOG(ERROR) << "Failed to fetch child node."; return false; } const sync_pb::TypedUrlSpecifics& typed_url( sync_child_node.GetTypedUrlSpecifics()); if (current_urls.find(typed_url.url()) == current_urls.end()) { new_visits.push_back( std::pair<GURL, std::vector<history::VisitInfo> >( GURL(typed_url.url()), std::vector<history::VisitInfo>())); std::vector<history::VisitInfo>& visits = new_visits.back().second; history::URLRow new_url(GURL(typed_url.url())); TypedUrlModelAssociator::UpdateURLRowFromTypedUrlSpecifics( typed_url, &new_url); for (int c = 0; c < typed_url.visits_size(); ++c) { DCHECK(c == 0 || typed_url.visits(c) > typed_url.visits(c - 1)); DCHECK_LE(typed_url.visit_transitions(c), static_cast<int>(PageTransition::LAST_CORE)); visits.push_back(history::VisitInfo( base::Time::FromInternalValue(typed_url.visits(c)), static_cast<PageTransition::Type>( typed_url.visit_transitions(c)))); } Associate(&typed_url.url(), sync_child_node.GetId()); new_urls.push_back(new_url); } sync_child_id = sync_child_node.GetSuccessorId(); } } return WriteToHistoryBackend(&titles, &new_urls, &updated_urls, &new_visits, NULL); }
CWE-399
183,929
4,953
235500637610336334647715426218352685174
null
null
null
Chrome
5fd35e5359c6345b8709695cd71fba307318e6aa
1
LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h) const { if (h.isFixed()) return computeContentBoxLogicalHeight(h.value()); if (isRenderView()) return isHorizontalWritingMode() ? toRenderView(this)->frameView()->visibleHeight() : toRenderView(this)->frameView()->visibleWidth(); if (isTableCell() && (h.isAuto() || h.isPercent())) return overrideHeight() - borderAndPaddingLogicalWidth(); if (h.isPercent()) return computeContentBoxLogicalHeight(h.calcValue(containingBlock()->availableLogicalHeight())); if (isRenderBlock() && isPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) { RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this)); LayoutUnit oldHeight = block->logicalHeight(); block->computeLogicalHeight(); LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentLogicalHeight()); block->setLogicalHeight(oldHeight); return computeContentBoxLogicalHeight(newHeight); } return containingBlock()->availableLogicalHeight(); }
CWE-20
184,085
5,096
64775624233662644301630204550974982901
null
null
null
Chrome
0c4225d1e9b23e7071bbf47ada310a9a7e5661a3
1
bool JSArray::increaseVectorPrefixLength(unsigned newLength) { ArrayStorage* storage = m_storage; unsigned vectorLength = m_vectorLength; ASSERT(newLength > vectorLength); ASSERT(newLength <= MAX_STORAGE_VECTOR_INDEX); unsigned newVectorLength = getNewVectorLength(newLength); void* newBaseStorage = fastMalloc(storageSize(newVectorLength + m_indexBias)); if (!newBaseStorage) return false; m_indexBias += newVectorLength - newLength; m_storage = reinterpret_cast_ptr<ArrayStorage*>(static_cast<char*>(newBaseStorage) + m_indexBias * sizeof(JSValue)); memcpy(m_storage, storage, storageSize(0)); memcpy(&m_storage->m_vector[newLength - m_vectorLength], &storage->m_vector[0], vectorLength * sizeof(JSValue)); m_storage->m_allocBase = newBaseStorage; m_vectorLength = newLength; fastFree(storage->m_allocBase); Heap::heap(this)->reportExtraMemoryCost(storageSize(newVectorLength) - storageSize(vectorLength)); return true; }
184,134
5,140
105469674364815897900117467885686093478
null
null
null
Chrome
ec14f31eca3a51f665432973552ee575635132b3
1
Eina_Bool ewk_view_scale_set(Evas_Object* ewkView, float scaleFactor, Evas_Coord centerX, Evas_Coord centerY) { EWK_VIEW_SD_GET_OR_RETURN(ewkView, smartData, false); EWK_VIEW_PRIV_GET_OR_RETURN(smartData, priv, false); float currentScaleFactor = ewk_view_scale_get(ewkView); if (currentScaleFactor == -1) return false; int x, y; ewk_frame_scroll_pos_get(smartData->main_frame, &x, &y); x = static_cast<int>(((x + centerX) / currentScaleFactor) * scaleFactor) - centerX; y = static_cast<int>(((y + centerY) / currentScaleFactor) * scaleFactor) - centerY; priv->page->setPageScaleFactor(scaleFactor, WebCore::LayoutPoint(x, y)); return true; }
184,135
5,141
243543869762520204045292402353309349493
null
null
null
Chrome
648cbc15a6830523b3a4eb78d674f059bd2a7ce9
1
void NetworkScreen::OnConnectionTimeout() { StopWaitingForConnection(network_id_); NetworkLibrary* network = CrosLibrary::Get()->GetNetworkLibrary(); bool is_connected = network && network->Connected(); if (!is_connected && !view()->is_dialog_open() && !(help_app_.get() && help_app_->is_open())) { ClearErrors(); views::View* network_control = view()->GetNetworkControlView(); bubble_ = MessageBubble::Show( network_control->GetWidget(), network_control->GetScreenBounds(), BubbleBorder::LEFT_TOP, ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_WARNING), UTF16ToWide(l10n_util::GetStringFUTF16( IDS_NETWORK_SELECTION_ERROR, l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME), network_id_)), UTF16ToWide( l10n_util::GetStringUTF16(IDS_NETWORK_SELECTION_ERROR_HELP)), this); network_control->RequestFocus(); } }
184,181
5,178
169965446383376320286840210510096470628
null
null
null
Chrome
2c3d133e93d0455eb64bd96384f317674db79ab5
1
IntRect InlineTextBox::selectionRect(int tx, int ty, int startPos, int endPos) { int sPos = max(startPos - m_start, 0); int ePos = min(endPos - m_start, (int)m_len); if (sPos > ePos) return IntRect(); RenderText* textObj = textRenderer(); int selTop = selectionTop(); int selHeight = selectionHeight(); RenderStyle* styleToUse = textObj->style(m_firstLine); const Font& f = styleToUse->font(); const UChar* characters = textObj->text()->characters() + m_start; int len = m_len; BufferForAppendingHyphen charactersWithHyphen; if (ePos == len && hasHyphen()) { adjustCharactersAndLengthForHyphen(charactersWithHyphen, styleToUse, characters, len); ePos = len; } IntRect r = enclosingIntRect(f.selectionRectForText(TextRun(characters, len, textObj->allowTabs(), textPos(), m_toAdd, !isLeftToRightDirection(), m_dirOverride), IntPoint(tx + m_x, ty + selTop), selHeight, sPos, ePos)); if (r.x() > tx + m_x + m_logicalWidth) r.setWidth(0); else if (r.right() - 1 > tx + m_x + m_logicalWidth) r.setWidth(tx + m_x + m_logicalWidth - r.x()); return r; }
184,204
5,196
123698694792161809807343095851420074040
null
null
null
Chrome
74c1ec481b33194dc7a428f2d58fc89640b313ae
1
void GLES2DecoderImpl::DoGetFramebufferAttachmentParameteriv( GLenum target, GLenum attachment, GLenum pname, GLint* params) { if (!bound_framebuffer_) { SetGLError(GL_INVALID_OPERATION, "glFramebufferAttachmentParameteriv: no framebuffer bound"); return; } glGetFramebufferAttachmentParameterivEXT(target, attachment, pname, params); }
184,205
5,197
140697587736518506039098662235197331054
null
null
null
Chrome
ffeada1f2de5281d59ea48c94c4001a568092cd3
1
bool SandboxedExtensionUnpacker::ValidateSignature() { ScopedStdioHandle file(file_util::OpenFile(crx_path_, "rb")); if (!file.get()) { ReportFailure("Could not open crx file for reading"); return false; } ExtensionHeader header; size_t len; len = fread(&header, 1, sizeof(ExtensionHeader), file.get()); if (len < sizeof(ExtensionHeader)) { ReportFailure("Invalid crx header"); return false; } if (strncmp(kExtensionHeaderMagic, header.magic, sizeof(header.magic))) { ReportFailure("Bad magic number"); return false; } if (header.version != kCurrentVersion) { ReportFailure("Bad version number"); return false; } if (header.key_size > kMaxPublicKeySize || header.signature_size > kMaxSignatureSize) { ReportFailure("Excessively large key or signature"); return false; } if (header.key_size == 0) { ReportFailure("Key length is zero"); return false; } std::vector<uint8> key; key.resize(header.key_size); len = fread(&key.front(), sizeof(uint8), header.key_size, file.get()); if (len < header.key_size) { ReportFailure("Invalid public key"); return false; } std::vector<uint8> signature; signature.resize(header.signature_size); len = fread(&signature.front(), sizeof(uint8), header.signature_size, file.get()); if (len < header.signature_size) { ReportFailure("Invalid signature"); return false; } base::SignatureVerifier verifier; if (!verifier.VerifyInit(extension_misc::kSignatureAlgorithm, sizeof(extension_misc::kSignatureAlgorithm), &signature.front(), signature.size(), &key.front(), key.size())) { ReportFailure("Signature verification initialization failed. " "This is most likely caused by a public key in " "the wrong format (should encode algorithm)."); return false; } unsigned char buf[1 << 12]; while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0) verifier.VerifyUpdate(buf, len); if (!verifier.VerifyFinal()) { ReportFailure("Signature verification failed"); return false; } base::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()), key.size()), &public_key_); return true; }
184,206
5,198
270299633739389198959151342100039297421
null
null
null
Chrome
b9866ebc631655c593a2ac60a3c7cf7d217ccf5d
1
void AudioOutputController::DoFlush() { DCHECK_EQ(message_loop_, MessageLoop::current()); if (!sync_reader_) { if (state_ != kPaused) return; buffer_.Clear(); } }
184,211
5,202
160217679043133965253484493831221900880
null
null
null
Chrome
a75c45bf1cad925548a75bf88f828443bc8ee27d
1
PPB_URLLoader_Impl::~PPB_URLLoader_Impl() { }
CWE-416
184,221
5,210
43110833936314473152044641356965998042
null
null
null
Chrome
8083841913b8eb8018ae52f67c923f0b3d66c466
1
bool HasPermissionsForFile(const FilePath& file, int permissions) { FilePath current_path = file.StripTrailingSeparators(); FilePath last_path; while (current_path != last_path) { if (file_permissions_.find(current_path) != file_permissions_.end()) return (file_permissions_[current_path] & permissions) == permissions; last_path = current_path; current_path = current_path.DirName(); } return false; }
184,224
5,211
70908000102023359195829425101355034226
null
null
null
Chrome
6e487b9db2ff0324523a040180f8da42796aeef5
1
xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { xmlChar limit = 0; xmlChar *buf = NULL; xmlChar *rep = NULL; int len = 0; int buf_size = 0; int c, l, in_space = 0; xmlChar *current = NULL; xmlEntityPtr ent; if (NXT(0) == '"') { ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; limit = '"'; NEXT; } else if (NXT(0) == '\'') { limit = '\''; ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; NEXT; } else { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return(NULL); } /* * allocate a translation buffer. */ buf_size = XML_PARSER_BUFFER_SIZE; buf = (xmlChar *) xmlMallocAtomic(buf_size * sizeof(xmlChar)); if (buf == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. */ c = CUR_CHAR(l); while ((NXT(0) != limit) && /* checked */ (IS_CHAR(c)) && (c != '<')) { if (c == 0) break; if (c == '&') { in_space = 0; if (NXT(1) == '#') { int val = xmlParseCharRef(ctxt); if (val == '&') { if (ctxt->replaceEntities) { if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; } else { /* * The reparsing will be done in xmlStringGetNodeList() * called by the attribute() function in SAX.c */ if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } } else if (val != 0) { if (len > buf_size - 10) { growBuffer(buf, 10); } len += xmlCopyChar(0, &buf[len], val); } } else { ent = xmlParseEntityRef(ctxt); ctxt->nbentities++; if (ent != NULL) ctxt->nbentities += ent->owner; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (len > buf_size - 10) { growBuffer(buf, 10); } if ((ctxt->replaceEntities == 0) && (ent->content[0] == '&')) { buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } else { buf[len++] = ent->content[0]; } } else if ((ent != NULL) && (ctxt->replaceEntities != 0)) { if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming */ if ((*current == 0xD) || (*current == 0xA) || (*current == 0x9)) { buf[len++] = 0x20; current++; } else buf[len++] = *current++; if (len > buf_size - 10) { growBuffer(buf, 10); } } xmlFree(rep); rep = NULL; } } else { if (len > buf_size - 10) { growBuffer(buf, 10); } if (ent->content != NULL) buf[len++] = ent->content[0]; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; /* * This may look absurd but is needed to detect * entities problems */ if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (ent->content != NULL)) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { xmlFree(rep); rep = NULL; } } /* * Just output the reference */ buf[len++] = '&'; while (len > buf_size - i - 10) { growBuffer(buf, i + 10); } for (;i > 0;i--) buf[len++] = *cur++; buf[len++] = ';'; } } } else { if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) { if ((len != 0) || (!normalize)) { if ((!normalize) || (!in_space)) { COPY_BUF(l,buf,len,0x20); while (len > buf_size - 10) { growBuffer(buf, 10); } } in_space = 1; } } else { in_space = 0; COPY_BUF(l,buf,len,c); if (len > buf_size - 10) { growBuffer(buf, 10); } } NEXTL(l); } GROW; c = CUR_CHAR(l); } if ((in_space) && (normalize)) { while (buf[len - 1] == 0x20) len--; } buf[len] = 0; if (RAW == '<') { xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL); } else if (RAW != limit) { if ((c != 0) && (!IS_CHAR(c))) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, "invalid character in attribute value\n"); } else { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue: ' expected\n"); } } else NEXT; if (attlen != NULL) *attlen = len; return(buf); mem_error: xmlErrMemory(ctxt, NULL); if (buf != NULL) xmlFree(buf); if (rep != NULL) xmlFree(rep); return(NULL); }
CWE-119
184,270
5,255
248539584304709647354178006225212249012
null
null
null
Chrome
ef97ce340c462d5212336f09bf8075d1cb10faa4
1
void PluginInfoMessageFilter::Context::DecidePluginStatus( const GetPluginInfo_Params& params, const WebPluginInfo& plugin, PluginFinder* plugin_finder, ChromeViewHostMsg_GetPluginInfo_Status* status, std::string* group_identifier, string16* group_name) const { PluginInstaller* installer = plugin_finder->GetPluginInstaller(plugin); *group_name = installer->name(); *group_identifier = installer->identifier(); ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT; bool uses_default_content_setting = true; GetPluginContentSetting(plugin, params.top_origin_url, params.url, *group_identifier, &plugin_setting, &uses_default_content_setting); DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT); #if defined(ENABLE_PLUGIN_INSTALLATION) PluginInstaller::SecurityStatus plugin_status = installer->GetSecurityStatus(plugin); if (plugin_status == PluginInstaller::SECURITY_STATUS_OUT_OF_DATE && !allow_outdated_plugins_.GetValue()) { if (allow_outdated_plugins_.IsManaged()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed; } else { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked; } return; } if ((plugin_status == PluginInstaller::SECURITY_STATUS_REQUIRES_AUTHORIZATION || PluginService::GetInstance()->IsPluginUnstable(plugin.path)) && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && uses_default_content_setting) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized; return; } #endif if (plugin_setting == CONTENT_SETTING_ASK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay; else if (plugin_setting == CONTENT_SETTING_BLOCK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kBlocked; }
184,282
5,266
12752085692413985630426692950978622141
null
null
null
Chrome
2511466dd15750f2ab0e5cecc30010f0a3f7949c
1
void FocusFirstNameField() { LOG(WARNING) << "Clicking on the tab."; ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER)); ASSERT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER)); LOG(WARNING) << "Focusing the first name field."; bool result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( render_view_host(), L"", L"if (document.readyState === 'complete')" L" document.getElementById('firstname').focus();" L"else" L" domAutomationController.send(false);", &result)); ASSERT_TRUE(result); }
CWE-119
184,295
5,278
40730733545771882199774349545138877774
null
null
null
Chrome
76a3314ac3b711e01fae3b76a5d85f0eddeeec0b
1
bool BaseSettingChange::Init(Profile* profile) { DCHECK(profile); profile_ = profile; return true; }
CWE-119
184,330
5,308
280299927734355536949977929219195325144
null
null
null
Chrome
b654d718218ece17c496e74acd250038656f31c3
1
CString fileSystemRepresentation(const String&) { ASSERT_NOT_REACHED(); return ""; }
184,333
5,311
242540235376333096147675682005141979166
null
null
null
Chrome
3ea4ba8af75eb37860c15d02af94f272e5bbc235
1
void FileSystemOperation::GetUsageAndQuotaThenRunTask( const GURL& origin, FileSystemType type, const base::Closure& task, const base::Closure& error_callback) { quota::QuotaManagerProxy* quota_manager_proxy = file_system_context()->quota_manager_proxy(); if (!quota_manager_proxy || !file_system_context()->GetQuotaUtil(type)) { operation_context_.set_allowed_bytes_growth(kint64max); task.Run(); return; } TaskParamsForDidGetQuota params; params.origin = origin; params.type = type; params.task = task; params.error_callback = error_callback; DCHECK(quota_manager_proxy); DCHECK(quota_manager_proxy->quota_manager()); quota_manager_proxy->quota_manager()->GetUsageAndQuota( origin, FileSystemTypeToQuotaStorageType(type), base::Bind(&FileSystemOperation::DidGetUsageAndQuotaAndRunTask, base::Unretained(this), params)); }
184,336
5,312
95170407629947645599050509833132522474
null
null
null
Chrome
9f5ebcc99c8cd3a19be087be38f14c99cfe9e006
1
static void* lookupOpenGLFunctionAddress(const char* functionName, bool* success = 0) { if (success && !*success) return 0; void* target = getProcAddress(functionName); if (target) return target; String fullFunctionName(functionName); fullFunctionName.append("ARB"); target = getProcAddress(fullFunctionName.utf8().data()); if (target) return target; fullFunctionName = functionName; fullFunctionName.append("EXT"); target = getProcAddress(fullFunctionName.utf8().data()); #if defined(GL_ES_VERSION_2_0) fullFunctionName = functionName; fullFunctionName.append("ANGLE"); target = getProcAddress(fullFunctionName.utf8().data()); fullFunctionName = functionName; fullFunctionName.append("APPLE"); target = getProcAddress(fullFunctionName.utf8().data()); #endif if (!target && success) *success = false; return target; }
184,353
5,326
142369121156279875994689980934247292740
null
null
null
Chrome
f81fcab3b31dfaff3473e8eb94c6531677116242
1
bool EditorClientBlackBerry::shouldChangeSelectedRange(Range* fromRange, Range* toRange, EAffinity affinity, bool stillSelecting) { if (m_webPagePrivate->m_dumpRenderTree) return m_webPagePrivate->m_dumpRenderTree->shouldChangeSelectedDOMRangeToDOMRangeAffinityStillSelecting(fromRange, toRange, static_cast<int>(affinity), stillSelecting); Frame* frame = m_webPagePrivate->focusedOrMainFrame(); if (frame && frame->document()) { if (frame->document()->focusedNode() && frame->document()->focusedNode()->hasTagName(HTMLNames::selectTag)) return false; if (m_webPagePrivate->m_inputHandler->isInputMode() && fromRange && toRange && (fromRange->startContainer() == toRange->startContainer())) m_webPagePrivate->m_inputHandler->notifyClientOfKeyboardVisibilityChange(true); } return true; }
184,354
5,327
3172131646278640413633035949444820483
null
null
null
Chrome
b7a161633fd7ecb59093c2c56ed908416292d778
1
JSRetainPtr<JSStringRef> AccessibilityUIElement::stringValue() { return JSStringCreateWithCharacters(0, 0); }
184,487
5,444
88411444336712579420402558041153887925
null
null
null
Chrome
e741149a6b7872a2bf1f2b6cc0a56e836592fb77
1
xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlNodePtr cur = NULL; long val; xmlChar str[30]; xmlDocPtr doc; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlXPathObjectPtr obj; xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } xmlXPathFreeObject(obj); } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ if (cur->type != XML_NAMESPACE_DECL) doc = cur->doc; else { xmlNsPtr ns = (xmlNsPtr) cur; if (ns->context != NULL) doc = ns->context; else doc = ctxt->context->doc; } val = (long)((char *)cur - (char *)doc); if (val >= 0) { sprintf((char *)str, "idp%ld", val); } else { sprintf((char *)str, "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); }
CWE-399
184,491
5,446
91106450881227737310553850084306207301
null
null
null
Chrome
68b6502084af7e2021f7321633f5fbb5f997a58b
1
SSLErrorInfo SSLErrorInfo::CreateError(ErrorType error_type, net::X509Certificate* cert, const GURL& request_url) { string16 title, details, short_description; std::vector<string16> extra_info; switch (error_type) { case CERT_COMMON_NAME_INVALID: { title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_COMMON_NAME_INVALID_TITLE); std::vector<std::string> dns_names; cert->GetDNSNames(&dns_names); DCHECK(!dns_names.empty()); size_t i = 0; for (; i < dns_names.size(); ++i) { if (dns_names[i] == cert->subject().common_name) break; } if (i == dns_names.size()) i = 0; details = l10n_util::GetStringFUTF16(IDS_CERT_ERROR_COMMON_NAME_INVALID_DETAILS, UTF8ToUTF16(request_url.host()), UTF8ToUTF16(dns_names[i]), UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_COMMON_NAME_INVALID_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringFUTF16( IDS_CERT_ERROR_COMMON_NAME_INVALID_EXTRA_INFO_2, UTF8ToUTF16(cert->subject().common_name), UTF8ToUTF16(request_url.host()))); break; } case CERT_DATE_INVALID: extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); if (cert->HasExpired()) { title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXPIRED_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_EXPIRED_DETAILS, UTF8ToUTF16(request_url.host()), UTF8ToUTF16(request_url.host()), base::TimeFormatFriendlyDateAndTime(base::Time::Now())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXPIRED_DESCRIPTION); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_EXPIRED_DETAILS_EXTRA_INFO_2)); } else { title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_NOT_YET_VALID_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_NOT_YET_VALID_DETAILS, UTF8ToUTF16(request_url.host()), UTF8ToUTF16(request_url.host()), base::TimeFormatFriendlyDateAndTime(base::Time::Now())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_NOT_YET_VALID_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16( IDS_CERT_ERROR_NOT_YET_VALID_DETAILS_EXTRA_INFO_2)); } break; case CERT_AUTHORITY_INVALID: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_AUTHORITY_INVALID_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back(l10n_util::GetStringFUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_EXTRA_INFO_2, UTF8ToUTF16(request_url.host()), UTF8ToUTF16(request_url.host()))); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_AUTHORITY_INVALID_EXTRA_INFO_3)); break; case CERT_CONTAINS_ERRORS: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_CONTAINS_ERRORS_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_CONTAINS_ERRORS_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_CONTAINS_ERRORS_DESCRIPTION); extra_info.push_back( l10n_util::GetStringFUTF16(IDS_CERT_ERROR_EXTRA_INFO_1, UTF8ToUTF16(request_url.host()))); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_CONTAINS_ERRORS_EXTRA_INFO_2)); break; case CERT_NO_REVOCATION_MECHANISM: title = l10n_util::GetStringUTF16( IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_TITLE); details = l10n_util::GetStringUTF16( IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_DETAILS); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_NO_REVOCATION_MECHANISM_DESCRIPTION); break; case CERT_UNABLE_TO_CHECK_REVOCATION: title = l10n_util::GetStringUTF16( IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_TITLE); details = l10n_util::GetStringUTF16( IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_DETAILS); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_DESCRIPTION); break; case CERT_REVOKED: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_TITLE); details = l10n_util::GetStringFUTF16(IDS_CERT_ERROR_REVOKED_CERT_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_REVOKED_CERT_EXTRA_INFO_2)); break; case CERT_INVALID: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_INVALID_CERT_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_INVALID_CERT_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_INVALID_CERT_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back(l10n_util::GetStringUTF16( IDS_CERT_ERROR_INVALID_CERT_EXTRA_INFO_2)); break; case CERT_WEAK_SIGNATURE_ALGORITHM: title = l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_SIGNATURE_ALGORITHM_EXTRA_INFO_2)); break; case CERT_WEAK_KEY: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_WEAK_KEY_TITLE); details = l10n_util::GetStringFUTF16( IDS_CERT_ERROR_WEAK_KEY_DETAILS, UTF8ToUTF16(request_url.host())); short_description = l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_KEY_DESCRIPTION); extra_info.push_back( l10n_util::GetStringUTF16(IDS_CERT_ERROR_EXTRA_INFO_1)); extra_info.push_back( l10n_util::GetStringUTF16( IDS_CERT_ERROR_WEAK_KEY_EXTRA_INFO_2)); break; case UNKNOWN: title = l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_TITLE); details = l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_DETAILS); short_description = l10n_util::GetStringUTF16(IDS_CERT_ERROR_UNKNOWN_ERROR_DESCRIPTION); break; default: NOTREACHED(); } return SSLErrorInfo(title, details, short_description, extra_info); }
CWE-79
184,492
5,447
53399739575118663367424243295997144464
null
null
null
Chrome
00f695aec78100076c4085388ad13eafe6eaa7c1
1
void DesktopNativeWidgetHelperAura::PreInitialize( aura::Window* window, const Widget::InitParams& params) { #if !defined(OS_WIN) if (params.type == Widget::InitParams::TYPE_POPUP) { is_embedded_window_ = true; position_client_.reset(new EmbeddedWindowScreenPositionClient(widget_)); aura::client::SetScreenPositionClient(window, position_client_.get()); return; } else if (params.type == Widget::InitParams::TYPE_CONTROL) { return; } #endif gfx::Rect bounds = params.bounds; if (bounds.IsEmpty()) { bounds.set_size(gfx::Size(100, 100)); } root_window_.reset(new aura::RootWindow(bounds)); root_window_->Init(); root_window_->set_focus_manager(new aura::FocusManager); root_window_event_filter_ = new aura::shared::RootWindowEventFilter(root_window_.get()); root_window_->SetEventFilter(root_window_event_filter_); input_method_filter_.reset(new aura::shared::InputMethodEventFilter()); root_window_event_filter_->AddFilter(input_method_filter_.get()); aura::DesktopActivationClient* activation_client = new aura::DesktopActivationClient(root_window_.get()); #if defined(USE_X11) x11_window_event_filter_.reset( new X11WindowEventFilter(root_window_.get(), activation_client, widget_)); x11_window_event_filter_->SetUseHostWindowBorders(false); root_window_event_filter_->AddFilter(x11_window_event_filter_.get()); #endif root_window_->AddRootWindowObserver(this); aura::client::SetActivationClient(root_window_.get(), activation_client); aura::client::SetDispatcherClient(root_window_.get(), new aura::DesktopDispatcherClient); position_client_.reset( new RootWindowScreenPositionClient(root_window_.get())); aura::client::SetScreenPositionClient(window, position_client_.get()); }
184,493
5,448
178982217967800104177636099742167175327
null
null
null
Chrome
a151041807a7e3c702c5f935a742368333aa69d4
1
void GpuProcessHostUIShim::OnResizeView(int32 surface_id, int32 route_id, gfx::Size size) { ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_ResizeViewACK(route_id)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(surface_id); if (!view) return; gfx::GLSurfaceHandle surface = view->GetCompositingSurface(); #if defined(TOOLKIT_GTK) GdkWindow* window = reinterpret_cast<GdkWindow*>( gdk_xid_table_lookup(surface.handle)); if (window) { Display* display = GDK_WINDOW_XDISPLAY(window); gdk_window_resize(window, size.width(), size.height()); XSync(display, False); } #elif defined(OS_WIN) SetWindowPos(surface.handle, NULL, 0, 0, std::max(1, size.width()), std::max(1, size.height()), SWP_NOSENDCHANGING | SWP_NOCOPYBITS | SWP_NOZORDER | SWP_NOACTIVATE | SWP_DEFERERASE); #endif }
184,494
5,449
214720266517195705186209732602904101120
null
null
null
Chrome
e3171b346e6919f4162ea128d0f7b342cf878fd4
1
PowerPopupView() { SetHorizontalAlignment(ALIGN_RIGHT); UpdateText(); }
CWE-399
184,535
5,484
112374548428927138430071883198540033125
null
null
null
Chrome
dbcfe72cb16222c9f7e7907fcc5f35b27cc25331
1
bool GetURLRowForAutocompleteMatch(Profile* profile, const AutocompleteMatch& match, history::URLRow* url_row) { DCHECK(url_row); HistoryService* history_service = profile->GetHistoryService(Profile::EXPLICIT_ACCESS); if (!history_service) return false; history::URLDatabase* url_db = history_service->InMemoryDatabase(); return url_db && (url_db->GetRowForURL(match.destination_url, url_row) != 0); }
CWE-20
184,585
5,531
159436592094021646442866975951391876709
null
null
null
Chrome
3511b6ec1e955578ddb6e90f0cc99f824e36026e
1
virtual void SetUpCommandLine(CommandLine* command_line) { GpuFeatureTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnableThreadedCompositing); }
CWE-399
184,586
5,532
260191358944750536748131359510248603618
null
null
null
Chrome
7c2785fab1685c8735288dfbbbb617d9c4f5d8b2
1
bool GraphicsContext3D::getImageData(Image* image, GC3Denum format, GC3Denum type, bool premultiplyAlpha, bool ignoreGammaAndColorProfile, Vector<uint8_t>& outputVector) { if (!image) return false; CGImageRef cgImage; RetainPtr<CGImageRef> decodedImage; bool hasAlpha = image->isBitmapImage() ? static_cast<BitmapImage*>(image)->frameHasAlphaAtIndex(0) : true; if ((ignoreGammaAndColorProfile || (hasAlpha && !premultiplyAlpha)) && image->data()) { ImageSource decoder(ImageSource::AlphaNotPremultiplied, ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied); decoder.setData(image->data(), true); if (!decoder.frameCount()) return false; decodedImage.adoptCF(decoder.createFrameAtIndex(0)); cgImage = decodedImage.get(); } else cgImage = image->nativeImageForCurrentFrame(); if (!cgImage) return false; size_t width = CGImageGetWidth(cgImage); size_t height = CGImageGetHeight(cgImage); if (!width || !height) return false; CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage); CGColorSpaceModel model = CGColorSpaceGetModel(colorSpace); if (model == kCGColorSpaceModelIndexed) { RetainPtr<CGContextRef> bitmapContext; bitmapContext.adoptCF(CGBitmapContextCreate(0, width, height, 8, width * 4, deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); if (!bitmapContext) return false; CGContextSetBlendMode(bitmapContext.get(), kCGBlendModeCopy); CGContextSetInterpolationQuality(bitmapContext.get(), kCGInterpolationNone); CGContextDrawImage(bitmapContext.get(), CGRectMake(0, 0, width, height), cgImage); decodedImage.adoptCF(CGBitmapContextCreateImage(bitmapContext.get())); cgImage = decodedImage.get(); } size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage); size_t bitsPerPixel = CGImageGetBitsPerPixel(cgImage); if (bitsPerComponent != 8 && bitsPerComponent != 16) return false; if (bitsPerPixel % bitsPerComponent) return false; size_t componentsPerPixel = bitsPerPixel / bitsPerComponent; CGBitmapInfo bitInfo = CGImageGetBitmapInfo(cgImage); bool bigEndianSource = false; if (bitsPerComponent == 16) { switch (bitInfo & kCGBitmapByteOrderMask) { case kCGBitmapByteOrder16Big: bigEndianSource = true; break; case kCGBitmapByteOrder16Little: bigEndianSource = false; break; case kCGBitmapByteOrderDefault: bigEndianSource = true; break; default: return false; } } else { switch (bitInfo & kCGBitmapByteOrderMask) { case kCGBitmapByteOrder32Big: bigEndianSource = true; break; case kCGBitmapByteOrder32Little: bigEndianSource = false; break; case kCGBitmapByteOrderDefault: bigEndianSource = true; break; default: return false; } } AlphaOp neededAlphaOp = AlphaDoNothing; AlphaFormat alphaFormat = AlphaFormatNone; switch (CGImageGetAlphaInfo(cgImage)) { case kCGImageAlphaPremultipliedFirst: if (!premultiplyAlpha) neededAlphaOp = AlphaDoUnmultiply; alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaFirst: if (premultiplyAlpha) neededAlphaOp = AlphaDoPremultiply; alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaNoneSkipFirst: alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaPremultipliedLast: if (!premultiplyAlpha) neededAlphaOp = AlphaDoUnmultiply; alphaFormat = AlphaFormatLast; break; case kCGImageAlphaLast: if (premultiplyAlpha) neededAlphaOp = AlphaDoPremultiply; alphaFormat = AlphaFormatLast; break; case kCGImageAlphaNoneSkipLast: alphaFormat = AlphaFormatLast; break; case kCGImageAlphaNone: alphaFormat = AlphaFormatNone; break; default: return false; } SourceDataFormat srcDataFormat = getSourceDataFormat(componentsPerPixel, alphaFormat, bitsPerComponent == 16, bigEndianSource); if (srcDataFormat == SourceFormatNumFormats) return false; RetainPtr<CFDataRef> pixelData; pixelData.adoptCF(CGDataProviderCopyData(CGImageGetDataProvider(cgImage))); if (!pixelData) return false; const UInt8* rgba = CFDataGetBytePtr(pixelData.get()); unsigned int packedSize; if (computeImageSizeInBytes(format, type, width, height, 1, &packedSize, 0) != GraphicsContext3D::NO_ERROR) return false; outputVector.resize(packedSize); unsigned int srcUnpackAlignment = 0; size_t bytesPerRow = CGImageGetBytesPerRow(cgImage); unsigned int padding = bytesPerRow - bitsPerPixel / 8 * width; if (padding) { srcUnpackAlignment = padding + 1; while (bytesPerRow % srcUnpackAlignment) ++srcUnpackAlignment; } bool rt = packPixels(rgba, srcDataFormat, width, height, srcUnpackAlignment, format, type, neededAlphaOp, outputVector.data()); return rt; }
CWE-399
184,587
5,533
194621381134065270873799783802424240477
null
null
null
Chrome
1595f66a8dec04864afd048809cd9d0802049feb
1
void removeAllDOMObjects() { DOMDataStore& store = DOMData::getCurrentStore(); v8::HandleScope scope; if (isMainThread()) { DOMData::removeObjectsFromWrapperMap<Node>(&store, store.domNodeMap()); DOMData::removeObjectsFromWrapperMap<Node>(&store, store.activeDomNodeMap()); } DOMData::removeObjectsFromWrapperMap<void>(&store, store.domObjectMap()); }
CWE-119
184,588
5,534
158567607023592302579743183252905901964
null
null
null
Chrome
1a828911013ff501b87aacc5b555e470b31f2909
1
uint64 Clipboard::GetSequenceNumber(Buffer buffer) { return 0; }
184,593
5,539
297545750745744992900533217407173054054
null
null
null
Chrome
04915c26ea193247b8a29aa24bfa34578ef5d39e
1
static inline quint32 swapBgrToRgb(quint32 pixel) { return ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff) | (pixel & 0xff00ff00); }
CWE-264
184,594
5,540
304658842432476569668324875792957709525
null
null
null
Chrome
b712795852f9d6073e062680e280634290c4ba5d
1
HarfBuzzShaperBase::HarfBuzzShaperBase(const Font* font, const TextRun& run) : m_font(font) , m_run(run) , m_wordSpacingAdjustment(font->wordSpacing()) , m_letterSpacing(font->letterSpacing()) { }
CWE-362
184,595
5,541
105068038334913611922876466353757950420
null
null
null
Chrome
0c14577c9905bd8161159ec7eaac810c594508d0
1
int OmniboxViewWin::OnPerformDropImpl(const views::DropTargetEvent& event, bool in_drag) { const ui::OSExchangeData& data = event.data(); if (data.HasURL()) { GURL url; string16 title; if (data.GetURLAndTitle(&url, &title)) { string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec()))); SetUserText(text); if (url.spec().length() == text.length()) model()->AcceptInput(CURRENT_TAB, true); return CopyOrLinkDragOperation(event.source_operations()); } } else if (data.HasString()) { int string_drop_position = drop_highlight_position(); string16 text; if ((string_drop_position != -1 || !in_drag) && data.GetString(&text)) { DCHECK(string_drop_position == -1 || ((string_drop_position >= 0) && (string_drop_position <= GetTextLength()))); if (in_drag) { if (event.source_operations()== ui::DragDropTypes::DRAG_MOVE) MoveSelectedText(string_drop_position); else InsertText(string_drop_position, text); } else { PasteAndGo(CollapseWhitespace(text, true)); } return CopyOrLinkDragOperation(event.source_operations()); } } return ui::DragDropTypes::DRAG_NONE; }
184,604
5,550
265871570571866678960599559846253798671
null
null
null
Chrome
7352baf29ac44d23cd580c2edfa8faf4e140a480
1
void SignatureUtil::CheckSignature( const FilePath& file_path, ClientDownloadRequest_SignatureInfo* signature_info) { VLOG(2) << "Checking signature for " << file_path.value(); WINTRUST_FILE_INFO file_info; file_info.cbStruct = sizeof(file_info); file_info.pcwszFilePath = file_path.value().c_str(); file_info.hFile = NULL; file_info.pgKnownSubject = NULL; WINTRUST_DATA wintrust_data; wintrust_data.cbStruct = sizeof(wintrust_data); wintrust_data.pPolicyCallbackData = NULL; wintrust_data.pSIPClientData = NULL; wintrust_data.dwUIChoice = WTD_UI_NONE; wintrust_data.fdwRevocationChecks = WTD_REVOKE_NONE; wintrust_data.dwUnionChoice = WTD_CHOICE_FILE; wintrust_data.pFile = &file_info; wintrust_data.dwStateAction = WTD_STATEACTION_VERIFY; wintrust_data.hWVTStateData = NULL; wintrust_data.pwszURLReference = NULL; wintrust_data.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL; wintrust_data.dwUIContext = WTD_UICONTEXT_EXECUTE; GUID policy_guid = WINTRUST_ACTION_GENERIC_VERIFY_V2; LONG result = WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE), &policy_guid, &wintrust_data); CRYPT_PROVIDER_DATA* prov_data = WTHelperProvDataFromStateData( wintrust_data.hWVTStateData); if (prov_data) { if (prov_data->csSigners > 0) { signature_info->set_trusted(result == ERROR_SUCCESS); } for (DWORD i = 0; i < prov_data->csSigners; ++i) { const CERT_CHAIN_CONTEXT* cert_chain_context = prov_data->pasSigners[i].pChainContext; for (DWORD j = 0; j < cert_chain_context->cChain; ++j) { CERT_SIMPLE_CHAIN* simple_chain = cert_chain_context->rgpChain[j]; ClientDownloadRequest_CertificateChain* chain = signature_info->add_certificate_chain(); for (DWORD k = 0; k < simple_chain->cElement; ++k) { CERT_CHAIN_ELEMENT* element = simple_chain->rgpElement[k]; chain->add_element()->set_certificate( element->pCertContext->pbCertEncoded, element->pCertContext->cbCertEncoded); } } } wintrust_data.dwStateAction = WTD_STATEACTION_CLOSE; WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE), &policy_guid, &wintrust_data); } }
CWE-20
184,605
5,551
283917935680180348820051506615368357795
null
null
null
Chrome
094c773bb6c144f07b004ff3d1886100f157f4f6
1
xsltCompilePatternInternal(const xmlChar *pattern, xmlDocPtr doc, xmlNodePtr node, xsltStylesheetPtr style, xsltTransformContextPtr runtime, int novar) { xsltParserContextPtr ctxt = NULL; xsltCompMatchPtr element, first = NULL, previous = NULL; int current, start, end, level, j; if (pattern == NULL) { xsltTransformError(NULL, NULL, node, "xsltCompilePattern : NULL pattern\n"); return(NULL); } ctxt = xsltNewParserContext(style, runtime); if (ctxt == NULL) return(NULL); ctxt->doc = doc; ctxt->elem = node; current = end = 0; while (pattern[current] != 0) { start = current; while (IS_BLANK_CH(pattern[current])) current++; end = current; level = 0; while ((pattern[end] != 0) && ((pattern[end] != '|') || (level != 0))) { if (pattern[end] == '[') level++; else if (pattern[end] == ']') level--; else if (pattern[end] == '\'') { end++; while ((pattern[end] != 0) && (pattern[end] != '\'')) end++; } else if (pattern[end] == '"') { end++; while ((pattern[end] != 0) && (pattern[end] != '"')) end++; } end++; } if (current == end) { xsltTransformError(NULL, NULL, node, "xsltCompilePattern : NULL pattern\n"); goto error; } element = xsltNewCompMatch(); if (element == NULL) { goto error; } if (first == NULL) first = element; else if (previous != NULL) previous->next = element; previous = element; ctxt->comp = element; ctxt->base = xmlStrndup(&pattern[start], end - start); if (ctxt->base == NULL) goto error; ctxt->cur = &(ctxt->base)[current - start]; element->pattern = ctxt->base; element->nsList = xmlGetNsList(doc, node); j = 0; if (element->nsList != NULL) { while (element->nsList[j] != NULL) j++; } element->nsNr = j; #ifdef WITH_XSLT_DEBUG_PATTERN xsltGenericDebug(xsltGenericDebugContext, "xsltCompilePattern : parsing '%s'\n", element->pattern); #endif /* Preset default priority to be zero. This may be changed by xsltCompileLocationPathPattern. */ element->priority = 0; xsltCompileLocationPathPattern(ctxt, novar); if (ctxt->error) { xsltTransformError(NULL, style, node, "xsltCompilePattern : failed to compile '%s'\n", element->pattern); if (style != NULL) style->errors++; goto error; } /* * Reverse for faster interpretation. */ xsltReverseCompMatch(ctxt, element); /* * Set-up the priority */ if (element->priority == 0) { /* if not yet determined */ if (((element->steps[0].op == XSLT_OP_ELEM) || (element->steps[0].op == XSLT_OP_ATTR) || (element->steps[0].op == XSLT_OP_PI)) && (element->steps[0].value != NULL) && (element->steps[1].op == XSLT_OP_END)) { ; /* previously preset */ } else if ((element->steps[0].op == XSLT_OP_ATTR) && (element->steps[0].value2 != NULL) && (element->steps[1].op == XSLT_OP_END)) { element->priority = -0.25; } else if ((element->steps[0].op == XSLT_OP_NS) && (element->steps[0].value != NULL) && (element->steps[1].op == XSLT_OP_END)) { element->priority = -0.25; } else if ((element->steps[0].op == XSLT_OP_ATTR) && (element->steps[0].value == NULL) && (element->steps[0].value2 == NULL) && (element->steps[1].op == XSLT_OP_END)) { element->priority = -0.5; } else if (((element->steps[0].op == XSLT_OP_PI) || (element->steps[0].op == XSLT_OP_TEXT) || (element->steps[0].op == XSLT_OP_ALL) || (element->steps[0].op == XSLT_OP_NODE) || (element->steps[0].op == XSLT_OP_COMMENT)) && (element->steps[1].op == XSLT_OP_END)) { element->priority = -0.5; } else { element->priority = 0.5; } } #ifdef WITH_XSLT_DEBUG_PATTERN xsltGenericDebug(xsltGenericDebugContext, "xsltCompilePattern : parsed %s, default priority %f\n", element->pattern, element->priority); #endif if (pattern[end] == '|') end++; current = end; } if (end == 0) { xsltTransformError(NULL, style, node, "xsltCompilePattern : NULL pattern\n"); if (style != NULL) style->errors++; goto error; } xsltFreeParserContext(ctxt); return(first); error: if (ctxt != NULL) xsltFreeParserContext(ctxt); if (first != NULL) xsltFreeCompMatchList(first); return(NULL); }
184,611
5,555
121486337326007709949705492814049984707
null
null
null
Chrome
58ffd25567098d8ce9443b7c977382929d163b3d
1
static void setPathFromConvexPoints(SkPath* path, size_t numPoints, const FloatPoint* points) { path->incReserve(numPoints); path->moveTo(WebCoreFloatToSkScalar(points[0].x()), WebCoreFloatToSkScalar(points[0].y())); for (size_t i = 1; i < numPoints; ++i) { path->lineTo(WebCoreFloatToSkScalar(points[i].x()), WebCoreFloatToSkScalar(points[i].y())); } path->setIsConvex(true); }
CWE-19
184,619
5,561
240318301613997723540746206540244318048
null
null
null
Chrome
d82b03d21f7e581f9206ef1fec4959ae7b06b8eb
1
xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; int buffer_size = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; int nbchars = 0; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size * sizeof(xmlChar)); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars > buffer_size - i - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if (ent != NULL) { if (ent->content == NULL) { xmlLoadEntityContent(ctxt, ent); } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); }
CWE-119
184,668
5,602
189668059679113703003442905361866296097
null
null
null