instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaStreamDispatcherHost::DoOpenDevice( int32_t page_request_id, const std::string& device_id, MediaStreamType type, OpenDeviceCallback callback, MediaDeviceSaltAndOrigin salt_and_origin) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!MediaStreamManager::IsOriginAllowed(render_process_id_, salt_and_origin.origin)) { std::move(callback).Run(false /* success */, std::string(), MediaStreamDevice()); return; } media_stream_manager_->OpenDevice( render_process_id_, render_frame_id_, page_request_id, device_id, type, std::move(salt_and_origin), std::move(callback), base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped, weak_factory_.GetWeakPtr())); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
void MediaStreamDispatcherHost::DoOpenDevice( int32_t page_request_id, const std::string& device_id, MediaStreamType type, OpenDeviceCallback callback, MediaDeviceSaltAndOrigin salt_and_origin) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!MediaStreamManager::IsOriginAllowed(render_process_id_, salt_and_origin.origin)) { std::move(callback).Run(false /* success */, std::string(), MediaStreamDevice()); return; } media_stream_manager_->OpenDevice( render_process_id_, render_frame_id_, page_request_id, requester_id_, device_id, type, std::move(salt_and_origin), std::move(callback), base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped, weak_factory_.GetWeakPtr())); }
173,095
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cfm_print(netdissect_options *ndo, register const u_char *pptr, register u_int length) { const struct cfm_common_header_t *cfm_common_header; const struct cfm_tlv_header_t *cfm_tlv_header; const uint8_t *tptr, *tlv_ptr; const uint8_t *namesp; u_int names_data_remaining; uint8_t md_nameformat, md_namelength; const uint8_t *md_name; uint8_t ma_nameformat, ma_namelength; const uint8_t *ma_name; u_int hexdump, tlen, cfm_tlv_len, cfm_tlv_type, ccm_interval; union { const struct cfm_ccm_t *cfm_ccm; const struct cfm_lbm_t *cfm_lbm; const struct cfm_ltm_t *cfm_ltm; const struct cfm_ltr_t *cfm_ltr; } msg_ptr; tptr=pptr; cfm_common_header = (const struct cfm_common_header_t *)pptr; if (length < sizeof(*cfm_common_header)) goto tooshort; ND_TCHECK(*cfm_common_header); /* * Sanity checking of the header. */ if (CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version) != CFM_VERSION) { ND_PRINT((ndo, "CFMv%u not supported, length %u", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), length)); return; } ND_PRINT((ndo, "CFMv%u %s, MD Level %u, length %u", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), tok2str(cfm_opcode_values, "unknown (%u)", cfm_common_header->opcode), CFM_EXTRACT_MD_LEVEL(cfm_common_header->mdlevel_version), length)); /* * In non-verbose mode just print the opcode and md-level. */ if (ndo->ndo_vflag < 1) { return; } ND_PRINT((ndo, "\n\tFirst TLV offset %u", cfm_common_header->first_tlv_offset)); tptr += sizeof(const struct cfm_common_header_t); tlen = length - sizeof(struct cfm_common_header_t); /* * Sanity check the first TLV offset. */ if (cfm_common_header->first_tlv_offset > tlen) { ND_PRINT((ndo, " (too large, must be <= %u)", tlen)); return; } switch (cfm_common_header->opcode) { case CFM_OPCODE_CCM: msg_ptr.cfm_ccm = (const struct cfm_ccm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ccm)) { ND_PRINT((ndo, " (too small 1, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ccm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ccm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ccm); ccm_interval = CFM_EXTRACT_CCM_INTERVAL(cfm_common_header->flags); ND_PRINT((ndo, ", Flags [CCM Interval %u%s]", ccm_interval, cfm_common_header->flags & CFM_CCM_RDI_FLAG ? ", RDI" : "")); /* * Resolve the CCM interval field. */ if (ccm_interval) { ND_PRINT((ndo, "\n\t CCM Interval %.3fs" ", min CCM Lifetime %.3fs, max CCM Lifetime %.3fs", ccm_interval_base[ccm_interval], ccm_interval_base[ccm_interval] * CCM_INTERVAL_MIN_MULTIPLIER, ccm_interval_base[ccm_interval] * CCM_INTERVAL_MAX_MULTIPLIER)); } ND_PRINT((ndo, "\n\t Sequence Number 0x%08x, MA-End-Point-ID 0x%04x", EXTRACT_32BITS(msg_ptr.cfm_ccm->sequence), EXTRACT_16BITS(msg_ptr.cfm_ccm->ma_epi))); namesp = msg_ptr.cfm_ccm->names; names_data_remaining = sizeof(msg_ptr.cfm_ccm->names); /* * Resolve the MD fields. */ md_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ if (md_nameformat != CFM_CCM_MD_FORMAT_NONE) { md_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is !=0 */ ND_PRINT((ndo, "\n\t MD Name Format %s (%u), MD Name length %u", tok2str(cfm_md_nameformat_values, "Unknown", md_nameformat), md_nameformat, md_namelength)); /* * -3 for the MA short name format and length and one byte * of MA short name. */ if (md_namelength > names_data_remaining - 3) { ND_PRINT((ndo, " (too large, must be <= %u)", names_data_remaining - 2)); return; } md_name = namesp; ND_PRINT((ndo, "\n\t MD Name: ")); switch (md_nameformat) { case CFM_CCM_MD_FORMAT_DNS: case CFM_CCM_MD_FORMAT_CHAR: safeputs(ndo, md_name, md_namelength); break; case CFM_CCM_MD_FORMAT_MAC: if (md_namelength == 6) { ND_PRINT((ndo, "\n\t MAC %s", etheraddr_string(ndo, md_name))); } else { ND_PRINT((ndo, "\n\t MAC (length invalid)")); } break; /* FIXME add printers for those MD formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: default: print_unknown_data(ndo, md_name, "\n\t ", md_namelength); } namesp += md_namelength; names_data_remaining -= md_namelength; } else { ND_PRINT((ndo, "\n\t MD Name Format %s (%u)", tok2str(cfm_md_nameformat_values, "Unknown", md_nameformat), md_nameformat)); } /* * Resolve the MA fields. */ ma_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ma_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ND_PRINT((ndo, "\n\t MA Name-Format %s (%u), MA name length %u", tok2str(cfm_ma_nameformat_values, "Unknown", ma_nameformat), ma_nameformat, ma_namelength)); if (ma_namelength > names_data_remaining) { ND_PRINT((ndo, " (too large, must be <= %u)", names_data_remaining)); return; } ma_name = namesp; ND_PRINT((ndo, "\n\t MA Name: ")); switch (ma_nameformat) { case CFM_CCM_MA_FORMAT_CHAR: safeputs(ndo, ma_name, ma_namelength); break; /* FIXME add printers for those MA formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: case CFM_CCM_MA_FORMAT_VID: case CFM_CCM_MA_FORMAT_INT: case CFM_CCM_MA_FORMAT_VPN: default: print_unknown_data(ndo, ma_name, "\n\t ", ma_namelength); } break; case CFM_OPCODE_LTM: msg_ptr.cfm_ltm = (const struct cfm_ltm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltm)) { ND_PRINT((ndo, " (too small 4, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ltm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltm); ND_PRINT((ndo, ", Flags [%s]", bittok2str(cfm_ltm_flag_values, "none", cfm_common_header->flags))); ND_PRINT((ndo, "\n\t Transaction-ID 0x%08x, ttl %u", EXTRACT_32BITS(msg_ptr.cfm_ltm->transaction_id), msg_ptr.cfm_ltm->ttl)); ND_PRINT((ndo, "\n\t Original-MAC %s, Target-MAC %s", etheraddr_string(ndo, msg_ptr.cfm_ltm->original_mac), etheraddr_string(ndo, msg_ptr.cfm_ltm->target_mac))); break; case CFM_OPCODE_LTR: msg_ptr.cfm_ltr = (const struct cfm_ltr_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltr)) { ND_PRINT((ndo, " (too small 5, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ltr))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltr)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltr); ND_PRINT((ndo, ", Flags [%s]", bittok2str(cfm_ltr_flag_values, "none", cfm_common_header->flags))); ND_PRINT((ndo, "\n\t Transaction-ID 0x%08x, ttl %u", EXTRACT_32BITS(msg_ptr.cfm_ltr->transaction_id), msg_ptr.cfm_ltr->ttl)); ND_PRINT((ndo, "\n\t Replay-Action %s (%u)", tok2str(cfm_ltr_replay_action_values, "Unknown", msg_ptr.cfm_ltr->replay_action), msg_ptr.cfm_ltr->replay_action)); break; /* * No message decoder yet. * Hexdump everything up until the start of the TLVs */ case CFM_OPCODE_LBR: case CFM_OPCODE_LBM: default: print_unknown_data(ndo, tptr, "\n\t ", tlen - cfm_common_header->first_tlv_offset); break; } tptr += cfm_common_header->first_tlv_offset; tlen -= cfm_common_header->first_tlv_offset; while (tlen > 0) { cfm_tlv_header = (const struct cfm_tlv_header_t *)tptr; /* Enough to read the tlv type ? */ ND_TCHECK2(*tptr, 1); cfm_tlv_type=cfm_tlv_header->type; ND_PRINT((ndo, "\n\t%s TLV (0x%02x)", tok2str(cfm_tlv_values, "Unknown", cfm_tlv_type), cfm_tlv_type)); if (cfm_tlv_type == CFM_TLV_END) { /* Length is "Not present if the Type field is 0." */ return; } /* do we have the full tlv header ? */ if (tlen < sizeof(struct cfm_tlv_header_t)) goto tooshort; ND_TCHECK2(*tptr, sizeof(struct cfm_tlv_header_t)); cfm_tlv_len=EXTRACT_16BITS(&cfm_tlv_header->length); ND_PRINT((ndo, ", length %u", cfm_tlv_len)); tptr += sizeof(struct cfm_tlv_header_t); tlen -= sizeof(struct cfm_tlv_header_t); tlv_ptr = tptr; /* do we have the full tlv ? */ if (tlen < cfm_tlv_len) goto tooshort; ND_TCHECK2(*tptr, cfm_tlv_len); hexdump = FALSE; switch(cfm_tlv_type) { case CFM_TLV_PORT_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); return; } ND_PRINT((ndo, ", Status: %s (%u)", tok2str(cfm_tlv_port_status_values, "Unknown", *tptr), *tptr)); break; case CFM_TLV_INTERFACE_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); return; } ND_PRINT((ndo, ", Status: %s (%u)", tok2str(cfm_tlv_interface_status_values, "Unknown", *tptr), *tptr)); break; case CFM_TLV_PRIVATE: if (cfm_tlv_len < 4) { ND_PRINT((ndo, " (too short, must be >= 4)")); return; } ND_PRINT((ndo, ", Vendor: %s (%u), Sub-Type %u", tok2str(oui_values,"Unknown", EXTRACT_24BITS(tptr)), EXTRACT_24BITS(tptr), *(tptr + 3))); hexdump = TRUE; break; case CFM_TLV_SENDER_ID: { u_int chassis_id_type, chassis_id_length; u_int mgmt_addr_length; if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); return; } /* * Get the Chassis ID length and check it. */ chassis_id_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (chassis_id_length) { if (cfm_tlv_len < 1) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } chassis_id_type = *tptr; cfm_tlv_len--; ND_PRINT((ndo, "\n\t Chassis-ID Type %s (%u), Chassis-ID length %u", tok2str(cfm_tlv_senderid_chassisid_values, "Unknown", chassis_id_type), chassis_id_type, chassis_id_length)); if (cfm_tlv_len < chassis_id_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } switch (chassis_id_type) { case CFM_CHASSIS_ID_MAC_ADDRESS: ND_PRINT((ndo, "\n\t MAC %s", etheraddr_string(ndo, tptr + 1))); break; case CFM_CHASSIS_ID_NETWORK_ADDRESS: hexdump |= cfm_network_addr_print(ndo, tptr); break; case CFM_CHASSIS_ID_INTERFACE_NAME: /* fall through */ case CFM_CHASSIS_ID_INTERFACE_ALIAS: case CFM_CHASSIS_ID_LOCAL: case CFM_CHASSIS_ID_CHASSIS_COMPONENT: case CFM_CHASSIS_ID_PORT_COMPONENT: safeputs(ndo, tptr + 1, chassis_id_length); break; default: hexdump = TRUE; break; } cfm_tlv_len -= chassis_id_length; tptr += 1 + chassis_id_length; tlen -= 1 + chassis_id_length; } /* * Check if there is a Management Address. */ if (cfm_tlv_len == 0) { /* No, there isn't; we're done. */ return; } mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (mgmt_addr_length) { if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is an OID; print it as such. */ tptr += mgmt_addr_length; tlen -= mgmt_addr_length; if (cfm_tlv_len < 1) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (mgmt_addr_length) { if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is a TransportDomain; print it as such. */ tptr += mgmt_addr_length; tlen -= mgmt_addr_length; } } break; } /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case CFM_TLV_DATA: case CFM_TLV_REPLY_INGRESS: case CFM_TLV_REPLY_EGRESS: default: hexdump = TRUE; break; } /* do we want to see an additional hexdump ? */ if (hexdump || ndo->ndo_vflag > 1) print_unknown_data(ndo, tlv_ptr, "\n\t ", cfm_tlv_len); tptr+=cfm_tlv_len; tlen-=cfm_tlv_len; } return; tooshort: ND_PRINT((ndo, "\n\t\t packet is too short")); return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); } Commit Message: CVE-2017-13052/CFM: refine decoding of the Sender ID TLV In cfm_network_addr_print() add a length argument and use it to validate the input buffer. In cfm_print() add a length check for MAC address chassis ID. Supply cfm_network_addr_print() with the length of its buffer and a correct pointer to the buffer (it was off-by-one before). Change some error handling blocks to skip to the next TLV in the current PDU rather than to stop decoding the PDU. Print the management domain and address contents, although in hex only so far. Add some comments to clarify the code flow and to tell exact sections in IEEE standard documents. Add new error messages and make some existing messages more specific. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
cfm_print(netdissect_options *ndo, register const u_char *pptr, register u_int length) { const struct cfm_common_header_t *cfm_common_header; const struct cfm_tlv_header_t *cfm_tlv_header; const uint8_t *tptr, *tlv_ptr; const uint8_t *namesp; u_int names_data_remaining; uint8_t md_nameformat, md_namelength; const uint8_t *md_name; uint8_t ma_nameformat, ma_namelength; const uint8_t *ma_name; u_int hexdump, tlen, cfm_tlv_len, cfm_tlv_type, ccm_interval; union { const struct cfm_ccm_t *cfm_ccm; const struct cfm_lbm_t *cfm_lbm; const struct cfm_ltm_t *cfm_ltm; const struct cfm_ltr_t *cfm_ltr; } msg_ptr; tptr=pptr; cfm_common_header = (const struct cfm_common_header_t *)pptr; if (length < sizeof(*cfm_common_header)) goto tooshort; ND_TCHECK(*cfm_common_header); /* * Sanity checking of the header. */ if (CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version) != CFM_VERSION) { ND_PRINT((ndo, "CFMv%u not supported, length %u", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), length)); return; } ND_PRINT((ndo, "CFMv%u %s, MD Level %u, length %u", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), tok2str(cfm_opcode_values, "unknown (%u)", cfm_common_header->opcode), CFM_EXTRACT_MD_LEVEL(cfm_common_header->mdlevel_version), length)); /* * In non-verbose mode just print the opcode and md-level. */ if (ndo->ndo_vflag < 1) { return; } ND_PRINT((ndo, "\n\tFirst TLV offset %u", cfm_common_header->first_tlv_offset)); tptr += sizeof(const struct cfm_common_header_t); tlen = length - sizeof(struct cfm_common_header_t); /* * Sanity check the first TLV offset. */ if (cfm_common_header->first_tlv_offset > tlen) { ND_PRINT((ndo, " (too large, must be <= %u)", tlen)); return; } switch (cfm_common_header->opcode) { case CFM_OPCODE_CCM: msg_ptr.cfm_ccm = (const struct cfm_ccm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ccm)) { ND_PRINT((ndo, " (too small 1, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ccm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ccm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ccm); ccm_interval = CFM_EXTRACT_CCM_INTERVAL(cfm_common_header->flags); ND_PRINT((ndo, ", Flags [CCM Interval %u%s]", ccm_interval, cfm_common_header->flags & CFM_CCM_RDI_FLAG ? ", RDI" : "")); /* * Resolve the CCM interval field. */ if (ccm_interval) { ND_PRINT((ndo, "\n\t CCM Interval %.3fs" ", min CCM Lifetime %.3fs, max CCM Lifetime %.3fs", ccm_interval_base[ccm_interval], ccm_interval_base[ccm_interval] * CCM_INTERVAL_MIN_MULTIPLIER, ccm_interval_base[ccm_interval] * CCM_INTERVAL_MAX_MULTIPLIER)); } ND_PRINT((ndo, "\n\t Sequence Number 0x%08x, MA-End-Point-ID 0x%04x", EXTRACT_32BITS(msg_ptr.cfm_ccm->sequence), EXTRACT_16BITS(msg_ptr.cfm_ccm->ma_epi))); namesp = msg_ptr.cfm_ccm->names; names_data_remaining = sizeof(msg_ptr.cfm_ccm->names); /* * Resolve the MD fields. */ md_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ if (md_nameformat != CFM_CCM_MD_FORMAT_NONE) { md_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is !=0 */ ND_PRINT((ndo, "\n\t MD Name Format %s (%u), MD Name length %u", tok2str(cfm_md_nameformat_values, "Unknown", md_nameformat), md_nameformat, md_namelength)); /* * -3 for the MA short name format and length and one byte * of MA short name. */ if (md_namelength > names_data_remaining - 3) { ND_PRINT((ndo, " (too large, must be <= %u)", names_data_remaining - 2)); return; } md_name = namesp; ND_PRINT((ndo, "\n\t MD Name: ")); switch (md_nameformat) { case CFM_CCM_MD_FORMAT_DNS: case CFM_CCM_MD_FORMAT_CHAR: safeputs(ndo, md_name, md_namelength); break; case CFM_CCM_MD_FORMAT_MAC: if (md_namelength == 6) { ND_PRINT((ndo, "\n\t MAC %s", etheraddr_string(ndo, md_name))); } else { ND_PRINT((ndo, "\n\t MAC (length invalid)")); } break; /* FIXME add printers for those MD formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: default: print_unknown_data(ndo, md_name, "\n\t ", md_namelength); } namesp += md_namelength; names_data_remaining -= md_namelength; } else { ND_PRINT((ndo, "\n\t MD Name Format %s (%u)", tok2str(cfm_md_nameformat_values, "Unknown", md_nameformat), md_nameformat)); } /* * Resolve the MA fields. */ ma_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ma_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ND_PRINT((ndo, "\n\t MA Name-Format %s (%u), MA name length %u", tok2str(cfm_ma_nameformat_values, "Unknown", ma_nameformat), ma_nameformat, ma_namelength)); if (ma_namelength > names_data_remaining) { ND_PRINT((ndo, " (too large, must be <= %u)", names_data_remaining)); return; } ma_name = namesp; ND_PRINT((ndo, "\n\t MA Name: ")); switch (ma_nameformat) { case CFM_CCM_MA_FORMAT_CHAR: safeputs(ndo, ma_name, ma_namelength); break; /* FIXME add printers for those MA formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: case CFM_CCM_MA_FORMAT_VID: case CFM_CCM_MA_FORMAT_INT: case CFM_CCM_MA_FORMAT_VPN: default: print_unknown_data(ndo, ma_name, "\n\t ", ma_namelength); } break; case CFM_OPCODE_LTM: msg_ptr.cfm_ltm = (const struct cfm_ltm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltm)) { ND_PRINT((ndo, " (too small 4, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ltm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltm); ND_PRINT((ndo, ", Flags [%s]", bittok2str(cfm_ltm_flag_values, "none", cfm_common_header->flags))); ND_PRINT((ndo, "\n\t Transaction-ID 0x%08x, ttl %u", EXTRACT_32BITS(msg_ptr.cfm_ltm->transaction_id), msg_ptr.cfm_ltm->ttl)); ND_PRINT((ndo, "\n\t Original-MAC %s, Target-MAC %s", etheraddr_string(ndo, msg_ptr.cfm_ltm->original_mac), etheraddr_string(ndo, msg_ptr.cfm_ltm->target_mac))); break; case CFM_OPCODE_LTR: msg_ptr.cfm_ltr = (const struct cfm_ltr_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltr)) { ND_PRINT((ndo, " (too small 5, must be >= %lu)", (unsigned long) sizeof(*msg_ptr.cfm_ltr))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltr)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltr); ND_PRINT((ndo, ", Flags [%s]", bittok2str(cfm_ltr_flag_values, "none", cfm_common_header->flags))); ND_PRINT((ndo, "\n\t Transaction-ID 0x%08x, ttl %u", EXTRACT_32BITS(msg_ptr.cfm_ltr->transaction_id), msg_ptr.cfm_ltr->ttl)); ND_PRINT((ndo, "\n\t Replay-Action %s (%u)", tok2str(cfm_ltr_replay_action_values, "Unknown", msg_ptr.cfm_ltr->replay_action), msg_ptr.cfm_ltr->replay_action)); break; /* * No message decoder yet. * Hexdump everything up until the start of the TLVs */ case CFM_OPCODE_LBR: case CFM_OPCODE_LBM: default: print_unknown_data(ndo, tptr, "\n\t ", tlen - cfm_common_header->first_tlv_offset); break; } tptr += cfm_common_header->first_tlv_offset; tlen -= cfm_common_header->first_tlv_offset; while (tlen > 0) { cfm_tlv_header = (const struct cfm_tlv_header_t *)tptr; /* Enough to read the tlv type ? */ ND_TCHECK2(*tptr, 1); cfm_tlv_type=cfm_tlv_header->type; ND_PRINT((ndo, "\n\t%s TLV (0x%02x)", tok2str(cfm_tlv_values, "Unknown", cfm_tlv_type), cfm_tlv_type)); if (cfm_tlv_type == CFM_TLV_END) { /* Length is "Not present if the Type field is 0." */ return; } /* do we have the full tlv header ? */ if (tlen < sizeof(struct cfm_tlv_header_t)) goto tooshort; ND_TCHECK2(*tptr, sizeof(struct cfm_tlv_header_t)); cfm_tlv_len=EXTRACT_16BITS(&cfm_tlv_header->length); ND_PRINT((ndo, ", length %u", cfm_tlv_len)); tptr += sizeof(struct cfm_tlv_header_t); tlen -= sizeof(struct cfm_tlv_header_t); tlv_ptr = tptr; /* do we have the full tlv ? */ if (tlen < cfm_tlv_len) goto tooshort; ND_TCHECK2(*tptr, cfm_tlv_len); hexdump = FALSE; switch(cfm_tlv_type) { case CFM_TLV_PORT_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); return; } ND_PRINT((ndo, ", Status: %s (%u)", tok2str(cfm_tlv_port_status_values, "Unknown", *tptr), *tptr)); break; case CFM_TLV_INTERFACE_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); return; } ND_PRINT((ndo, ", Status: %s (%u)", tok2str(cfm_tlv_interface_status_values, "Unknown", *tptr), *tptr)); break; case CFM_TLV_PRIVATE: if (cfm_tlv_len < 4) { ND_PRINT((ndo, " (too short, must be >= 4)")); return; } ND_PRINT((ndo, ", Vendor: %s (%u), Sub-Type %u", tok2str(oui_values,"Unknown", EXTRACT_24BITS(tptr)), EXTRACT_24BITS(tptr), *(tptr + 3))); hexdump = TRUE; break; case CFM_TLV_SENDER_ID: { u_int chassis_id_type, chassis_id_length; u_int mgmt_addr_length; if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (too short, must be >= 1)")); goto next_tlv; } /* * Get the Chassis ID length and check it. * IEEE 802.1Q-2014 Section 21.5.3.1 */ chassis_id_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (chassis_id_length) { /* * IEEE 802.1Q-2014 Section 21.5.3.2: Chassis ID Subtype, references * IEEE 802.1AB-2005 Section 9.5.2.2, subsequently * IEEE 802.1AB-2016 Section 8.5.2.2: chassis ID subtype */ if (cfm_tlv_len < 1) { ND_PRINT((ndo, "\n\t (TLV too short)")); goto next_tlv; } chassis_id_type = *tptr; cfm_tlv_len--; ND_PRINT((ndo, "\n\t Chassis-ID Type %s (%u), Chassis-ID length %u", tok2str(cfm_tlv_senderid_chassisid_values, "Unknown", chassis_id_type), chassis_id_type, chassis_id_length)); if (cfm_tlv_len < chassis_id_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); goto next_tlv; } /* IEEE 802.1Q-2014 Section 21.5.3.3: Chassis ID */ switch (chassis_id_type) { case CFM_CHASSIS_ID_MAC_ADDRESS: if (chassis_id_length != ETHER_ADDR_LEN) { ND_PRINT((ndo, " (invalid MAC address length)")); hexdump = TRUE; break; } ND_PRINT((ndo, "\n\t MAC %s", etheraddr_string(ndo, tptr + 1))); break; case CFM_CHASSIS_ID_NETWORK_ADDRESS: hexdump |= cfm_network_addr_print(ndo, tptr + 1, chassis_id_length); break; case CFM_CHASSIS_ID_INTERFACE_NAME: /* fall through */ case CFM_CHASSIS_ID_INTERFACE_ALIAS: case CFM_CHASSIS_ID_LOCAL: case CFM_CHASSIS_ID_CHASSIS_COMPONENT: case CFM_CHASSIS_ID_PORT_COMPONENT: safeputs(ndo, tptr + 1, chassis_id_length); break; default: hexdump = TRUE; break; } cfm_tlv_len -= chassis_id_length; tptr += 1 + chassis_id_length; tlen -= 1 + chassis_id_length; } /* * Check if there is a Management Address. * IEEE 802.1Q-2014 Section 21.5.3.4: Management Address Domain Length * This and all subsequent fields are not present if the TLV length * allows only the above fields. */ if (cfm_tlv_len == 0) { /* No, there isn't; we're done. */ break; } /* Here mgmt_addr_length stands for the management domain length. */ mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; ND_PRINT((ndo, "\n\t Management Address Domain Length %u", mgmt_addr_length)); if (mgmt_addr_length) { /* IEEE 802.1Q-2014 Section 21.5.3.5: Management Address Domain */ if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); goto next_tlv; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is an OID; print it as such. */ hex_print(ndo, "\n\t Management Address Domain: ", tptr, mgmt_addr_length); tptr += mgmt_addr_length; tlen -= mgmt_addr_length; /* * IEEE 802.1Q-2014 Section 21.5.3.6: Management Address Length * This field is present if Management Address Domain Length is not 0. */ if (cfm_tlv_len < 1) { ND_PRINT((ndo, " (Management Address Length is missing)")); hexdump = TRUE; break; } /* Here mgmt_addr_length stands for the management address length. */ mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; ND_PRINT((ndo, "\n\t Management Address Length %u", mgmt_addr_length)); if (mgmt_addr_length) { /* IEEE 802.1Q-2014 Section 21.5.3.7: Management Address */ if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, "\n\t (TLV too short)")); return; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is a TransportDomain; print it as such. */ hex_print(ndo, "\n\t Management Address: ", tptr, mgmt_addr_length); tptr += mgmt_addr_length; tlen -= mgmt_addr_length; } } break; } /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case CFM_TLV_DATA: case CFM_TLV_REPLY_INGRESS: case CFM_TLV_REPLY_EGRESS: default: hexdump = TRUE; break; } /* do we want to see an additional hexdump ? */ if (hexdump || ndo->ndo_vflag > 1) print_unknown_data(ndo, tlv_ptr, "\n\t ", cfm_tlv_len); next_tlv: tptr+=cfm_tlv_len; tlen-=cfm_tlv_len; } return; tooshort: ND_PRINT((ndo, "\n\t\t packet is too short")); return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); }
167,822
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::VaapiVP8Accelerator( VaapiVideoDecodeAccelerator* vaapi_dec, VaapiWrapper* vaapi_wrapper) : vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) { DCHECK(vaapi_wrapper_); DCHECK(vaapi_dec_); } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362
VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::VaapiVP8Accelerator( VaapiVideoDecodeAccelerator* vaapi_dec, VaapiWrapper* vaapi_wrapper) : vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) { DCHECK(vaapi_wrapper_); DCHECK(vaapi_dec_); DETACH_FROM_SEQUENCE(sequence_checker_); }
172,816
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: mcs_recv_connect_response(STREAM mcs_data) { UNUSED(mcs_data); uint8 result; int length; STREAM s; RD_BOOL is_fastpath; uint8 fastpath_hdr; logger(Protocol, Debug, "%s()", __func__); s = iso_recv(&is_fastpath, &fastpath_hdr); if (s == NULL) return False; ber_parse_header(s, MCS_CONNECT_RESPONSE, &length); ber_parse_header(s, BER_TAG_RESULT, &length); in_uint8(s, result); if (result != 0) { logger(Protocol, Error, "mcs_recv_connect_response(), result=%d", result); return False; } ber_parse_header(s, BER_TAG_INTEGER, &length); in_uint8s(s, length); /* connect id */ mcs_parse_domain_params(s); ber_parse_header(s, BER_TAG_OCTET_STRING, &length); sec_process_mcs_data(s); /* if (length > mcs_data->size) { logger(Protocol, Error, "mcs_recv_connect_response(), expected length=%d, got %d",length, mcs_data->size); length = mcs_data->size; } in_uint8a(s, mcs_data->data, length); mcs_data->p = mcs_data->data; mcs_data->end = mcs_data->data + length; */ return s_check_end(s); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
mcs_recv_connect_response(STREAM mcs_data) { UNUSED(mcs_data); uint8 result; uint32 length; STREAM s; struct stream packet; RD_BOOL is_fastpath; uint8 fastpath_hdr; logger(Protocol, Debug, "%s()", __func__); s = iso_recv(&is_fastpath, &fastpath_hdr); if (s == NULL) return False; packet = *s; ber_parse_header(s, MCS_CONNECT_RESPONSE, &length); ber_parse_header(s, BER_TAG_RESULT, &length); in_uint8(s, result); if (result != 0) { logger(Protocol, Error, "mcs_recv_connect_response(), result=%d", result); return False; } ber_parse_header(s, BER_TAG_INTEGER, &length); in_uint8s(s, length); /* connect id */ if (!s_check_rem(s, length)) { rdp_protocol_error("mcs_recv_connect_response(), consume connect id from stream would overrun", &packet); } mcs_parse_domain_params(s); ber_parse_header(s, BER_TAG_OCTET_STRING, &length); sec_process_mcs_data(s); /* if (length > mcs_data->size) { logger(Protocol, Error, "mcs_recv_connect_response(), expected length=%d, got %d",length, mcs_data->size); length = mcs_data->size; } in_uint8a(s, mcs_data->data, length); mcs_data->p = mcs_data->data; mcs_data->end = mcs_data->data + length; */ return s_check_end(s); }
169,800
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MaybeChangeCurrentKeyboardLayout(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value)) { ChangeCurrentInputMethodFromId(value.string_list_value[0]); } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void MaybeChangeCurrentKeyboardLayout(const std::string& section, void MaybeChangeCurrentKeyboardLayout( const std::string& section, const std::string& config_name, const input_method::ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value)) { ChangeCurrentInputMethodFromId(value.string_list_value[0]); } }
170,498
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __init xfrm6_tunnel_init(void) { int rv; rv = xfrm_register_type(&xfrm6_tunnel_type, AF_INET6); if (rv < 0) goto err; rv = xfrm6_tunnel_register(&xfrm6_tunnel_handler, AF_INET6); if (rv < 0) goto unreg; rv = xfrm6_tunnel_register(&xfrm46_tunnel_handler, AF_INET); if (rv < 0) goto dereg6; rv = xfrm6_tunnel_spi_init(); if (rv < 0) goto dereg46; rv = register_pernet_subsys(&xfrm6_tunnel_net_ops); if (rv < 0) goto deregspi; return 0; deregspi: xfrm6_tunnel_spi_fini(); dereg46: xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET); dereg6: xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6); unreg: xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6); err: return rv; } Commit Message: tunnels: fix netns vs proto registration ordering Same stuff as in ip_gre patch: receive hook can be called before netns setup is done, oopsing in net_generic(). Signed-off-by: Alexey Dobriyan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static int __init xfrm6_tunnel_init(void) { int rv; xfrm6_tunnel_spi_kmem = kmem_cache_create("xfrm6_tunnel_spi", sizeof(struct xfrm6_tunnel_spi), 0, SLAB_HWCACHE_ALIGN, NULL); if (!xfrm6_tunnel_spi_kmem) return -ENOMEM; rv = register_pernet_subsys(&xfrm6_tunnel_net_ops); if (rv < 0) goto out_pernet; rv = xfrm_register_type(&xfrm6_tunnel_type, AF_INET6); if (rv < 0) goto out_type; rv = xfrm6_tunnel_register(&xfrm6_tunnel_handler, AF_INET6); if (rv < 0) goto out_xfrm6; rv = xfrm6_tunnel_register(&xfrm46_tunnel_handler, AF_INET); if (rv < 0) goto out_xfrm46; return 0; out_xfrm46: xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6); out_xfrm6: xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6); out_type: unregister_pernet_subsys(&xfrm6_tunnel_net_ops); out_pernet: kmem_cache_destroy(xfrm6_tunnel_spi_kmem); return rv; }
165,880
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int send_full_color_rect(VncState *vs, int x, int y, int w, int h) { int stream = 0; ssize_t bytes; #ifdef CONFIG_VNC_PNG if (tight_can_send_png_rect(vs, w, h)) { return send_png_rect(vs, x, y, w, h, NULL); } #endif tight_pack24(vs, vs->tight.tight.buffer, w * h, &vs->tight.tight.offset); bytes = 3; } else { bytes = vs->clientds.pf.bytes_per_pixel; } Commit Message: CWE ID: CWE-125
static int send_full_color_rect(VncState *vs, int x, int y, int w, int h) { int stream = 0; ssize_t bytes; #ifdef CONFIG_VNC_PNG if (tight_can_send_png_rect(vs, w, h)) { return send_png_rect(vs, x, y, w, h, NULL); } #endif tight_pack24(vs, vs->tight.tight.buffer, w * h, &vs->tight.tight.offset); bytes = 3; } else { bytes = vs->client_pf.bytes_per_pixel; }
165,461
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gboolean lxterminal_socket_initialize(LXTermWindow * lxtermwin, gint argc, gchar * * argv) { /* Normally, LXTerminal uses one process to control all of its windows. * The first process to start will create a Unix domain socket in /tmp. * It will then bind and listen on this socket. * The subsequent processes will connect to the controller that owns the Unix domain socket. * They will pass their command line over the socket and exit. * * If for any reason both the connect and bind fail, we will fall back to having that * process be standalone; it will not be either the controller or a user of the controller. * This behavior was introduced in response to a problem report (2973537). * * This function returns TRUE if this process should keep running and FALSE if it should exit. */ /* Formulate the path for the Unix domain socket. */ gchar * socket_path = g_strdup_printf("/tmp/.lxterminal-socket%s-%s", gdk_display_get_name(gdk_display_get_default()), g_get_user_name()); /* Create socket. */ int fd = socket(PF_UNIX, SOCK_STREAM, 0); { g_warning("Socket create failed: %s\n", g_strerror(errno)); g_free(socket_path); return TRUE; } /* Initialize socket address for Unix domain socket. */ struct sockaddr_un sock_addr; memset(&sock_addr, 0, sizeof(sock_addr)); sock_addr.sun_family = AF_UNIX; snprintf(sock_addr.sun_path, sizeof(sock_addr.sun_path), "%s", socket_path); /* Try to connect to an existing LXTerminal process. */ if (connect(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0) { /* Connect failed. We are the controller, unless something fails. */ unlink(socket_path); g_free(socket_path); /* Bind to socket. */ if (bind(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0) { g_warning("Bind on socket failed: %s\n", g_strerror(errno)); close(fd); return TRUE; } /* Listen on socket. */ if (listen(fd, 5) < 0) { g_warning("Listen on socket failed: %s\n", g_strerror(errno)); close(fd); return TRUE; } /* Create a glib I/O channel. */ GIOChannel * gio = g_io_channel_unix_new(fd); if (gio == NULL) { g_warning("Cannot create GIOChannel\n"); close(fd); return TRUE; } /* Set up GIOChannel. */ g_io_channel_set_encoding(gio, NULL, NULL); g_io_channel_set_buffered(gio, FALSE); g_io_channel_set_close_on_unref(gio, TRUE); /* Add I/O channel to the main event loop. */ if ( ! g_io_add_watch(gio, G_IO_IN | G_IO_HUP, (GIOFunc) lxterminal_socket_accept_client, lxtermwin)) { g_warning("Cannot add watch on GIOChannel\n"); close(fd); g_io_channel_unref(gio); return TRUE; } /* Channel will automatically shut down when the watch returns FALSE. */ g_io_channel_set_close_on_unref(gio, TRUE); g_io_channel_unref(gio); return TRUE; } else { g_free(socket_path); /* Create a glib I/O channel. */ GIOChannel * gio = g_io_channel_unix_new(fd); g_io_channel_set_encoding(gio, NULL, NULL); /* Push current dir in case it is needed later */ gchar * cur_dir = g_get_current_dir(); g_io_channel_write_chars(gio, cur_dir, -1, NULL, NULL); /* Use "" as a pointer to '\0' since g_io_channel_write_chars() won't accept NULL */ g_io_channel_write_chars(gio, "", 1, NULL, NULL); g_free(cur_dir); /* push all of argv. */ gint i; for (i = 0; i < argc; i ++) { g_io_channel_write_chars(gio, argv[i], -1, NULL, NULL); g_io_channel_write_chars(gio, "", 1, NULL, NULL); } g_io_channel_flush(gio, NULL); g_io_channel_unref(gio); return FALSE; } } Commit Message: CWE ID: CWE-284
gboolean lxterminal_socket_initialize(LXTermWindow * lxtermwin, gint argc, gchar * * argv) { /* Normally, LXTerminal uses one process to control all of its windows. * The first process to start will create a Unix domain socket in /tmp. * It will then bind and listen on this socket. * The subsequent processes will connect to the controller that owns the Unix domain socket. * They will pass their command line over the socket and exit. * * If for any reason both the connect and bind fail, we will fall back to having that * process be standalone; it will not be either the controller or a user of the controller. * This behavior was introduced in response to a problem report (2973537). * * This function returns TRUE if this process should keep running and FALSE if it should exit. */ /* Formulate the path for the Unix domain socket. */ gchar * socket_path = g_strdup_printf("%s/.lxterminal-socket-%s", g_get_user_runtime_dir(), gdk_display_get_name(gdk_display_get_default())); printf("%s\n", socket_path); /* Create socket. */ int fd = socket(PF_UNIX, SOCK_STREAM, 0); { g_warning("Socket create failed: %s\n", g_strerror(errno)); g_free(socket_path); return TRUE; } /* Initialize socket address for Unix domain socket. */ struct sockaddr_un sock_addr; memset(&sock_addr, 0, sizeof(sock_addr)); sock_addr.sun_family = AF_UNIX; snprintf(sock_addr.sun_path, sizeof(sock_addr.sun_path), "%s", socket_path); /* Try to connect to an existing LXTerminal process. */ if (connect(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0) { /* Connect failed. We are the controller, unless something fails. */ unlink(socket_path); g_free(socket_path); /* Bind to socket. */ if (bind(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0) { g_warning("Bind on socket failed: %s\n", g_strerror(errno)); close(fd); return TRUE; } /* Listen on socket. */ if (listen(fd, 5) < 0) { g_warning("Listen on socket failed: %s\n", g_strerror(errno)); close(fd); return TRUE; } /* Create a glib I/O channel. */ GIOChannel * gio = g_io_channel_unix_new(fd); if (gio == NULL) { g_warning("Cannot create GIOChannel\n"); close(fd); return TRUE; } /* Set up GIOChannel. */ g_io_channel_set_encoding(gio, NULL, NULL); g_io_channel_set_buffered(gio, FALSE); g_io_channel_set_close_on_unref(gio, TRUE); /* Add I/O channel to the main event loop. */ if ( ! g_io_add_watch(gio, G_IO_IN | G_IO_HUP, (GIOFunc) lxterminal_socket_accept_client, lxtermwin)) { g_warning("Cannot add watch on GIOChannel\n"); close(fd); g_io_channel_unref(gio); return TRUE; } /* Channel will automatically shut down when the watch returns FALSE. */ g_io_channel_set_close_on_unref(gio, TRUE); g_io_channel_unref(gio); return TRUE; } else { g_free(socket_path); /* Create a glib I/O channel. */ GIOChannel * gio = g_io_channel_unix_new(fd); g_io_channel_set_encoding(gio, NULL, NULL); /* Push current dir in case it is needed later */ gchar * cur_dir = g_get_current_dir(); g_io_channel_write_chars(gio, cur_dir, -1, NULL, NULL); /* Use "" as a pointer to '\0' since g_io_channel_write_chars() won't accept NULL */ g_io_channel_write_chars(gio, "", 1, NULL, NULL); g_free(cur_dir); /* push all of argv. */ gint i; for (i = 0; i < argc; i ++) { g_io_channel_write_chars(gio, argv[i], -1, NULL, NULL); g_io_channel_write_chars(gio, "", 1, NULL, NULL); } g_io_channel_flush(gio, NULL); g_io_channel_unref(gio); return FALSE; } }
165,232
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int hmac_create(struct crypto_template *tmpl, struct rtattr **tb) { struct shash_instance *inst; struct crypto_alg *alg; struct shash_alg *salg; int err; int ds; int ss; err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_SHASH); if (err) return err; salg = shash_attr_alg(tb[1], 0, 0); if (IS_ERR(salg)) return PTR_ERR(salg); err = -EINVAL; ds = salg->digestsize; ss = salg->statesize; alg = &salg->base; if (ds > alg->cra_blocksize || ss < alg->cra_blocksize) goto out_put_alg; inst = shash_alloc_instance("hmac", alg); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; err = crypto_init_shash_spawn(shash_instance_ctx(inst), salg, shash_crypto_instance(inst)); if (err) goto out_free_inst; inst->alg.base.cra_priority = alg->cra_priority; inst->alg.base.cra_blocksize = alg->cra_blocksize; inst->alg.base.cra_alignmask = alg->cra_alignmask; ss = ALIGN(ss, alg->cra_alignmask + 1); inst->alg.digestsize = ds; inst->alg.statesize = ss; inst->alg.base.cra_ctxsize = sizeof(struct hmac_ctx) + ALIGN(ss * 2, crypto_tfm_ctx_alignment()); inst->alg.base.cra_init = hmac_init_tfm; inst->alg.base.cra_exit = hmac_exit_tfm; inst->alg.init = hmac_init; inst->alg.update = hmac_update; inst->alg.final = hmac_final; inst->alg.finup = hmac_finup; inst->alg.export = hmac_export; inst->alg.import = hmac_import; inst->alg.setkey = hmac_setkey; err = shash_register_instance(tmpl, inst); if (err) { out_free_inst: shash_free_instance(shash_crypto_instance(inst)); } out_put_alg: crypto_mod_put(alg); return err; } Commit Message: crypto: hmac - require that the underlying hash algorithm is unkeyed Because the HMAC template didn't check that its underlying hash algorithm is unkeyed, trying to use "hmac(hmac(sha3-512-generic))" through AF_ALG or through KEYCTL_DH_COMPUTE resulted in the inner HMAC being used without having been keyed, resulting in sha3_update() being called without sha3_init(), causing a stack buffer overflow. This is a very old bug, but it seems to have only started causing real problems when SHA-3 support was added (requires CONFIG_CRYPTO_SHA3) because the innermost hash's state is ->import()ed from a zeroed buffer, and it just so happens that other hash algorithms are fine with that, but SHA-3 is not. However, there could be arch or hardware-dependent hash algorithms also affected; I couldn't test everything. Fix the bug by introducing a function crypto_shash_alg_has_setkey() which tests whether a shash algorithm is keyed. Then update the HMAC template to require that its underlying hash algorithm is unkeyed. Here is a reproducer: #include <linux/if_alg.h> #include <sys/socket.h> int main() { int algfd; struct sockaddr_alg addr = { .salg_type = "hash", .salg_name = "hmac(hmac(sha3-512-generic))", }; char key[4096] = { 0 }; algfd = socket(AF_ALG, SOCK_SEQPACKET, 0); bind(algfd, (const struct sockaddr *)&addr, sizeof(addr)); setsockopt(algfd, SOL_ALG, ALG_SET_KEY, key, sizeof(key)); } Here was the KASAN report from syzbot: BUG: KASAN: stack-out-of-bounds in memcpy include/linux/string.h:341 [inline] BUG: KASAN: stack-out-of-bounds in sha3_update+0xdf/0x2e0 crypto/sha3_generic.c:161 Write of size 4096 at addr ffff8801cca07c40 by task syzkaller076574/3044 CPU: 1 PID: 3044 Comm: syzkaller076574 Not tainted 4.14.0-mm1+ #25 Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011 Call Trace: __dump_stack lib/dump_stack.c:17 [inline] dump_stack+0x194/0x257 lib/dump_stack.c:53 print_address_description+0x73/0x250 mm/kasan/report.c:252 kasan_report_error mm/kasan/report.c:351 [inline] kasan_report+0x25b/0x340 mm/kasan/report.c:409 check_memory_region_inline mm/kasan/kasan.c:260 [inline] check_memory_region+0x137/0x190 mm/kasan/kasan.c:267 memcpy+0x37/0x50 mm/kasan/kasan.c:303 memcpy include/linux/string.h:341 [inline] sha3_update+0xdf/0x2e0 crypto/sha3_generic.c:161 crypto_shash_update+0xcb/0x220 crypto/shash.c:109 shash_finup_unaligned+0x2a/0x60 crypto/shash.c:151 crypto_shash_finup+0xc4/0x120 crypto/shash.c:165 hmac_finup+0x182/0x330 crypto/hmac.c:152 crypto_shash_finup+0xc4/0x120 crypto/shash.c:165 shash_digest_unaligned+0x9e/0xd0 crypto/shash.c:172 crypto_shash_digest+0xc4/0x120 crypto/shash.c:186 hmac_setkey+0x36a/0x690 crypto/hmac.c:66 crypto_shash_setkey+0xad/0x190 crypto/shash.c:64 shash_async_setkey+0x47/0x60 crypto/shash.c:207 crypto_ahash_setkey+0xaf/0x180 crypto/ahash.c:200 hash_setkey+0x40/0x90 crypto/algif_hash.c:446 alg_setkey crypto/af_alg.c:221 [inline] alg_setsockopt+0x2a1/0x350 crypto/af_alg.c:254 SYSC_setsockopt net/socket.c:1851 [inline] SyS_setsockopt+0x189/0x360 net/socket.c:1830 entry_SYSCALL_64_fastpath+0x1f/0x96 Reported-by: syzbot <[email protected]> Cc: <[email protected]> Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-787
static int hmac_create(struct crypto_template *tmpl, struct rtattr **tb) { struct shash_instance *inst; struct crypto_alg *alg; struct shash_alg *salg; int err; int ds; int ss; err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_SHASH); if (err) return err; salg = shash_attr_alg(tb[1], 0, 0); if (IS_ERR(salg)) return PTR_ERR(salg); alg = &salg->base; /* The underlying hash algorithm must be unkeyed */ err = -EINVAL; if (crypto_shash_alg_has_setkey(salg)) goto out_put_alg; ds = salg->digestsize; ss = salg->statesize; if (ds > alg->cra_blocksize || ss < alg->cra_blocksize) goto out_put_alg; inst = shash_alloc_instance("hmac", alg); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; err = crypto_init_shash_spawn(shash_instance_ctx(inst), salg, shash_crypto_instance(inst)); if (err) goto out_free_inst; inst->alg.base.cra_priority = alg->cra_priority; inst->alg.base.cra_blocksize = alg->cra_blocksize; inst->alg.base.cra_alignmask = alg->cra_alignmask; ss = ALIGN(ss, alg->cra_alignmask + 1); inst->alg.digestsize = ds; inst->alg.statesize = ss; inst->alg.base.cra_ctxsize = sizeof(struct hmac_ctx) + ALIGN(ss * 2, crypto_tfm_ctx_alignment()); inst->alg.base.cra_init = hmac_init_tfm; inst->alg.base.cra_exit = hmac_exit_tfm; inst->alg.init = hmac_init; inst->alg.update = hmac_update; inst->alg.final = hmac_final; inst->alg.finup = hmac_finup; inst->alg.export = hmac_export; inst->alg.import = hmac_import; inst->alg.setkey = hmac_setkey; err = shash_register_instance(tmpl, inst); if (err) { out_free_inst: shash_free_instance(shash_crypto_instance(inst)); } out_put_alg: crypto_mod_put(alg); return err; }
167,649
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void StoreNewGroup() { PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_StoreNewGroup, base::Unretained(this))); group_ = new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId()); cache_ = new AppCache(storage(), storage()->NewCacheId()); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::EXPLICIT, 1, kDefaultEntrySize)); mock_quota_manager_proxy_->mock_manager_->async_ = true; storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate()); EXPECT_FALSE(delegate()->stored_group_success_); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
void StoreNewGroup() { PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_StoreNewGroup, base::Unretained(this))); group_ = new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId()); cache_ = new AppCache(storage(), storage()->NewCacheId()); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::MASTER, 1, kDefaultEntrySize, /*padding_size=*/0)); mock_quota_manager_proxy_->mock_manager_->async_ = true; storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate()); EXPECT_FALSE(delegate()->stored_group_success_); }
172,991
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AcceleratedStaticBitmapImage::Abandon() { texture_holder_->Abandon(); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
void AcceleratedStaticBitmapImage::Abandon() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); texture_holder_->Abandon(); }
172,587
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info, size_t count, const uint64_t clsid[2]) { size_t i; cdf_timestamp_t tp; struct timespec ts; char buf[64]; const char *str = NULL; const char *s; int len; if (!NOTMIME(ms)) str = cdf_clsid_to_mime(clsid, clsid2mime); for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: if (NOTMIME(ms) && file_printf(ms, ", %s: %hd", buf, info[i].pi_s16) == -1) return -1; break; case CDF_SIGNED32: if (NOTMIME(ms) && file_printf(ms, ", %s: %d", buf, info[i].pi_s32) == -1) return -1; break; case CDF_UNSIGNED32: if (NOTMIME(ms) && file_printf(ms, ", %s: %u", buf, info[i].pi_u32) == -1) return -1; break; case CDF_FLOAT: if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf, info[i].pi_f) == -1) return -1; break; case CDF_DOUBLE: if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf, info[i].pi_d) == -1) return -1; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: len = info[i].pi_str.s_len; if (len > 1) { char vbuf[1024]; size_t j, k = 1; if (info[i].pi_type == CDF_LENGTH32_WSTRING) k++; s = info[i].pi_str.s_buf; for (j = 0; j < sizeof(vbuf) && len--; j++, s += k) { if (*s == '\0') break; if (isprint((unsigned char)*s)) vbuf[j] = *s; } if (j == sizeof(vbuf)) --j; vbuf[j] = '\0'; if (NOTMIME(ms)) { if (vbuf[0]) { if (file_printf(ms, ", %s: %s", buf, vbuf) == -1) return -1; } } else if (str == NULL && info[i].pi_id == CDF_PROPERTY_NAME_OF_APPLICATION) { str = cdf_app_to_mime(vbuf, app2mime); } } break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp != 0) { char tbuf[64]; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(tbuf, sizeof(tbuf), tp); if (NOTMIME(ms) && file_printf(ms, ", %s: %s", buf, tbuf) == -1) return -1; } else { char *c, *ec; cdf_timestamp_to_timespec(&ts, tp); c = cdf_ctime(&ts.tv_sec, tbuf); if (c != NULL && (ec = strchr(c, '\n')) != NULL) *ec = '\0'; if (NOTMIME(ms) && file_printf(ms, ", %s: %s", buf, c) == -1) return -1; } } break; case CDF_CLIPBOARD: break; default: return -1; } } if (!NOTMIME(ms)) { if (str == NULL) return 0; if (file_printf(ms, "application/%s", str) == -1) return -1; } return 1; } Commit Message: Apply patches from file-CVE-2012-1571.patch From Francisco Alonso Espejo: file < 5.18/git version can be made to crash when checking some corrupt CDF files (Using an invalid cdf_read_short_sector size) The problem I found here, is that in most situations (if h_short_sec_size_p2 > 8) because the blocksize is 512 and normal values are 06 which means reading 64 bytes.As long as the check for the block size copy is not checked properly (there's an assert that makes wrong/invalid assumptions) CWE ID: CWE-119
cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info, size_t count, const cdf_directory_t *root_storage) { size_t i; cdf_timestamp_t tp; struct timespec ts; char buf[64]; const char *str = NULL; const char *s; int len; if (!NOTMIME(ms) && root_storage) str = cdf_clsid_to_mime(root_storage->d_storage_uuid, clsid2mime); for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: if (NOTMIME(ms) && file_printf(ms, ", %s: %hd", buf, info[i].pi_s16) == -1) return -1; break; case CDF_SIGNED32: if (NOTMIME(ms) && file_printf(ms, ", %s: %d", buf, info[i].pi_s32) == -1) return -1; break; case CDF_UNSIGNED32: if (NOTMIME(ms) && file_printf(ms, ", %s: %u", buf, info[i].pi_u32) == -1) return -1; break; case CDF_FLOAT: if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf, info[i].pi_f) == -1) return -1; break; case CDF_DOUBLE: if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf, info[i].pi_d) == -1) return -1; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: len = info[i].pi_str.s_len; if (len > 1) { char vbuf[1024]; size_t j, k = 1; if (info[i].pi_type == CDF_LENGTH32_WSTRING) k++; s = info[i].pi_str.s_buf; for (j = 0; j < sizeof(vbuf) && len--; j++, s += k) { if (*s == '\0') break; if (isprint((unsigned char)*s)) vbuf[j] = *s; } if (j == sizeof(vbuf)) --j; vbuf[j] = '\0'; if (NOTMIME(ms)) { if (vbuf[0]) { if (file_printf(ms, ", %s: %s", buf, vbuf) == -1) return -1; } } else if (str == NULL && info[i].pi_id == CDF_PROPERTY_NAME_OF_APPLICATION) { str = cdf_app_to_mime(vbuf, app2mime); } } break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp != 0) { char tbuf[64]; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(tbuf, sizeof(tbuf), tp); if (NOTMIME(ms) && file_printf(ms, ", %s: %s", buf, tbuf) == -1) return -1; } else { char *c, *ec; cdf_timestamp_to_timespec(&ts, tp); c = cdf_ctime(&ts.tv_sec, tbuf); if (c != NULL && (ec = strchr(c, '\n')) != NULL) *ec = '\0'; if (NOTMIME(ms) && file_printf(ms, ", %s: %s", buf, c) == -1) return -1; } } break; case CDF_CLIPBOARD: break; default: return -1; } } if (!NOTMIME(ms)) { if (str == NULL) return 0; if (file_printf(ms, "application/%s", str) == -1) return -1; } return 1; }
166,445
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_le_int (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 24) ; } ; } /* header_put_le_int */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_le_int (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = x ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 24) ; } /* header_put_le_int */
170,057
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */ { zval **value; zend_uchar key_type; zend_bool close_fp = 1; ulong int_key; struct _phar_t *p_obj = (struct _phar_t*) puser; uint str_key_len, base_len = p_obj->l, fname_len; phar_entry_data *data; php_stream *fp; size_t contents_len; char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL; phar_zstr key; char *str_key; zend_class_entry *ce = p_obj->c; phar_archive_object *phar_obj = p_obj->p; char *str = "[stream]"; iter->funcs->get_current_data(iter, &value TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (!value) { /* failure in get_current_data */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned no value", ce->name); return ZEND_HASH_APPLY_STOP; } switch (Z_TYPE_PP(value)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(*(value) TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: break; case IS_RESOURCE: php_stream_from_zval_no_verify(fp, value); if (!fp) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returned an invalid stream handle", ce->name); return ZEND_HASH_APPLY_STOP; } if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { /* IS_UNICODE == 10 */ #if PHP_VERSION_ID < 60000 /* this can never happen, but fixes a compile warning */ spprintf(&str_key, 0, "%s", key); #else spprintf(&str_key, 0, "%v", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\0') { str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } close_fp = 0; opened = (char *) estrndup(str, sizeof("[stream]") - 1); goto after_open_fp; case IS_OBJECT: if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) { char *test = NULL; zval dummy; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC); if (!base_len) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returns an SplFileInfo object, so base directory must be specified", ce->name); return ZEND_HASH_APPLY_STOP; } switch (intern->type) { case SPL_FS_DIR: #if PHP_VERSION_ID >= 60000 test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s; #elif PHP_VERSION_ID >= 50300 test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC); #else test = intern->path; #endif fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name); php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC); if (Z_BVAL(dummy)) { /* ignore directories */ efree(fname); return ZEND_HASH_APPLY_KEEP; } test = expand_filepath(fname, NULL TSRMLS_CC); efree(fname); if (test) { fname = test; fname_len = strlen(fname); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path"); return ZEND_HASH_APPLY_STOP; } save = fname; goto phar_spl_fileinfo; case SPL_FS_INFO: case SPL_FS_FILE: #if PHP_VERSION_ID >= 60000 if (intern->file_name_type == IS_UNICODE) { zval zv; INIT_ZVAL(zv); Z_UNIVAL(zv) = intern->file_name; Z_UNILEN(zv) = intern->file_name_len; Z_TYPE(zv) = IS_UNICODE; zval_copy_ctor(&zv); zval_unicode_to_string(&zv TSRMLS_CC); fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC); ezfree(Z_UNIVAL(zv)); } else { fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC); } #else fname = expand_filepath(intern->file_name, NULL TSRMLS_CC); #endif if (!fname) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path"); return ZEND_HASH_APPLY_STOP; } fname_len = strlen(fname); save = fname; goto phar_spl_fileinfo; } } /* fall-through */ default: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid value (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } fname = Z_STRVAL_PP(value); fname_len = Z_STRLEN_PP(value); phar_spl_fileinfo: if (base_len) { temp = expand_filepath(base, NULL TSRMLS_CC); if (!temp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path"); if (save) { efree(save); } return ZEND_HASH_APPLY_STOP; } base = temp; base_len = strlen(base); if (strstr(fname, base)) { str_key_len = fname_len - base_len; if (str_key_len <= 0) { if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_KEEP; } str_key = fname + base_len; if (*str_key == '/' || *str_key == '\\') { str_key++; str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that is not in the base directory \"%s\"", ce->name, fname, base); if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_STOP; } } else { if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { /* IS_UNICODE == 10 */ #if PHP_VERSION_ID < 60000 /* this can never happen, but fixes a compile warning */ spprintf(&str_key, 0, "%s", key); #else spprintf(&str_key, 0, "%v", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\0') str_key_len--; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that safe mode prevents opening", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that open_basedir prevents opening", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } /* try to open source file, then create internal phar file and copy contents */ fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened); if (!fp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a file that could not be opened \"%s\"", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } after_open_fp: if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { /* silently skip any files that would be added to the magic .phar directory */ if (save) { efree(save); } if (temp) { efree(temp); } if (opened) { efree(opened); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_KEEP; } if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1 TSRMLS_CC))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s cannot be created: %s", str_key, error); efree(error); if (save) { efree(save); } if (opened) { efree(opened); } if (temp) { efree(temp); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_STOP; } else { if (error) { efree(error); } /* convert to PHAR_UFP */ if (data->internal_file->fp_type == PHAR_MOD) { php_stream_close(data->internal_file->fp); } data->internal_file->fp = NULL; data->internal_file->fp_type = PHAR_UFP; data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp); data->fp = NULL; phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len); data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize = php_stream_tell(p_obj->fp) - data->internal_file->offset; } if (close_fp) { php_stream_close(fp); } add_assoc_string(p_obj->ret, str_key, opened, 0); if (save) { efree(save); } if (temp) { efree(temp); } data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; phar_entry_delref(data TSRMLS_CC); return ZEND_HASH_APPLY_KEEP; } /* }}} */ Commit Message: CWE ID: CWE-20
static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */ { zval **value; zend_uchar key_type; zend_bool close_fp = 1; ulong int_key; struct _phar_t *p_obj = (struct _phar_t*) puser; uint str_key_len, base_len = p_obj->l, fname_len; phar_entry_data *data; php_stream *fp; size_t contents_len; char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL; phar_zstr key; char *str_key; zend_class_entry *ce = p_obj->c; phar_archive_object *phar_obj = p_obj->p; char *str = "[stream]"; iter->funcs->get_current_data(iter, &value TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (!value) { /* failure in get_current_data */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned no value", ce->name); return ZEND_HASH_APPLY_STOP; } switch (Z_TYPE_PP(value)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(*(value) TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: break; case IS_RESOURCE: php_stream_from_zval_no_verify(fp, value); if (!fp) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returned an invalid stream handle", ce->name); return ZEND_HASH_APPLY_STOP; } if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { /* IS_UNICODE == 10 */ #if PHP_VERSION_ID < 60000 /* this can never happen, but fixes a compile warning */ spprintf(&str_key, 0, "%s", key); #else spprintf(&str_key, 0, "%v", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\0') { str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } close_fp = 0; opened = (char *) estrndup(str, sizeof("[stream]") - 1); goto after_open_fp; case IS_OBJECT: if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) { char *test = NULL; zval dummy; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC); if (!base_len) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returns an SplFileInfo object, so base directory must be specified", ce->name); return ZEND_HASH_APPLY_STOP; } switch (intern->type) { case SPL_FS_DIR: #if PHP_VERSION_ID >= 60000 test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s; #elif PHP_VERSION_ID >= 50300 test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC); #else test = intern->path; #endif fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name); php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC); if (Z_BVAL(dummy)) { /* ignore directories */ efree(fname); return ZEND_HASH_APPLY_KEEP; } test = expand_filepath(fname, NULL TSRMLS_CC); efree(fname); if (test) { fname = test; fname_len = strlen(fname); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path"); return ZEND_HASH_APPLY_STOP; } save = fname; goto phar_spl_fileinfo; case SPL_FS_INFO: case SPL_FS_FILE: #if PHP_VERSION_ID >= 60000 if (intern->file_name_type == IS_UNICODE) { zval zv; INIT_ZVAL(zv); Z_UNIVAL(zv) = intern->file_name; Z_UNILEN(zv) = intern->file_name_len; Z_TYPE(zv) = IS_UNICODE; zval_copy_ctor(&zv); zval_unicode_to_string(&zv TSRMLS_CC); fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC); ezfree(Z_UNIVAL(zv)); } else { fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC); } #else fname = expand_filepath(intern->file_name, NULL TSRMLS_CC); #endif if (!fname) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path"); return ZEND_HASH_APPLY_STOP; } fname_len = strlen(fname); save = fname; goto phar_spl_fileinfo; } } /* fall-through */ default: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid value (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } fname = Z_STRVAL_PP(value); fname_len = Z_STRLEN_PP(value); phar_spl_fileinfo: if (base_len) { temp = expand_filepath(base, NULL TSRMLS_CC); if (!temp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path"); if (save) { efree(save); } return ZEND_HASH_APPLY_STOP; } base = temp; base_len = strlen(base); if (strstr(fname, base)) { str_key_len = fname_len - base_len; if (str_key_len <= 0) { if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_KEEP; } str_key = fname + base_len; if (*str_key == '/' || *str_key == '\\') { str_key++; str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that is not in the base directory \"%s\"", ce->name, fname, base); if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_STOP; } } else { if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { /* IS_UNICODE == 10 */ #if PHP_VERSION_ID < 60000 /* this can never happen, but fixes a compile warning */ spprintf(&str_key, 0, "%s", key); #else spprintf(&str_key, 0, "%v", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\0') str_key_len--; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that safe mode prevents opening", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that open_basedir prevents opening", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } /* try to open source file, then create internal phar file and copy contents */ fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened); if (!fp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a file that could not be opened \"%s\"", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } after_open_fp: if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { /* silently skip any files that would be added to the magic .phar directory */ if (save) { efree(save); } if (temp) { efree(temp); } if (opened) { efree(opened); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_KEEP; } if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1 TSRMLS_CC))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s cannot be created: %s", str_key, error); efree(error); if (save) { efree(save); } if (opened) { efree(opened); } if (temp) { efree(temp); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_STOP; } else { if (error) { efree(error); } /* convert to PHAR_UFP */ if (data->internal_file->fp_type == PHAR_MOD) { php_stream_close(data->internal_file->fp); } data->internal_file->fp = NULL; data->internal_file->fp_type = PHAR_UFP; data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp); data->fp = NULL; phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len); data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize = php_stream_tell(p_obj->fp) - data->internal_file->offset; } if (close_fp) { php_stream_close(fp); } add_assoc_string(p_obj->ret, str_key, opened, 0); if (save) { efree(save); } if (temp) { efree(temp); } data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; phar_entry_delref(data TSRMLS_CC); return ZEND_HASH_APPLY_KEEP; } /* }}} */
165,297
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_recursive1 (MyObject *obj, GArray *array, guint32 *len_ret, GError **error) { *len_ret = array->len; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_recursive1 (MyObject *obj, GArray *array, guint32 *len_ret, GError **error)
165,117
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_vdec::set_parameter(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE paramIndex, OMX_IN OMX_PTR paramData) { OMX_ERRORTYPE eRet = OMX_ErrorNone; int ret=0; struct v4l2_format fmt; #ifdef _ANDROID_ char property_value[PROPERTY_VALUE_MAX] = {0}; #endif if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Set Param in Invalid State"); return OMX_ErrorInvalidState; } if (paramData == NULL) { DEBUG_PRINT_ERROR("Get Param in Invalid paramData"); return OMX_ErrorBadParameter; } if ((m_state != OMX_StateLoaded) && BITMASK_ABSENT(&m_flags,OMX_COMPONENT_OUTPUT_ENABLE_PENDING) && (m_out_bEnabled == OMX_TRUE) && BITMASK_ABSENT(&m_flags, OMX_COMPONENT_INPUT_ENABLE_PENDING) && (m_inp_bEnabled == OMX_TRUE)) { DEBUG_PRINT_ERROR("Set Param in Invalid State"); return OMX_ErrorIncorrectStateOperation; } switch ((unsigned long)paramIndex) { case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *portDefn; portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition H= %d, W = %d", (int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nFrameWidth); if (OMX_DirOutput == portDefn->eDir) { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition OP port"); bool port_format_changed = false; m_display_id = portDefn->format.video.pNativeWindow; unsigned int buffer_size; /* update output port resolution with client supplied dimensions in case scaling is enabled, else it follows input resolution set */ if (is_down_scalar_enabled) { DEBUG_PRINT_LOW("SetParam OP: WxH(%u x %u)", (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight); if (portDefn->format.video.nFrameHeight != 0x0 && portDefn->format.video.nFrameWidth != 0x0) { memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.pixelformat = capture_capability; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Get Resolution failed"); eRet = OMX_ErrorHardware; break; } if ((portDefn->format.video.nFrameHeight != (unsigned int)fmt.fmt.pix_mp.height) || (portDefn->format.video.nFrameWidth != (unsigned int)fmt.fmt.pix_mp.width)) { port_format_changed = true; } update_resolution(portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight, portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight); /* set crop info */ rectangle.nLeft = 0; rectangle.nTop = 0; rectangle.nWidth = portDefn->format.video.nFrameWidth; rectangle.nHeight = portDefn->format.video.nFrameHeight; eRet = is_video_session_supported(); if (eRet) break; memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = capture_capability; DEBUG_PRINT_LOW("fmt.fmt.pix_mp.height = %d , fmt.fmt.pix_mp.width = %d", fmt.fmt.pix_mp.height, fmt.fmt.pix_mp.width); ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set Resolution failed"); eRet = OMX_ErrorUnsupportedSetting; } else eRet = get_buffer_req(&drv_ctx.op_buf); } if (eRet) { break; } if (secure_mode) { struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_SECURE_SCALING_THRESHOLD; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Failed getting secure scaling threshold : %d, id was : %x", errno, control.id); eRet = OMX_ErrorHardware; } else { /* This is a workaround for a bug in fw which uses stride * and slice instead of width and height to check against * the threshold. */ OMX_U32 stride, slice; if (drv_ctx.output_format == VDEC_YUV_FORMAT_NV12) { stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, portDefn->format.video.nFrameWidth); slice = VENUS_Y_SCANLINES(COLOR_FMT_NV12, portDefn->format.video.nFrameHeight); } else { stride = portDefn->format.video.nFrameWidth; slice = portDefn->format.video.nFrameHeight; } DEBUG_PRINT_LOW("Stride is %d, slice is %d, sxs is %d\n", stride, slice, stride * slice); DEBUG_PRINT_LOW("Threshold value is %d\n", control.value); if (stride * slice <= (OMX_U32)control.value) { secure_scaling_to_non_secure_opb = true; DEBUG_PRINT_HIGH("Enabling secure scalar out of CPZ"); control.id = V4L2_CID_MPEG_VIDC_VIDEO_NON_SECURE_OUTPUT2; control.value = 1; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Enabling non-secure output2 failed"); eRet = OMX_ErrorUnsupportedSetting; } } } } } if (eRet) { break; } if (!client_buffers.get_buffer_req(buffer_size)) { DEBUG_PRINT_ERROR("Error in getting buffer requirements"); eRet = OMX_ErrorBadParameter; } else if (!port_format_changed) { if ( portDefn->nBufferCountActual >= drv_ctx.op_buf.mincount && portDefn->nBufferSize >= drv_ctx.op_buf.buffer_size ) { drv_ctx.op_buf.actualcount = portDefn->nBufferCountActual; drv_ctx.op_buf.buffer_size = portDefn->nBufferSize; drv_ctx.extradata_info.count = drv_ctx.op_buf.actualcount; drv_ctx.extradata_info.size = drv_ctx.extradata_info.count * drv_ctx.extradata_info.buffer_size; eRet = set_buffer_req(&drv_ctx.op_buf); if (eRet == OMX_ErrorNone) m_port_def = *portDefn; } else { DEBUG_PRINT_ERROR("ERROR: OP Requirements(#%d: %u) Requested(#%u: %u)", drv_ctx.op_buf.mincount, (unsigned int)drv_ctx.op_buf.buffer_size, (unsigned int)portDefn->nBufferCountActual, (unsigned int)portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; } } } else if (OMX_DirInput == portDefn->eDir) { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition IP port"); bool port_format_changed = false; if ((portDefn->format.video.xFramerate >> 16) > 0 && (portDefn->format.video.xFramerate >> 16) <= MAX_SUPPORTED_FPS) { DEBUG_PRINT_HIGH("set_parameter: frame rate set by omx client : %u", (unsigned int)portDefn->format.video.xFramerate >> 16); Q16ToFraction(portDefn->format.video.xFramerate, drv_ctx.frame_rate.fps_numerator, drv_ctx.frame_rate.fps_denominator); if (!drv_ctx.frame_rate.fps_numerator) { DEBUG_PRINT_ERROR("Numerator is zero setting to 30"); drv_ctx.frame_rate.fps_numerator = 30; } if (drv_ctx.frame_rate.fps_denominator) drv_ctx.frame_rate.fps_numerator = (int) drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator; drv_ctx.frame_rate.fps_denominator = 1; frm_int = drv_ctx.frame_rate.fps_denominator * 1e6 / drv_ctx.frame_rate.fps_numerator; DEBUG_PRINT_LOW("set_parameter: frm_int(%u) fps(%.2f)", (unsigned int)frm_int, drv_ctx.frame_rate.fps_numerator / (float)drv_ctx.frame_rate.fps_denominator); struct v4l2_outputparm oparm; /*XXX: we're providing timing info as seconds per frame rather than frames * per second.*/ oparm.timeperframe.numerator = drv_ctx.frame_rate.fps_denominator; oparm.timeperframe.denominator = drv_ctx.frame_rate.fps_numerator; struct v4l2_streamparm sparm; sparm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; sparm.parm.output = oparm; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_PARM, &sparm)) { DEBUG_PRINT_ERROR("Unable to convey fps info to driver, performance might be affected"); eRet = OMX_ErrorHardware; break; } } if (drv_ctx.video_resolution.frame_height != portDefn->format.video.nFrameHeight || drv_ctx.video_resolution.frame_width != portDefn->format.video.nFrameWidth) { DEBUG_PRINT_LOW("SetParam IP: WxH(%u x %u)", (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight); port_format_changed = true; OMX_U32 frameWidth = portDefn->format.video.nFrameWidth; OMX_U32 frameHeight = portDefn->format.video.nFrameHeight; if (frameHeight != 0x0 && frameWidth != 0x0) { if (m_smoothstreaming_mode && ((frameWidth * frameHeight) < (m_smoothstreaming_width * m_smoothstreaming_height))) { frameWidth = m_smoothstreaming_width; frameHeight = m_smoothstreaming_height; DEBUG_PRINT_LOW("NOTE: Setting resolution %u x %u " "for adaptive-playback/smooth-streaming", (unsigned int)frameWidth, (unsigned int)frameHeight); } update_resolution(frameWidth, frameHeight, frameWidth, frameHeight); eRet = is_video_session_supported(); if (eRet) break; memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = output_capability; DEBUG_PRINT_LOW("fmt.fmt.pix_mp.height = %d , fmt.fmt.pix_mp.width = %d",fmt.fmt.pix_mp.height,fmt.fmt.pix_mp.width); ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set Resolution failed"); eRet = OMX_ErrorUnsupportedSetting; } else { if (!is_down_scalar_enabled) eRet = get_buffer_req(&drv_ctx.op_buf); } } } if (m_custom_buffersize.input_buffersize && (portDefn->nBufferSize > m_custom_buffersize.input_buffersize)) { DEBUG_PRINT_ERROR("ERROR: Custom buffer size set by client: %d, trying to set: %d", m_custom_buffersize.input_buffersize, portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; break; } if (portDefn->nBufferCountActual >= drv_ctx.ip_buf.mincount || portDefn->nBufferSize != drv_ctx.ip_buf.buffer_size) { port_format_changed = true; vdec_allocatorproperty *buffer_prop = &drv_ctx.ip_buf; drv_ctx.ip_buf.actualcount = portDefn->nBufferCountActual; drv_ctx.ip_buf.buffer_size = (portDefn->nBufferSize + buffer_prop->alignment - 1) & (~(buffer_prop->alignment - 1)); eRet = set_buffer_req(buffer_prop); } if (false == port_format_changed) { DEBUG_PRINT_ERROR("ERROR: IP Requirements(#%d: %u) Requested(#%u: %u)", drv_ctx.ip_buf.mincount, (unsigned int)drv_ctx.ip_buf.buffer_size, (unsigned int)portDefn->nBufferCountActual, (unsigned int)portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; } } else if (portDefn->eDir == OMX_DirMax) { DEBUG_PRINT_ERROR(" Set_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } } break; case OMX_IndexParamVideoPortFormat: { OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; int ret=0; struct v4l2_format fmt; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat 0x%x, port: %u", portFmt->eColorFormat, (unsigned int)portFmt->nPortIndex); memset(&fmt, 0x0, sizeof(struct v4l2_format)); if (1 == portFmt->nPortIndex) { fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = capture_capability; enum vdec_output_fromat op_format; if (portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m || portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mMultiView || portFmt->eColorFormat == OMX_COLOR_FormatYUV420Planar || portFmt->eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) op_format = (enum vdec_output_fromat)VDEC_YUV_FORMAT_NV12; else eRet = OMX_ErrorBadParameter; if (eRet == OMX_ErrorNone) { drv_ctx.output_format = op_format; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set output format failed"); eRet = OMX_ErrorUnsupportedSetting; /*TODO: How to handle this case */ } else { eRet = get_buffer_req(&drv_ctx.op_buf); } } if (eRet == OMX_ErrorNone) { if (!client_buffers.set_color_format(portFmt->eColorFormat)) { DEBUG_PRINT_ERROR("Set color format failed"); eRet = OMX_ErrorBadParameter; } } } } break; case OMX_QcomIndexPortDefn: { OMX_QCOM_PARAM_PORTDEFINITIONTYPE *portFmt = (OMX_QCOM_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexQcomParamPortDefinitionType %u", (unsigned int)portFmt->nFramePackingFormat); /* Input port */ if (portFmt->nPortIndex == 0) { if (portFmt->nFramePackingFormat == OMX_QCOM_FramePacking_Arbitrary) { if (secure_mode) { arbitrary_bytes = false; DEBUG_PRINT_ERROR("setparameter: cannot set to arbitary bytes mode in secure session"); eRet = OMX_ErrorUnsupportedSetting; } else { arbitrary_bytes = true; } } else if (portFmt->nFramePackingFormat == OMX_QCOM_FramePacking_OnlyOneCompleteFrame) { arbitrary_bytes = false; #ifdef _ANDROID_ property_get("vidc.dec.debug.arbitrarybytes.mode", property_value, "0"); if (atoi(property_value)) { DEBUG_PRINT_HIGH("arbitrary_bytes enabled via property command"); arbitrary_bytes = true; } #endif } else { DEBUG_PRINT_ERROR("Setparameter: unknown FramePacking format %u", (unsigned int)portFmt->nFramePackingFormat); eRet = OMX_ErrorUnsupportedSetting; } } else if (portFmt->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { DEBUG_PRINT_HIGH("set_parameter: OMX_IndexQcomParamPortDefinitionType OP Port"); if ( (portFmt->nMemRegion > OMX_QCOM_MemRegionInvalid && portFmt->nMemRegion < OMX_QCOM_MemRegionMax) && portFmt->nCacheAttr == OMX_QCOM_CacheAttrNone) { m_out_mem_region_smi = OMX_TRUE; if ((m_out_mem_region_smi && m_out_pvt_entry_pmem)) { DEBUG_PRINT_HIGH("set_parameter: OMX_IndexQcomParamPortDefinitionType OP Port: out pmem set"); m_use_output_pmem = OMX_TRUE; } } } } break; case OMX_IndexParamStandardComponentRole: { OMX_PARAM_COMPONENTROLETYPE *comp_role; comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamStandardComponentRole %s", comp_role->cRole); if ((m_state == OMX_StateLoaded)&& !BITMASK_PRESENT(&m_flags,OMX_COMPONENT_IDLE_PENDING)) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.avc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_decoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mvc", OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole, "video_decoder.mvc", OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole, "video_decoder.mvc", OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.h263",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.h263",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.h263",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if ((!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx",OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx311", OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx4", OMX_MAX_STRINGNAME_SIZE)) ) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.divx",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.divx",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if ( (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.vc1",OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.wmv",OMX_MAX_STRINGNAME_SIZE)) ) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.vc1",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.vc1",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.vp8",OMX_MAX_STRINGNAME_SIZE) || (!strncmp((const char*)comp_role->cRole,"video_decoder.vpx",OMX_MAX_STRINGNAME_SIZE))) { strlcpy((char*)m_cRole,"video_decoder.vp8",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.hevc", OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole, "video_decoder.hevc", OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole, "video_decoder.hevc", OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("Setparameter: unknown param %s", drv_ctx.kind); eRet = OMX_ErrorInvalidComponentName; } break; } case OMX_IndexParamPriorityMgmt: { if (m_state != OMX_StateLoaded) { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } OMX_PRIORITYMGMTTYPE *priorityMgmtype = (OMX_PRIORITYMGMTTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt %u", (unsigned int)priorityMgmtype->nGroupID); DEBUG_PRINT_LOW("set_parameter: priorityMgmtype %u", (unsigned int)priorityMgmtype->nGroupPriority); m_priority_mgm.nGroupID = priorityMgmtype->nGroupID; m_priority_mgm.nGroupPriority = priorityMgmtype->nGroupPriority; break; } case OMX_IndexParamCompBufferSupplier: { OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier %d", bufferSupplierType->eBufferSupplier); if (bufferSupplierType->nPortIndex == 0 || bufferSupplierType->nPortIndex ==1) m_buffer_supplier.eBufferSupplier = bufferSupplierType->eBufferSupplier; else eRet = OMX_ErrorBadPortIndex; break; } case OMX_IndexParamVideoAvc: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoAvc %d", paramIndex); break; } case (OMX_INDEXTYPE)QOMX_IndexParamVideoMvc: { DEBUG_PRINT_LOW("set_parameter: QOMX_IndexParamVideoMvc %d", paramIndex); break; } case OMX_IndexParamVideoH263: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoH263 %d", paramIndex); break; } case OMX_IndexParamVideoMpeg4: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg4 %d", paramIndex); break; } case OMX_IndexParamVideoMpeg2: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg2 %d", paramIndex); break; } case OMX_QcomIndexParamVideoDecoderPictureOrder: { QOMX_VIDEO_DECODER_PICTURE_ORDER *pictureOrder = (QOMX_VIDEO_DECODER_PICTURE_ORDER *)paramData; struct v4l2_control control; int pic_order,rc=0; DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamVideoDecoderPictureOrder %d", pictureOrder->eOutputPictureOrder); if (pictureOrder->eOutputPictureOrder == QOMX_VIDEO_DISPLAY_ORDER) { pic_order = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DISPLAY; } else if (pictureOrder->eOutputPictureOrder == QOMX_VIDEO_DECODE_ORDER) { pic_order = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE; time_stamp_dts.set_timestamp_reorder_mode(false); } else eRet = OMX_ErrorBadParameter; if (eRet == OMX_ErrorNone) { control.id = V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER; control.value = pic_order; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Set picture order failed"); eRet = OMX_ErrorUnsupportedSetting; } } break; } case OMX_QcomIndexParamConcealMBMapExtraData: eRet = enable_extradata(VDEC_EXTRADATA_MB_ERROR_MAP, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamFrameInfoExtraData: eRet = enable_extradata(OMX_FRAMEINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_ExtraDataFrameDimension: eRet = enable_extradata(OMX_FRAMEDIMENSION_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamInterlaceExtraData: eRet = enable_extradata(OMX_INTERLACE_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamH264TimeInfo: eRet = enable_extradata(OMX_TIMEINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoFramePackingExtradata: eRet = enable_extradata(OMX_FRAMEPACK_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoQPExtraData: eRet = enable_extradata(OMX_QP_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoInputBitsInfoExtraData: eRet = enable_extradata(OMX_BITSINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexEnableExtnUserData: eRet = enable_extradata(OMX_EXTNUSER_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamMpeg2SeqDispExtraData: eRet = enable_extradata(OMX_MPEG2SEQDISP_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoDivx: { QOMX_VIDEO_PARAM_DIVXTYPE* divXType = (QOMX_VIDEO_PARAM_DIVXTYPE *) paramData; } break; case OMX_QcomIndexPlatformPvt: { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexPlatformPvt OP Port"); OMX_QCOM_PLATFORMPRIVATE_EXTN* entryType = (OMX_QCOM_PLATFORMPRIVATE_EXTN *) paramData; if (entryType->type != OMX_QCOM_PLATFORM_PRIVATE_PMEM) { DEBUG_PRINT_HIGH("set_parameter: Platform Private entry type (%d) not supported.", entryType->type); eRet = OMX_ErrorUnsupportedSetting; } else { m_out_pvt_entry_pmem = OMX_TRUE; if ((m_out_mem_region_smi && m_out_pvt_entry_pmem)) { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexPlatformPvt OP Port: out pmem set"); m_use_output_pmem = OMX_TRUE; } } } break; case OMX_QcomIndexParamVideoSyncFrameDecodingMode: { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamVideoSyncFrameDecodingMode"); DEBUG_PRINT_HIGH("set idr only decoding for thumbnail mode"); struct v4l2_control control; int rc; drv_ctx.idr_only_decoding = 1; control.id = V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER; control.value = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Set picture order failed"); eRet = OMX_ErrorUnsupportedSetting; } else { control.id = V4L2_CID_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE; control.value = V4L2_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE_ENABLE; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Sync frame setting failed"); eRet = OMX_ErrorUnsupportedSetting; } /*Setting sync frame decoding on driver might change buffer * requirements so update them here*/ if (get_buffer_req(&drv_ctx.ip_buf)) { DEBUG_PRINT_ERROR("Sync frame setting failed: falied to get buffer i/p requirements"); eRet = OMX_ErrorUnsupportedSetting; } if (get_buffer_req(&drv_ctx.op_buf)) { DEBUG_PRINT_ERROR("Sync frame setting failed: falied to get buffer o/p requirements"); eRet = OMX_ErrorUnsupportedSetting; } } } break; case OMX_QcomIndexParamIndexExtraDataType: { QOMX_INDEXEXTRADATATYPE *extradataIndexType = (QOMX_INDEXEXTRADATATYPE *) paramData; if ((extradataIndexType->nIndex == OMX_IndexParamPortDefinition) && (extradataIndexType->bEnabled == OMX_TRUE) && (extradataIndexType->nPortIndex == 1)) { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamIndexExtraDataType SmoothStreaming"); eRet = enable_extradata(OMX_PORTDEF_EXTRADATA, false, extradataIndexType->bEnabled); } } break; case OMX_QcomIndexParamEnableSmoothStreaming: { #ifndef SMOOTH_STREAMING_DISABLED eRet = enable_smoothstreaming(); #else eRet = OMX_ErrorUnsupportedSetting; #endif } break; #if defined (_ANDROID_HONEYCOMB_) || defined (_ANDROID_ICS_) /* Need to allow following two set_parameters even in Idle * state. This is ANDROID architecture which is not in sync * with openmax standard. */ case OMX_GoogleAndroidIndexEnableAndroidNativeBuffers: { EnableAndroidNativeBuffersParams* enableNativeBuffers = (EnableAndroidNativeBuffersParams *) paramData; if (enableNativeBuffers) { m_enable_android_native_buffers = enableNativeBuffers->enable; } #if !defined(FLEXYUV_SUPPORTED) if (m_enable_android_native_buffers) { if(!client_buffers.set_color_format(getPreferredColorFormatDefaultMode(0))) { DEBUG_PRINT_ERROR("Failed to set native color format!"); eRet = OMX_ErrorUnsupportedSetting; } } #endif } break; case OMX_GoogleAndroidIndexUseAndroidNativeBuffer: { eRet = use_android_native_buffer(hComp, paramData); } break; #endif case OMX_QcomIndexParamEnableTimeStampReorder: { QOMX_INDEXTIMESTAMPREORDER *reorder = (QOMX_INDEXTIMESTAMPREORDER *)paramData; if (drv_ctx.picture_order == (vdec_output_order)QOMX_VIDEO_DISPLAY_ORDER) { if (reorder->bEnable == OMX_TRUE) { frm_int =0; time_stamp_dts.set_timestamp_reorder_mode(true); } else time_stamp_dts.set_timestamp_reorder_mode(false); } else { time_stamp_dts.set_timestamp_reorder_mode(false); if (reorder->bEnable == OMX_TRUE) { eRet = OMX_ErrorUnsupportedSetting; } } } break; case OMX_IndexParamVideoProfileLevelCurrent: { OMX_VIDEO_PARAM_PROFILELEVELTYPE* pParam = (OMX_VIDEO_PARAM_PROFILELEVELTYPE*)paramData; if (pParam) { m_profile_lvl.eProfile = pParam->eProfile; m_profile_lvl.eLevel = pParam->eLevel; } break; } case OMX_QcomIndexParamVideoMetaBufferMode: { StoreMetaDataInBuffersParams *metabuffer = (StoreMetaDataInBuffersParams *)paramData; if (!metabuffer) { DEBUG_PRINT_ERROR("Invalid param: %p", metabuffer); eRet = OMX_ErrorBadParameter; break; } if (m_disable_dynamic_buf_mode) { DEBUG_PRINT_HIGH("Dynamic buffer mode disabled by setprop"); eRet = OMX_ErrorUnsupportedSetting; break; } if (metabuffer->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { struct v4l2_control control; struct v4l2_format fmt; control.id = V4L2_CID_MPEG_VIDC_VIDEO_ALLOC_MODE_OUTPUT; if (metabuffer->bStoreMetaData == true) { control.value = V4L2_MPEG_VIDC_VIDEO_DYNAMIC; } else { control.value = V4L2_MPEG_VIDC_VIDEO_STATIC; } int rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL,&control); if (!rc) { DEBUG_PRINT_HIGH("%s buffer mode", (metabuffer->bStoreMetaData == true)? "Enabled dynamic" : "Disabled dynamic"); dynamic_buf_mode = metabuffer->bStoreMetaData; } else { DEBUG_PRINT_ERROR("Failed to %s buffer mode", (metabuffer->bStoreMetaData == true)? "enable dynamic" : "disable dynamic"); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR( "OMX_QcomIndexParamVideoMetaBufferMode not supported for port: %u", (unsigned int)metabuffer->nPortIndex); eRet = OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamVideoDownScalar: { QOMX_INDEXDOWNSCALAR* pParam = (QOMX_INDEXDOWNSCALAR*)paramData; struct v4l2_control control; int rc; if (pParam) { is_down_scalar_enabled = pParam->bEnable; if (is_down_scalar_enabled) { control.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE; control.value = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_SECONDARY; DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoDownScalar value = %d", pParam->bEnable); rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc < 0) { DEBUG_PRINT_ERROR("Failed to set down scalar on driver."); eRet = OMX_ErrorUnsupportedSetting; } control.id = V4L2_CID_MPEG_VIDC_VIDEO_KEEP_ASPECT_RATIO; control.value = 1; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc < 0) { DEBUG_PRINT_ERROR("Failed to set keep aspect ratio on driver."); eRet = OMX_ErrorUnsupportedSetting; } } } break; } #ifdef ADAPTIVE_PLAYBACK_SUPPORTED case OMX_QcomIndexParamVideoAdaptivePlaybackMode: { DEBUG_PRINT_LOW("set_parameter: OMX_GoogleAndroidIndexPrepareForAdaptivePlayback"); PrepareForAdaptivePlaybackParams* pParams = (PrepareForAdaptivePlaybackParams *) paramData; if (pParams->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { if (!pParams->bEnable) { return OMX_ErrorNone; } if (pParams->nMaxFrameWidth > maxSmoothStreamingWidth || pParams->nMaxFrameHeight > maxSmoothStreamingHeight) { DEBUG_PRINT_ERROR( "Adaptive playback request exceeds max supported resolution : [%u x %u] vs [%u x %u]", (unsigned int)pParams->nMaxFrameWidth, (unsigned int)pParams->nMaxFrameHeight, (unsigned int)maxSmoothStreamingWidth, (unsigned int)maxSmoothStreamingHeight); eRet = OMX_ErrorBadParameter; } else { eRet = enable_adaptive_playback(pParams->nMaxFrameWidth, pParams->nMaxFrameHeight); } } else { DEBUG_PRINT_ERROR( "Prepare for adaptive playback supported only on output port"); eRet = OMX_ErrorBadParameter; } break; } #endif case OMX_QcomIndexParamVideoCustomBufferSize: { DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoCustomBufferSize"); QOMX_VIDEO_CUSTOM_BUFFERSIZE* pParam = (QOMX_VIDEO_CUSTOM_BUFFERSIZE*)paramData; if (pParam->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) { struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_BUFFER_SIZE_LIMIT; control.value = pParam->nBufferSize; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) { DEBUG_PRINT_ERROR("Failed to set input buffer size"); eRet = OMX_ErrorUnsupportedSetting; } else { eRet = get_buffer_req(&drv_ctx.ip_buf); if (eRet == OMX_ErrorNone) { m_custom_buffersize.input_buffersize = drv_ctx.ip_buf.buffer_size; DEBUG_PRINT_HIGH("Successfully set custom input buffer size = %d", m_custom_buffersize.input_buffersize); } else { DEBUG_PRINT_ERROR("Failed to get buffer requirement"); } } } else { DEBUG_PRINT_ERROR("ERROR: Custom buffer size in not supported on output port"); eRet = OMX_ErrorBadParameter; } break; } default: { DEBUG_PRINT_ERROR("Setparameter: unknown param %d", paramIndex); eRet = OMX_ErrorUnsupportedIndex; } } if (eRet != OMX_ErrorNone) DEBUG_PRINT_ERROR("set_parameter: Error: 0x%x, setting param 0x%x", eRet, paramIndex); return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20
OMX_ERRORTYPE omx_vdec::set_parameter(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE paramIndex, OMX_IN OMX_PTR paramData) { OMX_ERRORTYPE eRet = OMX_ErrorNone; int ret=0; struct v4l2_format fmt; #ifdef _ANDROID_ char property_value[PROPERTY_VALUE_MAX] = {0}; #endif if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Set Param in Invalid State"); return OMX_ErrorInvalidState; } if (paramData == NULL) { DEBUG_PRINT_ERROR("Get Param in Invalid paramData"); return OMX_ErrorBadParameter; } if ((m_state != OMX_StateLoaded) && BITMASK_ABSENT(&m_flags,OMX_COMPONENT_OUTPUT_ENABLE_PENDING) && (m_out_bEnabled == OMX_TRUE) && BITMASK_ABSENT(&m_flags, OMX_COMPONENT_INPUT_ENABLE_PENDING) && (m_inp_bEnabled == OMX_TRUE)) { DEBUG_PRINT_ERROR("Set Param in Invalid State"); return OMX_ErrorIncorrectStateOperation; } switch ((unsigned long)paramIndex) { case OMX_IndexParamPortDefinition: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_PORTDEFINITIONTYPE); OMX_PARAM_PORTDEFINITIONTYPE *portDefn; portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition H= %d, W = %d", (int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nFrameWidth); if (OMX_DirOutput == portDefn->eDir) { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition OP port"); bool port_format_changed = false; m_display_id = portDefn->format.video.pNativeWindow; unsigned int buffer_size; /* update output port resolution with client supplied dimensions in case scaling is enabled, else it follows input resolution set */ if (is_down_scalar_enabled) { DEBUG_PRINT_LOW("SetParam OP: WxH(%u x %u)", (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight); if (portDefn->format.video.nFrameHeight != 0x0 && portDefn->format.video.nFrameWidth != 0x0) { memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.pixelformat = capture_capability; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Get Resolution failed"); eRet = OMX_ErrorHardware; break; } if ((portDefn->format.video.nFrameHeight != (unsigned int)fmt.fmt.pix_mp.height) || (portDefn->format.video.nFrameWidth != (unsigned int)fmt.fmt.pix_mp.width)) { port_format_changed = true; } update_resolution(portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight, portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight); /* set crop info */ rectangle.nLeft = 0; rectangle.nTop = 0; rectangle.nWidth = portDefn->format.video.nFrameWidth; rectangle.nHeight = portDefn->format.video.nFrameHeight; eRet = is_video_session_supported(); if (eRet) break; memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = capture_capability; DEBUG_PRINT_LOW("fmt.fmt.pix_mp.height = %d , fmt.fmt.pix_mp.width = %d", fmt.fmt.pix_mp.height, fmt.fmt.pix_mp.width); ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set Resolution failed"); eRet = OMX_ErrorUnsupportedSetting; } else eRet = get_buffer_req(&drv_ctx.op_buf); } if (eRet) { break; } if (secure_mode) { struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_SECURE_SCALING_THRESHOLD; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Failed getting secure scaling threshold : %d, id was : %x", errno, control.id); eRet = OMX_ErrorHardware; } else { /* This is a workaround for a bug in fw which uses stride * and slice instead of width and height to check against * the threshold. */ OMX_U32 stride, slice; if (drv_ctx.output_format == VDEC_YUV_FORMAT_NV12) { stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, portDefn->format.video.nFrameWidth); slice = VENUS_Y_SCANLINES(COLOR_FMT_NV12, portDefn->format.video.nFrameHeight); } else { stride = portDefn->format.video.nFrameWidth; slice = portDefn->format.video.nFrameHeight; } DEBUG_PRINT_LOW("Stride is %d, slice is %d, sxs is %d\n", stride, slice, stride * slice); DEBUG_PRINT_LOW("Threshold value is %d\n", control.value); if (stride * slice <= (OMX_U32)control.value) { secure_scaling_to_non_secure_opb = true; DEBUG_PRINT_HIGH("Enabling secure scalar out of CPZ"); control.id = V4L2_CID_MPEG_VIDC_VIDEO_NON_SECURE_OUTPUT2; control.value = 1; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Enabling non-secure output2 failed"); eRet = OMX_ErrorUnsupportedSetting; } } } } } if (eRet) { break; } if (!client_buffers.get_buffer_req(buffer_size)) { DEBUG_PRINT_ERROR("Error in getting buffer requirements"); eRet = OMX_ErrorBadParameter; } else if (!port_format_changed) { if ( portDefn->nBufferCountActual >= drv_ctx.op_buf.mincount && portDefn->nBufferSize >= drv_ctx.op_buf.buffer_size ) { drv_ctx.op_buf.actualcount = portDefn->nBufferCountActual; drv_ctx.op_buf.buffer_size = portDefn->nBufferSize; drv_ctx.extradata_info.count = drv_ctx.op_buf.actualcount; drv_ctx.extradata_info.size = drv_ctx.extradata_info.count * drv_ctx.extradata_info.buffer_size; eRet = set_buffer_req(&drv_ctx.op_buf); if (eRet == OMX_ErrorNone) m_port_def = *portDefn; } else { DEBUG_PRINT_ERROR("ERROR: OP Requirements(#%d: %u) Requested(#%u: %u)", drv_ctx.op_buf.mincount, (unsigned int)drv_ctx.op_buf.buffer_size, (unsigned int)portDefn->nBufferCountActual, (unsigned int)portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; } } } else if (OMX_DirInput == portDefn->eDir) { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition IP port"); bool port_format_changed = false; if ((portDefn->format.video.xFramerate >> 16) > 0 && (portDefn->format.video.xFramerate >> 16) <= MAX_SUPPORTED_FPS) { DEBUG_PRINT_HIGH("set_parameter: frame rate set by omx client : %u", (unsigned int)portDefn->format.video.xFramerate >> 16); Q16ToFraction(portDefn->format.video.xFramerate, drv_ctx.frame_rate.fps_numerator, drv_ctx.frame_rate.fps_denominator); if (!drv_ctx.frame_rate.fps_numerator) { DEBUG_PRINT_ERROR("Numerator is zero setting to 30"); drv_ctx.frame_rate.fps_numerator = 30; } if (drv_ctx.frame_rate.fps_denominator) drv_ctx.frame_rate.fps_numerator = (int) drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator; drv_ctx.frame_rate.fps_denominator = 1; frm_int = drv_ctx.frame_rate.fps_denominator * 1e6 / drv_ctx.frame_rate.fps_numerator; DEBUG_PRINT_LOW("set_parameter: frm_int(%u) fps(%.2f)", (unsigned int)frm_int, drv_ctx.frame_rate.fps_numerator / (float)drv_ctx.frame_rate.fps_denominator); struct v4l2_outputparm oparm; /*XXX: we're providing timing info as seconds per frame rather than frames * per second.*/ oparm.timeperframe.numerator = drv_ctx.frame_rate.fps_denominator; oparm.timeperframe.denominator = drv_ctx.frame_rate.fps_numerator; struct v4l2_streamparm sparm; sparm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; sparm.parm.output = oparm; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_PARM, &sparm)) { DEBUG_PRINT_ERROR("Unable to convey fps info to driver, performance might be affected"); eRet = OMX_ErrorHardware; break; } } if (drv_ctx.video_resolution.frame_height != portDefn->format.video.nFrameHeight || drv_ctx.video_resolution.frame_width != portDefn->format.video.nFrameWidth) { DEBUG_PRINT_LOW("SetParam IP: WxH(%u x %u)", (unsigned int)portDefn->format.video.nFrameWidth, (unsigned int)portDefn->format.video.nFrameHeight); port_format_changed = true; OMX_U32 frameWidth = portDefn->format.video.nFrameWidth; OMX_U32 frameHeight = portDefn->format.video.nFrameHeight; if (frameHeight != 0x0 && frameWidth != 0x0) { if (m_smoothstreaming_mode && ((frameWidth * frameHeight) < (m_smoothstreaming_width * m_smoothstreaming_height))) { frameWidth = m_smoothstreaming_width; frameHeight = m_smoothstreaming_height; DEBUG_PRINT_LOW("NOTE: Setting resolution %u x %u " "for adaptive-playback/smooth-streaming", (unsigned int)frameWidth, (unsigned int)frameHeight); } update_resolution(frameWidth, frameHeight, frameWidth, frameHeight); eRet = is_video_session_supported(); if (eRet) break; memset(&fmt, 0x0, sizeof(struct v4l2_format)); fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = output_capability; DEBUG_PRINT_LOW("fmt.fmt.pix_mp.height = %d , fmt.fmt.pix_mp.width = %d",fmt.fmt.pix_mp.height,fmt.fmt.pix_mp.width); ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set Resolution failed"); eRet = OMX_ErrorUnsupportedSetting; } else { if (!is_down_scalar_enabled) eRet = get_buffer_req(&drv_ctx.op_buf); } } } if (m_custom_buffersize.input_buffersize && (portDefn->nBufferSize > m_custom_buffersize.input_buffersize)) { DEBUG_PRINT_ERROR("ERROR: Custom buffer size set by client: %d, trying to set: %d", m_custom_buffersize.input_buffersize, portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; break; } if (portDefn->nBufferCountActual >= drv_ctx.ip_buf.mincount || portDefn->nBufferSize != drv_ctx.ip_buf.buffer_size) { port_format_changed = true; vdec_allocatorproperty *buffer_prop = &drv_ctx.ip_buf; drv_ctx.ip_buf.actualcount = portDefn->nBufferCountActual; drv_ctx.ip_buf.buffer_size = (portDefn->nBufferSize + buffer_prop->alignment - 1) & (~(buffer_prop->alignment - 1)); eRet = set_buffer_req(buffer_prop); } if (false == port_format_changed) { DEBUG_PRINT_ERROR("ERROR: IP Requirements(#%d: %u) Requested(#%u: %u)", drv_ctx.ip_buf.mincount, (unsigned int)drv_ctx.ip_buf.buffer_size, (unsigned int)portDefn->nBufferCountActual, (unsigned int)portDefn->nBufferSize); eRet = OMX_ErrorBadParameter; } } else if (portDefn->eDir == OMX_DirMax) { DEBUG_PRINT_ERROR(" Set_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } } break; case OMX_IndexParamVideoPortFormat: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PORTFORMATTYPE); OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; int ret=0; struct v4l2_format fmt; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat 0x%x, port: %u", portFmt->eColorFormat, (unsigned int)portFmt->nPortIndex); memset(&fmt, 0x0, sizeof(struct v4l2_format)); if (1 == portFmt->nPortIndex) { fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height; fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width; fmt.fmt.pix_mp.pixelformat = capture_capability; enum vdec_output_fromat op_format; if (portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m || portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mMultiView || portFmt->eColorFormat == OMX_COLOR_FormatYUV420Planar || portFmt->eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) op_format = (enum vdec_output_fromat)VDEC_YUV_FORMAT_NV12; else eRet = OMX_ErrorBadParameter; if (eRet == OMX_ErrorNone) { drv_ctx.output_format = op_format; ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt); if (ret) { DEBUG_PRINT_ERROR("Set output format failed"); eRet = OMX_ErrorUnsupportedSetting; /*TODO: How to handle this case */ } else { eRet = get_buffer_req(&drv_ctx.op_buf); } } if (eRet == OMX_ErrorNone) { if (!client_buffers.set_color_format(portFmt->eColorFormat)) { DEBUG_PRINT_ERROR("Set color format failed"); eRet = OMX_ErrorBadParameter; } } } } break; case OMX_QcomIndexPortDefn: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PARAM_PORTDEFINITIONTYPE); OMX_QCOM_PARAM_PORTDEFINITIONTYPE *portFmt = (OMX_QCOM_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexQcomParamPortDefinitionType %u", (unsigned int)portFmt->nFramePackingFormat); /* Input port */ if (portFmt->nPortIndex == 0) { if (portFmt->nFramePackingFormat == OMX_QCOM_FramePacking_Arbitrary) { if (secure_mode) { arbitrary_bytes = false; DEBUG_PRINT_ERROR("setparameter: cannot set to arbitary bytes mode in secure session"); eRet = OMX_ErrorUnsupportedSetting; } else { arbitrary_bytes = true; } } else if (portFmt->nFramePackingFormat == OMX_QCOM_FramePacking_OnlyOneCompleteFrame) { arbitrary_bytes = false; #ifdef _ANDROID_ property_get("vidc.dec.debug.arbitrarybytes.mode", property_value, "0"); if (atoi(property_value)) { DEBUG_PRINT_HIGH("arbitrary_bytes enabled via property command"); arbitrary_bytes = true; } #endif } else { DEBUG_PRINT_ERROR("Setparameter: unknown FramePacking format %u", (unsigned int)portFmt->nFramePackingFormat); eRet = OMX_ErrorUnsupportedSetting; } } else if (portFmt->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { DEBUG_PRINT_HIGH("set_parameter: OMX_IndexQcomParamPortDefinitionType OP Port"); if ( (portFmt->nMemRegion > OMX_QCOM_MemRegionInvalid && portFmt->nMemRegion < OMX_QCOM_MemRegionMax) && portFmt->nCacheAttr == OMX_QCOM_CacheAttrNone) { m_out_mem_region_smi = OMX_TRUE; if ((m_out_mem_region_smi && m_out_pvt_entry_pmem)) { DEBUG_PRINT_HIGH("set_parameter: OMX_IndexQcomParamPortDefinitionType OP Port: out pmem set"); m_use_output_pmem = OMX_TRUE; } } } } break; case OMX_IndexParamStandardComponentRole: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_COMPONENTROLETYPE); OMX_PARAM_COMPONENTROLETYPE *comp_role; comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamStandardComponentRole %s", comp_role->cRole); if ((m_state == OMX_StateLoaded)&& !BITMASK_PRESENT(&m_flags,OMX_COMPONENT_IDLE_PENDING)) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.avc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_decoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mvc", OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole, "video_decoder.mvc", OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole, "video_decoder.mvc", OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.h263",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.h263",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.h263",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if ((!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx",OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx311", OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx4", OMX_MAX_STRINGNAME_SIZE)) ) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.divx",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.divx",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if ( (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.vc1",OMX_MAX_STRINGNAME_SIZE)) || (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.wmv",OMX_MAX_STRINGNAME_SIZE)) ) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.vc1",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_decoder.vc1",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_decoder.vp8",OMX_MAX_STRINGNAME_SIZE) || (!strncmp((const char*)comp_role->cRole,"video_decoder.vpx",OMX_MAX_STRINGNAME_SIZE))) { strlcpy((char*)m_cRole,"video_decoder.vp8",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.hevc", OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole, "video_decoder.hevc", OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole, "video_decoder.hevc", OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("Setparameter: unknown param %s", drv_ctx.kind); eRet = OMX_ErrorInvalidComponentName; } break; } case OMX_IndexParamPriorityMgmt: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PRIORITYMGMTTYPE); if (m_state != OMX_StateLoaded) { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } OMX_PRIORITYMGMTTYPE *priorityMgmtype = (OMX_PRIORITYMGMTTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt %u", (unsigned int)priorityMgmtype->nGroupID); DEBUG_PRINT_LOW("set_parameter: priorityMgmtype %u", (unsigned int)priorityMgmtype->nGroupPriority); m_priority_mgm.nGroupID = priorityMgmtype->nGroupID; m_priority_mgm.nGroupPriority = priorityMgmtype->nGroupPriority; break; } case OMX_IndexParamCompBufferSupplier: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_BUFFERSUPPLIERTYPE); OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier %d", bufferSupplierType->eBufferSupplier); if (bufferSupplierType->nPortIndex == 0 || bufferSupplierType->nPortIndex ==1) m_buffer_supplier.eBufferSupplier = bufferSupplierType->eBufferSupplier; else eRet = OMX_ErrorBadPortIndex; break; } case OMX_IndexParamVideoAvc: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoAvc %d", paramIndex); break; } case (OMX_INDEXTYPE)QOMX_IndexParamVideoMvc: { DEBUG_PRINT_LOW("set_parameter: QOMX_IndexParamVideoMvc %d", paramIndex); break; } case OMX_IndexParamVideoH263: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoH263 %d", paramIndex); break; } case OMX_IndexParamVideoMpeg4: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg4 %d", paramIndex); break; } case OMX_IndexParamVideoMpeg2: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg2 %d", paramIndex); break; } case OMX_QcomIndexParamVideoDecoderPictureOrder: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_DECODER_PICTURE_ORDER); QOMX_VIDEO_DECODER_PICTURE_ORDER *pictureOrder = (QOMX_VIDEO_DECODER_PICTURE_ORDER *)paramData; struct v4l2_control control; int pic_order,rc=0; DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamVideoDecoderPictureOrder %d", pictureOrder->eOutputPictureOrder); if (pictureOrder->eOutputPictureOrder == QOMX_VIDEO_DISPLAY_ORDER) { pic_order = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DISPLAY; } else if (pictureOrder->eOutputPictureOrder == QOMX_VIDEO_DECODE_ORDER) { pic_order = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE; time_stamp_dts.set_timestamp_reorder_mode(false); } else eRet = OMX_ErrorBadParameter; if (eRet == OMX_ErrorNone) { control.id = V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER; control.value = pic_order; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Set picture order failed"); eRet = OMX_ErrorUnsupportedSetting; } } break; } case OMX_QcomIndexParamConcealMBMapExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(VDEC_EXTRADATA_MB_ERROR_MAP, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamFrameInfoExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_FRAMEINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_ExtraDataFrameDimension: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_FRAMEDIMENSION_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamInterlaceExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_INTERLACE_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamH264TimeInfo: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_TIMEINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoFramePackingExtradata: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_FRAMEPACK_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoQPExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_QP_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoInputBitsInfoExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_BITSINFO_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexEnableExtnUserData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_EXTNUSER_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamMpeg2SeqDispExtraData: VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); eRet = enable_extradata(OMX_MPEG2SEQDISP_EXTRADATA, false, ((QOMX_ENABLETYPE *)paramData)->bEnable); break; case OMX_QcomIndexParamVideoDivx: { QOMX_VIDEO_PARAM_DIVXTYPE* divXType = (QOMX_VIDEO_PARAM_DIVXTYPE *) paramData; } break; case OMX_QcomIndexPlatformPvt: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PLATFORMPRIVATE_EXTN); DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexPlatformPvt OP Port"); OMX_QCOM_PLATFORMPRIVATE_EXTN* entryType = (OMX_QCOM_PLATFORMPRIVATE_EXTN *) paramData; if (entryType->type != OMX_QCOM_PLATFORM_PRIVATE_PMEM) { DEBUG_PRINT_HIGH("set_parameter: Platform Private entry type (%d) not supported.", entryType->type); eRet = OMX_ErrorUnsupportedSetting; } else { m_out_pvt_entry_pmem = OMX_TRUE; if ((m_out_mem_region_smi && m_out_pvt_entry_pmem)) { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexPlatformPvt OP Port: out pmem set"); m_use_output_pmem = OMX_TRUE; } } } break; case OMX_QcomIndexParamVideoSyncFrameDecodingMode: { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamVideoSyncFrameDecodingMode"); DEBUG_PRINT_HIGH("set idr only decoding for thumbnail mode"); struct v4l2_control control; int rc; drv_ctx.idr_only_decoding = 1; control.id = V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER; control.value = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Set picture order failed"); eRet = OMX_ErrorUnsupportedSetting; } else { control.id = V4L2_CID_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE; control.value = V4L2_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE_ENABLE; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc) { DEBUG_PRINT_ERROR("Sync frame setting failed"); eRet = OMX_ErrorUnsupportedSetting; } /*Setting sync frame decoding on driver might change buffer * requirements so update them here*/ if (get_buffer_req(&drv_ctx.ip_buf)) { DEBUG_PRINT_ERROR("Sync frame setting failed: falied to get buffer i/p requirements"); eRet = OMX_ErrorUnsupportedSetting; } if (get_buffer_req(&drv_ctx.op_buf)) { DEBUG_PRINT_ERROR("Sync frame setting failed: falied to get buffer o/p requirements"); eRet = OMX_ErrorUnsupportedSetting; } } } break; case OMX_QcomIndexParamIndexExtraDataType: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXEXTRADATATYPE); QOMX_INDEXEXTRADATATYPE *extradataIndexType = (QOMX_INDEXEXTRADATATYPE *) paramData; if ((extradataIndexType->nIndex == OMX_IndexParamPortDefinition) && (extradataIndexType->bEnabled == OMX_TRUE) && (extradataIndexType->nPortIndex == 1)) { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamIndexExtraDataType SmoothStreaming"); eRet = enable_extradata(OMX_PORTDEF_EXTRADATA, false, extradataIndexType->bEnabled); } } break; case OMX_QcomIndexParamEnableSmoothStreaming: { #ifndef SMOOTH_STREAMING_DISABLED eRet = enable_smoothstreaming(); #else eRet = OMX_ErrorUnsupportedSetting; #endif } break; #if defined (_ANDROID_HONEYCOMB_) || defined (_ANDROID_ICS_) /* Need to allow following two set_parameters even in Idle * state. This is ANDROID architecture which is not in sync * with openmax standard. */ case OMX_GoogleAndroidIndexEnableAndroidNativeBuffers: { VALIDATE_OMX_PARAM_DATA(paramData, EnableAndroidNativeBuffersParams); EnableAndroidNativeBuffersParams* enableNativeBuffers = (EnableAndroidNativeBuffersParams *) paramData; if (enableNativeBuffers) { m_enable_android_native_buffers = enableNativeBuffers->enable; } #if !defined(FLEXYUV_SUPPORTED) if (m_enable_android_native_buffers) { if(!client_buffers.set_color_format(getPreferredColorFormatDefaultMode(0))) { DEBUG_PRINT_ERROR("Failed to set native color format!"); eRet = OMX_ErrorUnsupportedSetting; } } #endif } break; case OMX_GoogleAndroidIndexUseAndroidNativeBuffer: { VALIDATE_OMX_PARAM_DATA(paramData, UseAndroidNativeBufferParams); eRet = use_android_native_buffer(hComp, paramData); } break; #endif case OMX_QcomIndexParamEnableTimeStampReorder: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXTIMESTAMPREORDER); QOMX_INDEXTIMESTAMPREORDER *reorder = (QOMX_INDEXTIMESTAMPREORDER *)paramData; if (drv_ctx.picture_order == (vdec_output_order)QOMX_VIDEO_DISPLAY_ORDER) { if (reorder->bEnable == OMX_TRUE) { frm_int =0; time_stamp_dts.set_timestamp_reorder_mode(true); } else time_stamp_dts.set_timestamp_reorder_mode(false); } else { time_stamp_dts.set_timestamp_reorder_mode(false); if (reorder->bEnable == OMX_TRUE) { eRet = OMX_ErrorUnsupportedSetting; } } } break; case OMX_IndexParamVideoProfileLevelCurrent: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PROFILELEVELTYPE); OMX_VIDEO_PARAM_PROFILELEVELTYPE* pParam = (OMX_VIDEO_PARAM_PROFILELEVELTYPE*)paramData; if (pParam) { m_profile_lvl.eProfile = pParam->eProfile; m_profile_lvl.eLevel = pParam->eLevel; } break; } case OMX_QcomIndexParamVideoMetaBufferMode: { VALIDATE_OMX_PARAM_DATA(paramData, StoreMetaDataInBuffersParams); StoreMetaDataInBuffersParams *metabuffer = (StoreMetaDataInBuffersParams *)paramData; if (!metabuffer) { DEBUG_PRINT_ERROR("Invalid param: %p", metabuffer); eRet = OMX_ErrorBadParameter; break; } if (m_disable_dynamic_buf_mode) { DEBUG_PRINT_HIGH("Dynamic buffer mode disabled by setprop"); eRet = OMX_ErrorUnsupportedSetting; break; } if (metabuffer->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { struct v4l2_control control; struct v4l2_format fmt; control.id = V4L2_CID_MPEG_VIDC_VIDEO_ALLOC_MODE_OUTPUT; if (metabuffer->bStoreMetaData == true) { control.value = V4L2_MPEG_VIDC_VIDEO_DYNAMIC; } else { control.value = V4L2_MPEG_VIDC_VIDEO_STATIC; } int rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL,&control); if (!rc) { DEBUG_PRINT_HIGH("%s buffer mode", (metabuffer->bStoreMetaData == true)? "Enabled dynamic" : "Disabled dynamic"); dynamic_buf_mode = metabuffer->bStoreMetaData; } else { DEBUG_PRINT_ERROR("Failed to %s buffer mode", (metabuffer->bStoreMetaData == true)? "enable dynamic" : "disable dynamic"); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR( "OMX_QcomIndexParamVideoMetaBufferMode not supported for port: %u", (unsigned int)metabuffer->nPortIndex); eRet = OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamVideoDownScalar: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXDOWNSCALAR); QOMX_INDEXDOWNSCALAR* pParam = (QOMX_INDEXDOWNSCALAR*)paramData; struct v4l2_control control; int rc; if (pParam) { is_down_scalar_enabled = pParam->bEnable; if (is_down_scalar_enabled) { control.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE; control.value = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_SECONDARY; DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoDownScalar value = %d", pParam->bEnable); rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc < 0) { DEBUG_PRINT_ERROR("Failed to set down scalar on driver."); eRet = OMX_ErrorUnsupportedSetting; } control.id = V4L2_CID_MPEG_VIDC_VIDEO_KEEP_ASPECT_RATIO; control.value = 1; rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control); if (rc < 0) { DEBUG_PRINT_ERROR("Failed to set keep aspect ratio on driver."); eRet = OMX_ErrorUnsupportedSetting; } } } break; } #ifdef ADAPTIVE_PLAYBACK_SUPPORTED case OMX_QcomIndexParamVideoAdaptivePlaybackMode: { VALIDATE_OMX_PARAM_DATA(paramData, PrepareForAdaptivePlaybackParams); DEBUG_PRINT_LOW("set_parameter: OMX_GoogleAndroidIndexPrepareForAdaptivePlayback"); PrepareForAdaptivePlaybackParams* pParams = (PrepareForAdaptivePlaybackParams *) paramData; if (pParams->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { if (!pParams->bEnable) { return OMX_ErrorNone; } if (pParams->nMaxFrameWidth > maxSmoothStreamingWidth || pParams->nMaxFrameHeight > maxSmoothStreamingHeight) { DEBUG_PRINT_ERROR( "Adaptive playback request exceeds max supported resolution : [%u x %u] vs [%u x %u]", (unsigned int)pParams->nMaxFrameWidth, (unsigned int)pParams->nMaxFrameHeight, (unsigned int)maxSmoothStreamingWidth, (unsigned int)maxSmoothStreamingHeight); eRet = OMX_ErrorBadParameter; } else { eRet = enable_adaptive_playback(pParams->nMaxFrameWidth, pParams->nMaxFrameHeight); } } else { DEBUG_PRINT_ERROR( "Prepare for adaptive playback supported only on output port"); eRet = OMX_ErrorBadParameter; } break; } #endif case OMX_QcomIndexParamVideoCustomBufferSize: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_CUSTOM_BUFFERSIZE); DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoCustomBufferSize"); QOMX_VIDEO_CUSTOM_BUFFERSIZE* pParam = (QOMX_VIDEO_CUSTOM_BUFFERSIZE*)paramData; if (pParam->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) { struct v4l2_control control; control.id = V4L2_CID_MPEG_VIDC_VIDEO_BUFFER_SIZE_LIMIT; control.value = pParam->nBufferSize; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) { DEBUG_PRINT_ERROR("Failed to set input buffer size"); eRet = OMX_ErrorUnsupportedSetting; } else { eRet = get_buffer_req(&drv_ctx.ip_buf); if (eRet == OMX_ErrorNone) { m_custom_buffersize.input_buffersize = drv_ctx.ip_buf.buffer_size; DEBUG_PRINT_HIGH("Successfully set custom input buffer size = %d", m_custom_buffersize.input_buffersize); } else { DEBUG_PRINT_ERROR("Failed to get buffer requirement"); } } } else { DEBUG_PRINT_ERROR("ERROR: Custom buffer size in not supported on output port"); eRet = OMX_ErrorBadParameter; } break; } default: { DEBUG_PRINT_ERROR("Setparameter: unknown param %d", paramIndex); eRet = OMX_ErrorUnsupportedIndex; } } if (eRet != OMX_ErrorNone) DEBUG_PRINT_ERROR("set_parameter: Error: 0x%x, setting param 0x%x", eRet, paramIndex); return eRet; }
173,791
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: qedi_dbg_info(struct qedi_dbg_ctx *qedi, const char *func, u32 line, u32 level, const char *fmt, ...) { va_list va; struct va_format vaf; char nfunc[32]; memset(nfunc, 0, sizeof(nfunc)); memcpy(nfunc, func, sizeof(nfunc) - 1); va_start(va, fmt); vaf.fmt = fmt; vaf.va = &va; if (!(qedi_dbg_log & level)) goto ret; if (likely(qedi) && likely(qedi->pdev)) pr_info("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev), nfunc, line, qedi->host_no, &vaf); else pr_info("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf); ret: va_end(va); } Commit Message: scsi: qedi: remove memset/memcpy to nfunc and use func instead KASAN reports this: BUG: KASAN: global-out-of-bounds in qedi_dbg_err+0xda/0x330 [qedi] Read of size 31 at addr ffffffffc12b0ae0 by task syz-executor.0/2429 CPU: 0 PID: 2429 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 print_address_description+0x1c4/0x270 mm/kasan/report.c:187 kasan_report+0x149/0x18d mm/kasan/report.c:317 memcpy+0x1f/0x50 mm/kasan/common.c:130 qedi_dbg_err+0xda/0x330 [qedi] ? 0xffffffffc12d0000 qedi_init+0x118/0x1000 [qedi] ? 0xffffffffc12d0000 ? 0xffffffffc12d0000 ? 0xffffffffc12d0000 do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f2d57e55c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bfa0 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 00000000200003c0 RDI: 0000000000000003 RBP: 00007f2d57e55c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f2d57e566bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 The buggy address belongs to the variable: __func__.67584+0x0/0xffffffffffffd520 [qedi] Memory state around the buggy address: ffffffffc12b0980: fa fa fa fa 00 04 fa fa fa fa fa fa 00 00 05 fa ffffffffc12b0a00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 05 fa fa > ffffffffc12b0a80: fa fa fa fa 00 06 fa fa fa fa fa fa 00 02 fa fa ^ ffffffffc12b0b00: fa fa fa fa 00 00 04 fa fa fa fa fa 00 00 03 fa ffffffffc12b0b80: fa fa fa fa 00 00 02 fa fa fa fa fa 00 00 04 fa Currently the qedi_dbg_* family of functions can overrun the end of the source string if it is less than the destination buffer length because of the use of a fixed sized memcpy. Remove the memset/memcpy calls to nfunc and just use func instead as it is always a null terminated string. Reported-by: Hulk Robot <[email protected]> Fixes: ace7f46ba5fd ("scsi: qedi: Add QLogic FastLinQ offload iSCSI driver framework.") Signed-off-by: YueHaibing <[email protected]> Reviewed-by: Dan Carpenter <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: CWE-125
qedi_dbg_info(struct qedi_dbg_ctx *qedi, const char *func, u32 line, u32 level, const char *fmt, ...) { va_list va; struct va_format vaf; va_start(va, fmt); vaf.fmt = fmt; vaf.va = &va; if (!(qedi_dbg_log & level)) goto ret; if (likely(qedi) && likely(qedi->pdev)) pr_info("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev), func, line, qedi->host_no, &vaf); else pr_info("[0000:00:00.0]:[%s:%d]: %pV", func, line, &vaf); ret: va_end(va); }
169,559
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_expand_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit * depth is at least 8 already. */ return (colour_type & PNG_COLOR_MASK_ALPHA) == 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit * depth is at least 8 already. */ return (colour_type & PNG_COLOR_MASK_ALPHA) == 0; }
173,629
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t MPEG4Extractor::parse3GPPMetaData(off64_t offset, size_t size, int depth) { if (size < 4 || size == SIZE_MAX) { return ERROR_MALFORMED; } uint8_t *buffer = new (std::nothrow) uint8_t[size + 1]; if (buffer == NULL) { return ERROR_MALFORMED; } if (mDataSource->readAt( offset, buffer, size) != (ssize_t)size) { delete[] buffer; buffer = NULL; return ERROR_IO; } uint32_t metadataKey = 0; switch (mPath[depth]) { case FOURCC('t', 'i', 't', 'l'): { metadataKey = kKeyTitle; break; } case FOURCC('p', 'e', 'r', 'f'): { metadataKey = kKeyArtist; break; } case FOURCC('a', 'u', 't', 'h'): { metadataKey = kKeyWriter; break; } case FOURCC('g', 'n', 'r', 'e'): { metadataKey = kKeyGenre; break; } case FOURCC('a', 'l', 'b', 'm'): { if (buffer[size - 1] != '\0') { char tmp[4]; sprintf(tmp, "%u", buffer[size - 1]); mFileMetaData->setCString(kKeyCDTrackNumber, tmp); } metadataKey = kKeyAlbum; break; } case FOURCC('y', 'r', 'r', 'c'): { char tmp[5]; uint16_t year = U16_AT(&buffer[4]); if (year < 10000) { sprintf(tmp, "%u", year); mFileMetaData->setCString(kKeyYear, tmp); } break; } default: break; } if (metadataKey > 0) { bool isUTF8 = true; // Common case char16_t *framedata = NULL; int len16 = 0; // Number of UTF-16 characters if (size - 6 >= 4) { len16 = ((size - 6) / 2) - 1; // don't include 0x0000 terminator framedata = (char16_t *)(buffer + 6); if (0xfffe == *framedata) { for (int i = 0; i < len16; i++) { framedata[i] = bswap_16(framedata[i]); } } if (0xfeff == *framedata) { framedata++; len16--; isUTF8 = false; } } if (isUTF8) { buffer[size] = 0; mFileMetaData->setCString(metadataKey, (const char *)buffer + 6); } else { String8 tmpUTF8str(framedata, len16); mFileMetaData->setCString(metadataKey, tmpUTF8str.string()); } } delete[] buffer; buffer = NULL; return OK; } Commit Message: Prevent integer underflow if size is below 6 When processing 3GPP metadata, a subtraction operation may underflow and lead to a rather large linear byteswap operation in the subsequent framedata decoding code. Bound the 'size' value to prevent this from occurring. Bug: 20923261 Change-Id: I35dfbc8878c6b65cfe8b8adb7351a77ad4d604e5 (cherry picked from commit 9458e715d391ee8fe455fc31f07ff35ce12e0531) CWE ID: CWE-119
status_t MPEG4Extractor::parse3GPPMetaData(off64_t offset, size_t size, int depth) { if (size < 4 || size == SIZE_MAX) { return ERROR_MALFORMED; } uint8_t *buffer = new (std::nothrow) uint8_t[size + 1]; if (buffer == NULL) { return ERROR_MALFORMED; } if (mDataSource->readAt( offset, buffer, size) != (ssize_t)size) { delete[] buffer; buffer = NULL; return ERROR_IO; } uint32_t metadataKey = 0; switch (mPath[depth]) { case FOURCC('t', 'i', 't', 'l'): { metadataKey = kKeyTitle; break; } case FOURCC('p', 'e', 'r', 'f'): { metadataKey = kKeyArtist; break; } case FOURCC('a', 'u', 't', 'h'): { metadataKey = kKeyWriter; break; } case FOURCC('g', 'n', 'r', 'e'): { metadataKey = kKeyGenre; break; } case FOURCC('a', 'l', 'b', 'm'): { if (buffer[size - 1] != '\0') { char tmp[4]; sprintf(tmp, "%u", buffer[size - 1]); mFileMetaData->setCString(kKeyCDTrackNumber, tmp); } metadataKey = kKeyAlbum; break; } case FOURCC('y', 'r', 'r', 'c'): { char tmp[5]; uint16_t year = U16_AT(&buffer[4]); if (year < 10000) { sprintf(tmp, "%u", year); mFileMetaData->setCString(kKeyYear, tmp); } break; } default: break; } if (metadataKey > 0) { bool isUTF8 = true; // Common case char16_t *framedata = NULL; int len16 = 0; // Number of UTF-16 characters if (size < 6) { return ERROR_MALFORMED; } if (size - 6 >= 4) { len16 = ((size - 6) / 2) - 1; // don't include 0x0000 terminator framedata = (char16_t *)(buffer + 6); if (0xfffe == *framedata) { for (int i = 0; i < len16; i++) { framedata[i] = bswap_16(framedata[i]); } } if (0xfeff == *framedata) { framedata++; len16--; isUTF8 = false; } } if (isUTF8) { buffer[size] = 0; mFileMetaData->setCString(metadataKey, (const char *)buffer + 6); } else { String8 tmpUTF8str(framedata, len16); mFileMetaData->setCString(metadataKey, tmpUTF8str.string()); } } delete[] buffer; buffer = NULL; return OK; }
173,367
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev, struct ib_udata *udata) { int ret = 0; struct hns_roce_ucontext *context; struct hns_roce_ib_alloc_ucontext_resp resp; struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); resp.qp_tab_size = hr_dev->caps.num_qps; context = kmalloc(sizeof(*context), GFP_KERNEL); if (!context) return ERR_PTR(-ENOMEM); ret = hns_roce_uar_alloc(hr_dev, &context->uar); if (ret) goto error_fail_uar_alloc; if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) { INIT_LIST_HEAD(&context->page_list); mutex_init(&context->page_mutex); } ret = ib_copy_to_udata(udata, &resp, sizeof(resp)); if (ret) goto error_fail_copy_to_udata; return &context->ibucontext; error_fail_copy_to_udata: hns_roce_uar_free(hr_dev, &context->uar); error_fail_uar_alloc: kfree(context); return ERR_PTR(ret); } Commit Message: RDMA/hns: Fix init resp when alloc ucontext The data in resp will be copied from kernel to userspace, thus it needs to be initialized to zeros to avoid copying uninited stack memory. Reported-by: Dan Carpenter <[email protected]> Fixes: e088a685eae9 ("RDMA/hns: Support rq record doorbell for the user space") Signed-off-by: Yixian Liu <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> CWE ID: CWE-665
static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev, struct ib_udata *udata) { int ret = 0; struct hns_roce_ucontext *context; struct hns_roce_ib_alloc_ucontext_resp resp = {}; struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); resp.qp_tab_size = hr_dev->caps.num_qps; context = kmalloc(sizeof(*context), GFP_KERNEL); if (!context) return ERR_PTR(-ENOMEM); ret = hns_roce_uar_alloc(hr_dev, &context->uar); if (ret) goto error_fail_uar_alloc; if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) { INIT_LIST_HEAD(&context->page_list); mutex_init(&context->page_mutex); } ret = ib_copy_to_udata(udata, &resp, sizeof(resp)); if (ret) goto error_fail_copy_to_udata; return &context->ibucontext; error_fail_copy_to_udata: hns_roce_uar_free(hr_dev, &context->uar); error_fail_uar_alloc: kfree(context); return ERR_PTR(ret); }
169,504
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ssl3_send_server_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q; int j, num; RSA *rsa; unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH]; unsigned int u; #endif #ifndef OPENSSL_NO_DH DH *dh = NULL, *dhp; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL, *ecdhp; unsigned char *encodedPoint = NULL; int encodedlen = 0; int curve_id = 0; BN_CTX *bn_ctx = NULL; #endif EVP_PKEY *pkey; const EVP_MD *md = NULL; unsigned char *p, *d; int al, i; unsigned long type; int n; CERT *cert; BIGNUM *r[4]; int nr[4], kn; BUF_MEM *buf; EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); if (s->state == SSL3_ST_SW_KEY_EXCH_A) { type = s->s3->tmp.new_cipher->algorithm_mkey; cert = s->cert; buf = s->init_buf; r[0] = r[1] = r[2] = r[3] = NULL; n = 0; #ifndef OPENSSL_NO_RSA if (type & SSL_kRSA) { rsa = cert->rsa_tmp; if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) { rsa = s->cert->rsa_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_ERROR_GENERATING_TMP_RSA_KEY); goto f_err; } RSA_up_ref(rsa); cert->rsa_tmp = rsa; } if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_RSA_KEY); goto f_err; } r[0] = rsa->n; r[1] = rsa->e; s->s3->tmp.use_rsa_tmp = 1; } else #endif #ifndef OPENSSL_NO_DH if (type & SSL_kEDH) { dhp = cert->dh_tmp; if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL)) dhp = s->cert->dh_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (dhp == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_DH_KEY); goto f_err; } if (s->s3->tmp.dh != NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((dh = DHparams_dup(dhp)) == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } s->s3->tmp.dh = dh; if ((dhp->pub_key == NULL || dhp->priv_key == NULL || (s->options & SSL_OP_SINGLE_DH_USE))) { if (!DH_generate_key(dh)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } else { dh->pub_key = BN_dup(dhp->pub_key); dh->priv_key = BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } r[0] = dh->p; r[1] = dh->g; } } else { dh->pub_key = BN_dup(dhp->pub_key); dh->priv_key = BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } r[0] = dh->p; r[1] = dh->g; r[2] = dh->pub_key; } else Commit Message: CWE ID: CWE-200
int ssl3_send_server_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q; int j, num; RSA *rsa; unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH]; unsigned int u; #endif #ifndef OPENSSL_NO_DH DH *dh = NULL, *dhp; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL, *ecdhp; unsigned char *encodedPoint = NULL; int encodedlen = 0; int curve_id = 0; BN_CTX *bn_ctx = NULL; #endif EVP_PKEY *pkey; const EVP_MD *md = NULL; unsigned char *p, *d; int al, i; unsigned long type; int n; CERT *cert; BIGNUM *r[4]; int nr[4], kn; BUF_MEM *buf; EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); if (s->state == SSL3_ST_SW_KEY_EXCH_A) { type = s->s3->tmp.new_cipher->algorithm_mkey; cert = s->cert; buf = s->init_buf; r[0] = r[1] = r[2] = r[3] = NULL; n = 0; #ifndef OPENSSL_NO_RSA if (type & SSL_kRSA) { rsa = cert->rsa_tmp; if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) { rsa = s->cert->rsa_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_ERROR_GENERATING_TMP_RSA_KEY); goto f_err; } RSA_up_ref(rsa); cert->rsa_tmp = rsa; } if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_RSA_KEY); goto f_err; } r[0] = rsa->n; r[1] = rsa->e; s->s3->tmp.use_rsa_tmp = 1; } else #endif #ifndef OPENSSL_NO_DH if (type & SSL_kEDH) { dhp = cert->dh_tmp; if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL)) dhp = s->cert->dh_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (dhp == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_DH_KEY); goto f_err; } if (s->s3->tmp.dh != NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((dh = DHparams_dup(dhp)) == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } s->s3->tmp.dh = dh; if (!DH_generate_key(dh)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } r[0] = dh->p; r[1] = dh->g; } } else { dh->pub_key = BN_dup(dhp->pub_key); dh->priv_key = BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } r[0] = dh->p; r[1] = dh->g; r[2] = dh->pub_key; } else
165,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { goto error; } box->ops = &jp2_boxinfo_unk.ops; if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->ops = &boxinfo->ops; box->len = len; if (box->len == 1) { if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; } Commit Message: Fixed a bug that resulted in the destruction of JP2 box data that had never been constructed in the first place. CWE ID: CWE-476
jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { goto error; } box->ops = &jp2_boxinfo_unk.ops; if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->ops = &boxinfo->ops; box->len = len; JAS_DBGLOG(10, ( "preliminary processing of JP2 box: type=%c%s%c (0x%08x); length=%d\n", '"', boxinfo->name, '"', box->type, box->len )); if (box->len == 1) { if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { // Mark the box data as never having been constructed // so that we will not errantly attempt to destroy it later. box->ops = &jp2_boxinfo_unk.ops; jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; }
168,753
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FragmentPaintPropertyTreeBuilder::UpdateClipPathClip( bool spv1_compositing_specific_pass) { bool is_spv1_composited = object_.HasLayer() && ToLayoutBoxModelObject(object_).Layer()->GetCompositedLayerMapping(); if (is_spv1_composited != spv1_compositing_specific_pass) return; if (NeedsPaintPropertyUpdate()) { if (!NeedsClipPathClip(object_)) { OnClearClip(properties_->ClearClipPathClip()); } else { ClipPaintPropertyNode::State state; state.local_transform_space = context_.current.transform; state.clip_rect = FloatRoundedRect(FloatRect(*fragment_data_.ClipPathBoundingBox())); state.clip_path = fragment_data_.ClipPathPath(); OnUpdateClip(properties_->UpdateClipPathClip(context_.current.clip, std::move(state))); } } if (properties_->ClipPathClip() && !spv1_compositing_specific_pass) { context_.current.clip = context_.absolute_position.clip = context_.fixed_position.clip = properties_->ClipPathClip(); } } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
void FragmentPaintPropertyTreeBuilder::UpdateClipPathClip( bool spv1_compositing_specific_pass) { bool is_spv1_composited = object_.HasLayer() && ToLayoutBoxModelObject(object_).Layer()->GetCompositedLayerMapping(); if (is_spv1_composited != spv1_compositing_specific_pass) return; if (NeedsPaintPropertyUpdate()) { if (!NeedsClipPathClip(object_)) { OnClearClip(properties_->ClearClipPathClip()); } else { ClipPaintPropertyNode::State state; state.local_transform_space = context_.current.transform; state.clip_rect = FloatRoundedRect(FloatRect(*fragment_data_.ClipPathBoundingBox())); state.clip_path = fragment_data_.ClipPathPath(); OnUpdateClip(properties_->UpdateClipPathClip(*context_.current.clip, std::move(state))); } } if (properties_->ClipPathClip() && !spv1_compositing_specific_pass) { context_.current.clip = context_.absolute_position.clip = context_.fixed_position.clip = properties_->ClipPathClip(); } }
171,793
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: UINT CSoundFile::ReadSample(MODINSTRUMENT *pIns, UINT nFlags, LPCSTR lpMemFile, DWORD dwMemLength) { UINT len = 0, mem = pIns->nLength+6; if ((!pIns) || (pIns->nLength < 4) || (!lpMemFile)) return 0; if (pIns->nLength > MAX_SAMPLE_LENGTH) pIns->nLength = MAX_SAMPLE_LENGTH; pIns->uFlags &= ~(CHN_16BIT|CHN_STEREO); if (nFlags & RSF_16BIT) { mem *= 2; pIns->uFlags |= CHN_16BIT; } if (nFlags & RSF_STEREO) { mem *= 2; pIns->uFlags |= CHN_STEREO; } if ((pIns->pSample = AllocateSample(mem)) == NULL) { pIns->nLength = 0; return 0; } switch(nFlags) { case RS_PCM8U: { len = pIns->nLength; if (len > dwMemLength) len = pIns->nLength = dwMemLength; signed char *pSample = pIns->pSample; for (UINT j=0; j<len; j++) pSample[j] = (signed char)(lpMemFile[j] - 0x80); } break; case RS_PCM8D: { len = pIns->nLength; if (len > dwMemLength) break; signed char *pSample = pIns->pSample; const signed char *p = (const signed char *)lpMemFile; int delta = 0; for (UINT j=0; j<len; j++) { delta += p[j]; *pSample++ = (signed char)delta; } } break; case RS_ADPCM4: { len = (pIns->nLength + 1) / 2; if (len > dwMemLength - 16) break; memcpy(CompressionTable, lpMemFile, 16); lpMemFile += 16; signed char *pSample = pIns->pSample; signed char delta = 0; for (UINT j=0; j<len; j++) { BYTE b0 = (BYTE)lpMemFile[j]; BYTE b1 = (BYTE)(lpMemFile[j] >> 4); delta = (signed char)GetDeltaValue((int)delta, b0); pSample[0] = delta; delta = (signed char)GetDeltaValue((int)delta, b1); pSample[1] = delta; pSample += 2; } len += 16; } break; case RS_PCM16D: { len = pIns->nLength * 2; if (len > dwMemLength) break; short int *pSample = (short int *)pIns->pSample; short int *p = (short int *)lpMemFile; int delta16 = 0; for (UINT j=0; j<len; j+=2) { delta16 += bswapLE16(*p++); *pSample++ = (short int)delta16; } } break; case RS_PCM16S: { len = pIns->nLength * 2; if (len <= dwMemLength) memcpy(pIns->pSample, lpMemFile, len); short int *pSample = (short int *)pIns->pSample; for (UINT j=0; j<len; j+=2) { short int s = bswapLE16(*pSample); *pSample++ = s; } } break; case RS_PCM16M: len = pIns->nLength * 2; if (len > dwMemLength) len = dwMemLength & ~1; if (len > 1) { signed char *pSample = (signed char *)pIns->pSample; signed char *pSrc = (signed char *)lpMemFile; for (UINT j=0; j<len; j+=2) { *((unsigned short *)(pSample+j)) = bswapBE16(*((unsigned short *)(pSrc+j))); } } break; case RS_PCM16U: { len = pIns->nLength * 2; if (len > dwMemLength) break; short int *pSample = (short int *)pIns->pSample; short int *pSrc = (short int *)lpMemFile; for (UINT j=0; j<len; j+=2) *pSample++ = bswapLE16(*(pSrc++)) - 0x8000; } break; case RS_STPCM16M: len = pIns->nLength * 2; if (len*2 <= dwMemLength) { signed char *pSample = (signed char *)pIns->pSample; signed char *pSrc = (signed char *)lpMemFile; for (UINT j=0; j<len; j+=2) { *((unsigned short *)(pSample+j*2)) = bswapBE16(*((unsigned short *)(pSrc+j))); *((unsigned short *)(pSample+j*2+2)) = bswapBE16(*((unsigned short *)(pSrc+j+len))); } len *= 2; } break; case RS_STPCM8S: case RS_STPCM8U: case RS_STPCM8D: { int iadd_l = 0, iadd_r = 0; if (nFlags == RS_STPCM8U) { iadd_l = iadd_r = -128; } len = pIns->nLength; signed char *psrc = (signed char *)lpMemFile; signed char *pSample = (signed char *)pIns->pSample; if (len*2 > dwMemLength) break; for (UINT j=0; j<len; j++) { pSample[j*2] = (signed char)(psrc[0] + iadd_l); pSample[j*2+1] = (signed char)(psrc[len] + iadd_r); psrc++; if (nFlags == RS_STPCM8D) { iadd_l = pSample[j*2]; iadd_r = pSample[j*2+1]; } } len *= 2; } break; case RS_STPCM16S: case RS_STPCM16U: case RS_STPCM16D: { int iadd_l = 0, iadd_r = 0; if (nFlags == RS_STPCM16U) { iadd_l = iadd_r = -0x8000; } len = pIns->nLength; short int *psrc = (short int *)lpMemFile; short int *pSample = (short int *)pIns->pSample; if (len*4 > dwMemLength) break; for (UINT j=0; j<len; j++) { pSample[j*2] = (short int) (bswapLE16(psrc[0]) + iadd_l); pSample[j*2+1] = (short int) (bswapLE16(psrc[len]) + iadd_r); psrc++; if (nFlags == RS_STPCM16D) { iadd_l = pSample[j*2]; iadd_r = pSample[j*2+1]; } } len *= 4; } break; case RS_IT2148: case RS_IT21416: case RS_IT2158: case RS_IT21516: len = dwMemLength; if (len < 4) break; if ((nFlags == RS_IT2148) || (nFlags == RS_IT2158)) ITUnpack8Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT2158)); else ITUnpack16Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT21516)); break; #ifndef MODPLUG_BASIC_SUPPORT #ifndef FASTSOUNDLIB case RS_STIPCM8S: case RS_STIPCM8U: { int iadd = 0; if (nFlags == RS_STIPCM8U) { iadd = -0x80; } len = pIns->nLength; if (len*2 > dwMemLength) len = dwMemLength >> 1; LPBYTE psrc = (LPBYTE)lpMemFile; LPBYTE pSample = (LPBYTE)pIns->pSample; for (UINT j=0; j<len; j++) { pSample[j*2] = (signed char)(psrc[0] + iadd); pSample[j*2+1] = (signed char)(psrc[1] + iadd); psrc+=2; } len *= 2; } break; case RS_STIPCM16S: case RS_STIPCM16U: { int iadd = 0; if (nFlags == RS_STIPCM16U) iadd = -32768; len = pIns->nLength; if (len*4 > dwMemLength) len = dwMemLength >> 2; short int *psrc = (short int *)lpMemFile; short int *pSample = (short int *)pIns->pSample; for (UINT j=0; j<len; j++) { pSample[j*2] = (short int)(bswapLE16(psrc[0]) + iadd); pSample[j*2+1] = (short int)(bswapLE16(psrc[1]) + iadd); psrc += 2; } len *= 4; } break; case RS_AMS8: case RS_AMS16: len = 9; if (dwMemLength > 9) { const char *psrc = lpMemFile; char packcharacter = lpMemFile[8], *pdest = (char *)pIns->pSample; len += bswapLE32(*((LPDWORD)(lpMemFile+4))); if (len > dwMemLength) len = dwMemLength; UINT dmax = pIns->nLength; if (pIns->uFlags & CHN_16BIT) dmax <<= 1; AMSUnpack(psrc+9, len-9, pdest, dmax, packcharacter); } break; case RS_PTM8DTO16: { len = pIns->nLength * 2; if (len > dwMemLength) break; signed char *pSample = (signed char *)pIns->pSample; signed char delta8 = 0; for (UINT j=0; j<len; j++) { delta8 += lpMemFile[j]; *pSample++ = delta8; } WORD *pSampleW = (WORD *)pIns->pSample; for (UINT j=0; j<len; j+=2) // swaparoni! { WORD s = bswapLE16(*pSampleW); *pSampleW++ = s; } } break; case RS_MDL8: case RS_MDL16: len = dwMemLength; if (len >= 4) { LPBYTE pSample = (LPBYTE)pIns->pSample; LPBYTE ibuf = (LPBYTE)lpMemFile; DWORD bitbuf = bswapLE32(*((DWORD *)ibuf)); UINT bitnum = 32; BYTE dlt = 0, lowbyte = 0; ibuf += 4; for (UINT j=0; j<pIns->nLength; j++) { BYTE hibyte; BYTE sign; if (nFlags == RS_MDL16) lowbyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 8); sign = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 1); if (MDLReadBits(bitbuf, bitnum, ibuf, 1)) { hibyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 3); } else { hibyte = 8; while (!MDLReadBits(bitbuf, bitnum, ibuf, 1)) hibyte += 0x10; hibyte += MDLReadBits(bitbuf, bitnum, ibuf, 4); } if (sign) hibyte = ~hibyte; dlt += hibyte; if (nFlags != RS_MDL16) pSample[j] = dlt; else { pSample[j<<1] = lowbyte; pSample[(j<<1)+1] = dlt; } } } break; case RS_DMF8: case RS_DMF16: len = dwMemLength; if (len >= 4) { UINT maxlen = pIns->nLength; if (pIns->uFlags & CHN_16BIT) maxlen <<= 1; LPBYTE ibuf = (LPBYTE)lpMemFile, ibufmax = (LPBYTE)(lpMemFile+dwMemLength); len = DMFUnpack((LPBYTE)pIns->pSample, ibuf, ibufmax, maxlen); } break; #ifdef MODPLUG_TRACKER case RS_PCM24S: case RS_PCM32S: len = pIns->nLength * 3; if (nFlags == RS_PCM32S) len += pIns->nLength; if (len > dwMemLength) break; if (len > 4*8) { UINT slsize = (nFlags == RS_PCM32S) ? 4 : 3; LPBYTE pSrc = (LPBYTE)lpMemFile; LONG max = 255; if (nFlags == RS_PCM32S) pSrc++; for (UINT j=0; j<len; j+=slsize) { LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8; l /= 256; if (l > max) max = l; if (-l > max) max = -l; } max = (max / 128) + 1; signed short *pDest = (signed short *)pIns->pSample; for (UINT k=0; k<len; k+=slsize) { LONG l = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8; *pDest++ = (signed short)(l / max); } } break; case RS_STIPCM24S: case RS_STIPCM32S: len = pIns->nLength * 6; if (nFlags == RS_STIPCM32S) len += pIns->nLength * 2; if (len > dwMemLength) break; if (len > 8*8) { UINT slsize = (nFlags == RS_STIPCM32S) ? 4 : 3; LPBYTE pSrc = (LPBYTE)lpMemFile; LONG max = 255; if (nFlags == RS_STIPCM32S) pSrc++; for (UINT j=0; j<len; j+=slsize) { LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8; l /= 256; if (l > max) max = l; if (-l > max) max = -l; } max = (max / 128) + 1; signed short *pDest = (signed short *)pIns->pSample; for (UINT k=0; k<len; k+=slsize) { LONG lr = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8; k += slsize; LONG ll = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8; pDest[0] = (signed short)ll; pDest[1] = (signed short)lr; pDest += 2; } } break; case RS_STIPCM16M: { len = pIns->nLength; if (len*4 > dwMemLength) len = dwMemLength >> 2; LPCBYTE psrc = (LPCBYTE)lpMemFile; short int *pSample = (short int *)pIns->pSample; for (UINT j=0; j<len; j++) { pSample[j*2] = (signed short)(((UINT)psrc[0] << 8) | (psrc[1])); pSample[j*2+1] = (signed short)(((UINT)psrc[2] << 8) | (psrc[3])); psrc += 4; } len *= 4; } break; #endif // MODPLUG_TRACKER #endif // !FASTSOUNDLIB #endif // !MODPLUG_BASIC_SUPPORT default: len = pIns->nLength; if (len > dwMemLength) len = pIns->nLength = dwMemLength; memcpy(pIns->pSample, lpMemFile, len); } if (len > dwMemLength) { if (pIns->pSample) { pIns->nLength = 0; FreeSample(pIns->pSample); pIns->pSample = NULL; } return 0; } AdjustSampleLoop(pIns); return len; } Commit Message: CWE ID:
UINT CSoundFile::ReadSample(MODINSTRUMENT *pIns, UINT nFlags, LPCSTR lpMemFile, DWORD dwMemLength) { UINT len = 0, mem = pIns->nLength+6; if ((!pIns) || ((int)pIns->nLength < 4) || (!lpMemFile)) return 0; if (pIns->nLength > MAX_SAMPLE_LENGTH) pIns->nLength = MAX_SAMPLE_LENGTH; pIns->uFlags &= ~(CHN_16BIT|CHN_STEREO); if (nFlags & RSF_16BIT) { mem *= 2; pIns->uFlags |= CHN_16BIT; } if (nFlags & RSF_STEREO) { mem *= 2; pIns->uFlags |= CHN_STEREO; } if ((pIns->pSample = AllocateSample(mem)) == NULL) { pIns->nLength = 0; return 0; } switch(nFlags) { case RS_PCM8U: { len = pIns->nLength; if (len > dwMemLength) len = pIns->nLength = dwMemLength; signed char *pSample = pIns->pSample; for (UINT j=0; j<len; j++) pSample[j] = (signed char)(lpMemFile[j] - 0x80); } break; case RS_PCM8D: { len = pIns->nLength; if (len > dwMemLength) break; signed char *pSample = pIns->pSample; const signed char *p = (const signed char *)lpMemFile; int delta = 0; for (UINT j=0; j<len; j++) { delta += p[j]; *pSample++ = (signed char)delta; } } break; case RS_ADPCM4: { len = (pIns->nLength + 1) / 2; if (len > dwMemLength - 16) break; memcpy(CompressionTable, lpMemFile, 16); lpMemFile += 16; signed char *pSample = pIns->pSample; signed char delta = 0; for (UINT j=0; j<len; j++) { BYTE b0 = (BYTE)lpMemFile[j]; BYTE b1 = (BYTE)(lpMemFile[j] >> 4); delta = (signed char)GetDeltaValue((int)delta, b0); pSample[0] = delta; delta = (signed char)GetDeltaValue((int)delta, b1); pSample[1] = delta; pSample += 2; } len += 16; } break; case RS_PCM16D: { len = pIns->nLength * 2; if (len > dwMemLength) break; short int *pSample = (short int *)pIns->pSample; short int *p = (short int *)lpMemFile; int delta16 = 0; for (UINT j=0; j<len; j+=2) { delta16 += bswapLE16(*p++); *pSample++ = (short int)delta16; } } break; case RS_PCM16S: { len = pIns->nLength * 2; if (len <= dwMemLength) memcpy(pIns->pSample, lpMemFile, len); short int *pSample = (short int *)pIns->pSample; for (UINT j=0; j<len; j+=2) { short int s = bswapLE16(*pSample); *pSample++ = s; } } break; case RS_PCM16M: len = pIns->nLength * 2; if (len > dwMemLength) len = dwMemLength & ~1; if (len > 1) { signed char *pSample = (signed char *)pIns->pSample; signed char *pSrc = (signed char *)lpMemFile; for (UINT j=0; j<len; j+=2) { *((unsigned short *)(pSample+j)) = bswapBE16(*((unsigned short *)(pSrc+j))); } } break; case RS_PCM16U: { len = pIns->nLength * 2; if (len > dwMemLength) break; short int *pSample = (short int *)pIns->pSample; short int *pSrc = (short int *)lpMemFile; for (UINT j=0; j<len; j+=2) *pSample++ = bswapLE16(*(pSrc++)) - 0x8000; } break; case RS_STPCM16M: len = pIns->nLength * 2; if (len*2 <= dwMemLength) { signed char *pSample = (signed char *)pIns->pSample; signed char *pSrc = (signed char *)lpMemFile; for (UINT j=0; j<len; j+=2) { *((unsigned short *)(pSample+j*2)) = bswapBE16(*((unsigned short *)(pSrc+j))); *((unsigned short *)(pSample+j*2+2)) = bswapBE16(*((unsigned short *)(pSrc+j+len))); } len *= 2; } break; case RS_STPCM8S: case RS_STPCM8U: case RS_STPCM8D: { int iadd_l = 0, iadd_r = 0; if (nFlags == RS_STPCM8U) { iadd_l = iadd_r = -128; } len = pIns->nLength; signed char *psrc = (signed char *)lpMemFile; signed char *pSample = (signed char *)pIns->pSample; if (len*2 > dwMemLength) break; for (UINT j=0; j<len; j++) { pSample[j*2] = (signed char)(psrc[0] + iadd_l); pSample[j*2+1] = (signed char)(psrc[len] + iadd_r); psrc++; if (nFlags == RS_STPCM8D) { iadd_l = pSample[j*2]; iadd_r = pSample[j*2+1]; } } len *= 2; } break; case RS_STPCM16S: case RS_STPCM16U: case RS_STPCM16D: { int iadd_l = 0, iadd_r = 0; if (nFlags == RS_STPCM16U) { iadd_l = iadd_r = -0x8000; } len = pIns->nLength; short int *psrc = (short int *)lpMemFile; short int *pSample = (short int *)pIns->pSample; if (len*4 > dwMemLength) break; for (UINT j=0; j<len; j++) { pSample[j*2] = (short int) (bswapLE16(psrc[0]) + iadd_l); pSample[j*2+1] = (short int) (bswapLE16(psrc[len]) + iadd_r); psrc++; if (nFlags == RS_STPCM16D) { iadd_l = pSample[j*2]; iadd_r = pSample[j*2+1]; } } len *= 4; } break; case RS_IT2148: case RS_IT21416: case RS_IT2158: case RS_IT21516: len = dwMemLength; if (len < 4) break; if ((nFlags == RS_IT2148) || (nFlags == RS_IT2158)) ITUnpack8Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT2158)); else ITUnpack16Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT21516)); break; #ifndef MODPLUG_BASIC_SUPPORT #ifndef FASTSOUNDLIB case RS_STIPCM8S: case RS_STIPCM8U: { int iadd = 0; if (nFlags == RS_STIPCM8U) { iadd = -0x80; } len = pIns->nLength; if (len*2 > dwMemLength) len = dwMemLength >> 1; LPBYTE psrc = (LPBYTE)lpMemFile; LPBYTE pSample = (LPBYTE)pIns->pSample; for (UINT j=0; j<len; j++) { pSample[j*2] = (signed char)(psrc[0] + iadd); pSample[j*2+1] = (signed char)(psrc[1] + iadd); psrc+=2; } len *= 2; } break; case RS_STIPCM16S: case RS_STIPCM16U: { int iadd = 0; if (nFlags == RS_STIPCM16U) iadd = -32768; len = pIns->nLength; if (len*4 > dwMemLength) len = dwMemLength >> 2; short int *psrc = (short int *)lpMemFile; short int *pSample = (short int *)pIns->pSample; for (UINT j=0; j<len; j++) { pSample[j*2] = (short int)(bswapLE16(psrc[0]) + iadd); pSample[j*2+1] = (short int)(bswapLE16(psrc[1]) + iadd); psrc += 2; } len *= 4; } break; case RS_AMS8: case RS_AMS16: len = 9; if (dwMemLength > 9) { const char *psrc = lpMemFile; char packcharacter = lpMemFile[8], *pdest = (char *)pIns->pSample; len += bswapLE32(*((LPDWORD)(lpMemFile+4))); if (len > dwMemLength) len = dwMemLength; UINT dmax = pIns->nLength; if (pIns->uFlags & CHN_16BIT) dmax <<= 1; AMSUnpack(psrc+9, len-9, pdest, dmax, packcharacter); } break; case RS_PTM8DTO16: { len = pIns->nLength * 2; if (len > dwMemLength) break; signed char *pSample = (signed char *)pIns->pSample; signed char delta8 = 0; for (UINT j=0; j<len; j++) { delta8 += lpMemFile[j]; *pSample++ = delta8; } WORD *pSampleW = (WORD *)pIns->pSample; for (UINT j=0; j<len; j+=2) // swaparoni! { WORD s = bswapLE16(*pSampleW); *pSampleW++ = s; } } break; case RS_MDL8: case RS_MDL16: len = dwMemLength; if (len >= 4) { LPBYTE pSample = (LPBYTE)pIns->pSample; LPBYTE ibuf = (LPBYTE)lpMemFile; DWORD bitbuf = bswapLE32(*((DWORD *)ibuf)); UINT bitnum = 32; BYTE dlt = 0, lowbyte = 0; ibuf += 4; for (UINT j=0; j<pIns->nLength; j++) { BYTE hibyte; BYTE sign; if (nFlags == RS_MDL16) lowbyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 8); sign = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 1); if (MDLReadBits(bitbuf, bitnum, ibuf, 1)) { hibyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 3); } else { hibyte = 8; while (!MDLReadBits(bitbuf, bitnum, ibuf, 1)) hibyte += 0x10; hibyte += MDLReadBits(bitbuf, bitnum, ibuf, 4); } if (sign) hibyte = ~hibyte; dlt += hibyte; if (nFlags != RS_MDL16) pSample[j] = dlt; else { pSample[j<<1] = lowbyte; pSample[(j<<1)+1] = dlt; } } } break; case RS_DMF8: case RS_DMF16: len = dwMemLength; if (len >= 4) { UINT maxlen = pIns->nLength; if (pIns->uFlags & CHN_16BIT) maxlen <<= 1; LPBYTE ibuf = (LPBYTE)lpMemFile, ibufmax = (LPBYTE)(lpMemFile+dwMemLength); len = DMFUnpack((LPBYTE)pIns->pSample, ibuf, ibufmax, maxlen); } break; #ifdef MODPLUG_TRACKER case RS_PCM24S: case RS_PCM32S: len = pIns->nLength * 3; if (nFlags == RS_PCM32S) len += pIns->nLength; if (len > dwMemLength) break; if (len > 4*8) { UINT slsize = (nFlags == RS_PCM32S) ? 4 : 3; LPBYTE pSrc = (LPBYTE)lpMemFile; LONG max = 255; if (nFlags == RS_PCM32S) pSrc++; for (UINT j=0; j<len; j+=slsize) { LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8; l /= 256; if (l > max) max = l; if (-l > max) max = -l; } max = (max / 128) + 1; signed short *pDest = (signed short *)pIns->pSample; for (UINT k=0; k<len; k+=slsize) { LONG l = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8; *pDest++ = (signed short)(l / max); } } break; case RS_STIPCM24S: case RS_STIPCM32S: len = pIns->nLength * 6; if (nFlags == RS_STIPCM32S) len += pIns->nLength * 2; if (len > dwMemLength) break; if (len > 8*8) { UINT slsize = (nFlags == RS_STIPCM32S) ? 4 : 3; LPBYTE pSrc = (LPBYTE)lpMemFile; LONG max = 255; if (nFlags == RS_STIPCM32S) pSrc++; for (UINT j=0; j<len; j+=slsize) { LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8; l /= 256; if (l > max) max = l; if (-l > max) max = -l; } max = (max / 128) + 1; signed short *pDest = (signed short *)pIns->pSample; for (UINT k=0; k<len; k+=slsize) { LONG lr = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8; k += slsize; LONG ll = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8; pDest[0] = (signed short)ll; pDest[1] = (signed short)lr; pDest += 2; } } break; case RS_STIPCM16M: { len = pIns->nLength; if (len*4 > dwMemLength) len = dwMemLength >> 2; LPCBYTE psrc = (LPCBYTE)lpMemFile; short int *pSample = (short int *)pIns->pSample; for (UINT j=0; j<len; j++) { pSample[j*2] = (signed short)(((UINT)psrc[0] << 8) | (psrc[1])); pSample[j*2+1] = (signed short)(((UINT)psrc[2] << 8) | (psrc[3])); psrc += 4; } len *= 4; } break; #endif // MODPLUG_TRACKER #endif // !FASTSOUNDLIB #endif // !MODPLUG_BASIC_SUPPORT default: len = pIns->nLength; if (len > dwMemLength) len = pIns->nLength = dwMemLength; memcpy(pIns->pSample, lpMemFile, len); } if (len > dwMemLength) { if (pIns->pSample) { pIns->nLength = 0; FreeSample(pIns->pSample); pIns->pSample = NULL; } return 0; } AdjustSampleLoop(pIns); return len; }
164,930
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ext4_split_extent(handle_t *handle, struct inode *inode, struct ext4_ext_path *path, struct ext4_map_blocks *map, int split_flag, int flags) { ext4_lblk_t ee_block; struct ext4_extent *ex; unsigned int ee_len, depth; int err = 0; int uninitialized; int split_flag1, flags1; depth = ext_depth(inode); ex = path[depth].p_ext; ee_block = le32_to_cpu(ex->ee_block); ee_len = ext4_ext_get_actual_len(ex); uninitialized = ext4_ext_is_uninitialized(ex); if (map->m_lblk + map->m_len < ee_block + ee_len) { split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ? EXT4_EXT_MAY_ZEROOUT : 0; flags1 = flags | EXT4_GET_BLOCKS_PRE_IO; if (uninitialized) split_flag1 |= EXT4_EXT_MARK_UNINIT1 | EXT4_EXT_MARK_UNINIT2; err = ext4_split_extent_at(handle, inode, path, map->m_lblk + map->m_len, split_flag1, flags1); if (err) goto out; } ext4_ext_drop_refs(path); path = ext4_ext_find_extent(inode, map->m_lblk, path); if (IS_ERR(path)) return PTR_ERR(path); if (map->m_lblk >= ee_block) { split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ? EXT4_EXT_MAY_ZEROOUT : 0; if (uninitialized) split_flag1 |= EXT4_EXT_MARK_UNINIT1; if (split_flag & EXT4_EXT_MARK_UNINIT2) split_flag1 |= EXT4_EXT_MARK_UNINIT2; err = ext4_split_extent_at(handle, inode, path, map->m_lblk, split_flag1, flags); if (err) goto out; } ext4_ext_show_leaf(inode, path); out: return err ? err : map->m_len; } Commit Message: ext4: race-condition protection for ext4_convert_unwritten_extents_endio We assumed that at the time we call ext4_convert_unwritten_extents_endio() extent in question is fully inside [map.m_lblk, map->m_len] because it was already split during submission. But this may not be true due to a race between writeback vs fallocate. If extent in question is larger than requested we will split it again. Special precautions should being done if zeroout required because [map.m_lblk, map->m_len] already contains valid data. Signed-off-by: Dmitry Monakhov <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> Cc: [email protected] CWE ID: CWE-362
static int ext4_split_extent(handle_t *handle, struct inode *inode, struct ext4_ext_path *path, struct ext4_map_blocks *map, int split_flag, int flags) { ext4_lblk_t ee_block; struct ext4_extent *ex; unsigned int ee_len, depth; int err = 0; int uninitialized; int split_flag1, flags1; depth = ext_depth(inode); ex = path[depth].p_ext; ee_block = le32_to_cpu(ex->ee_block); ee_len = ext4_ext_get_actual_len(ex); uninitialized = ext4_ext_is_uninitialized(ex); if (map->m_lblk + map->m_len < ee_block + ee_len) { split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT; flags1 = flags | EXT4_GET_BLOCKS_PRE_IO; if (uninitialized) split_flag1 |= EXT4_EXT_MARK_UNINIT1 | EXT4_EXT_MARK_UNINIT2; if (split_flag & EXT4_EXT_DATA_VALID2) split_flag1 |= EXT4_EXT_DATA_VALID1; err = ext4_split_extent_at(handle, inode, path, map->m_lblk + map->m_len, split_flag1, flags1); if (err) goto out; } ext4_ext_drop_refs(path); path = ext4_ext_find_extent(inode, map->m_lblk, path); if (IS_ERR(path)) return PTR_ERR(path); if (map->m_lblk >= ee_block) { split_flag1 = split_flag & (EXT4_EXT_MAY_ZEROOUT | EXT4_EXT_DATA_VALID2); if (uninitialized) split_flag1 |= EXT4_EXT_MARK_UNINIT1; if (split_flag & EXT4_EXT_MARK_UNINIT2) split_flag1 |= EXT4_EXT_MARK_UNINIT2; err = ext4_split_extent_at(handle, inode, path, map->m_lblk, split_flag1, flags); if (err) goto out; } ext4_ext_show_leaf(inode, path); out: return err ? err : map->m_len; }
165,533
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool WebviewHandler::Parse(Extension* extension, base::string16* error) { scoped_ptr<WebviewInfo> info(new WebviewInfo()); const base::DictionaryValue* dict_value = NULL; if (!extension->manifest()->GetDictionary(keys::kWebview, &dict_value)) { *error = base::ASCIIToUTF16(errors::kInvalidWebview); return false; } const base::ListValue* url_list = NULL; if (!dict_value->GetList(keys::kWebviewAccessibleResources, &url_list)) { *error = base::ASCIIToUTF16(errors::kInvalidWebviewAccessibleResourcesList); return false; } for (size_t i = 0; i < url_list->GetSize(); ++i) { std::string relative_path; if (!url_list->GetString(i, &relative_path)) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidWebviewAccessibleResource, base::IntToString(i)); return false; } URLPattern pattern(URLPattern::SCHEME_EXTENSION); if (pattern.Parse(extension->url().spec()) != URLPattern::PARSE_SUCCESS) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidURLPatternError, extension->url().spec()); return false; } while (relative_path[0] == '/') relative_path = relative_path.substr(1, relative_path.length() - 1); pattern.SetPath(pattern.path() + relative_path); info->webview_accessible_resources_.AddPattern(pattern); } const base::ListValue* partition_list = NULL; if (!dict_value->GetList(keys::kWebviewPrivilegedPartitions, &partition_list)) { *error = base::ASCIIToUTF16(errors::kInvalidWebviewPrivilegedPartitionList); return false; } for (size_t i = 0; i < partition_list->GetSize(); ++i) { std::string partition_wildcard; if (!partition_list->GetString(i, &partition_wildcard)) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidWebviewPrivilegedPartition, base::IntToString(i)); return false; } info->webview_privileged_partitions_.push_back(partition_wildcard); } extension->SetManifestData(keys::kWebviewAccessibleResources, info.release()); return true; } Commit Message: <webview>: Update format for local file access in manifest.json The new format is: "webview" : { "partitions" : [ { "name" : "foo*", "accessible_resources" : ["a.html", "b.html"] }, { "name" : "bar", "accessible_resources" : ["a.html", "c.html"] } ] } BUG=340291 Review URL: https://codereview.chromium.org/151923005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249640 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool WebviewHandler::Parse(Extension* extension, base::string16* error) { scoped_ptr<WebviewInfo> info(new WebviewInfo()); const base::DictionaryValue* dict_value = NULL; if (!extension->manifest()->GetDictionary(keys::kWebview, &dict_value)) { *error = base::ASCIIToUTF16(errors::kInvalidWebview); return false; } const base::ListValue* partition_list = NULL; if (!dict_value->GetList(keys::kWebviewPartitions, &partition_list)) { *error = base::ASCIIToUTF16(errors::kInvalidWebviewPartitionsList); return false; } // The partition list must have at least one entry. if (partition_list->GetSize() == 0) { *error = base::ASCIIToUTF16(errors::kInvalidWebviewPartitionsList); return false; } for (size_t i = 0; i < partition_list->GetSize(); ++i) { const base::DictionaryValue* partition = NULL; if (!partition_list->GetDictionary(i, &partition)) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidWebviewPartition, base::IntToString(i)); return false; } std::string partition_pattern; if (!partition->GetString(keys::kWebviewName, &partition_pattern)) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidWebviewPartitionName, base::IntToString(i)); return false; } const base::ListValue* url_list = NULL; if (!partition->GetList(keys::kWebviewAccessibleResources, &url_list)) { *error = base::ASCIIToUTF16( errors::kInvalidWebviewAccessibleResourcesList); return false; } // The URL list should have at least one entry. if (url_list->GetSize() == 0) { *error = base::ASCIIToUTF16( errors::kInvalidWebviewAccessibleResourcesList); return false; } scoped_ptr<PartitionItem> partition_item( new PartitionItem(partition_pattern)); for (size_t i = 0; i < url_list->GetSize(); ++i) { std::string relative_path; if (!url_list->GetString(i, &relative_path)) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidWebviewAccessibleResource, base::IntToString(i)); return false; } URLPattern pattern(URLPattern::SCHEME_EXTENSION, Extension::GetResourceURL(extension->url(), relative_path).spec()); partition_item->AddPattern(pattern); } info->AddPartitionItem(partition_item.Pass()); } extension->SetManifestData(keys::kWebviewAccessibleResources, info.release()); return true; }
171,209
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_attr3_leaf_getvalue( struct xfs_buf *bp, struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf; struct xfs_attr3_icleaf_hdr ichdr; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; int valuelen; leaf = bp->b_addr; xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf); ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8); ASSERT(args->index < ichdr.count); entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); ASSERT(name_loc->namelen == args->namelen); ASSERT(memcmp(args->name, name_loc->nameval, args->namelen) == 0); valuelen = be16_to_cpu(name_loc->valuelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = valuelen; return 0; } if (args->valuelen < valuelen) { args->valuelen = valuelen; return XFS_ERROR(ERANGE); } args->valuelen = valuelen; memcpy(args->value, &name_loc->nameval[args->namelen], valuelen); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); ASSERT(name_rmt->namelen == args->namelen); ASSERT(memcmp(args->name, name_rmt->name, args->namelen) == 0); valuelen = be32_to_cpu(name_rmt->valuelen); args->rmtblkno = be32_to_cpu(name_rmt->valueblk); args->rmtblkcnt = xfs_attr3_rmt_blocks(args->dp->i_mount, valuelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = valuelen; return 0; } if (args->valuelen < valuelen) { args->valuelen = valuelen; return XFS_ERROR(ERANGE); } args->valuelen = valuelen; } return 0; } Commit Message: xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-19
xfs_attr3_leaf_getvalue( struct xfs_buf *bp, struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf; struct xfs_attr3_icleaf_hdr ichdr; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; int valuelen; leaf = bp->b_addr; xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf); ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8); ASSERT(args->index < ichdr.count); entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); ASSERT(name_loc->namelen == args->namelen); ASSERT(memcmp(args->name, name_loc->nameval, args->namelen) == 0); valuelen = be16_to_cpu(name_loc->valuelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = valuelen; return 0; } if (args->valuelen < valuelen) { args->valuelen = valuelen; return XFS_ERROR(ERANGE); } args->valuelen = valuelen; memcpy(args->value, &name_loc->nameval[args->namelen], valuelen); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); ASSERT(name_rmt->namelen == args->namelen); ASSERT(memcmp(args->name, name_rmt->name, args->namelen) == 0); args->rmtvaluelen = be32_to_cpu(name_rmt->valuelen); args->rmtblkno = be32_to_cpu(name_rmt->valueblk); args->rmtblkcnt = xfs_attr3_rmt_blocks(args->dp->i_mount, args->rmtvaluelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = args->rmtvaluelen; return 0; } if (args->valuelen < args->rmtvaluelen) { args->valuelen = args->rmtvaluelen; return XFS_ERROR(ERANGE); } args->valuelen = args->rmtvaluelen; } return 0; }
166,736
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off, int bpf_size, enum bpf_access_type t, int value_regno) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = regs + regno; int size, err = 0; size = bpf_size_to_bytes(bpf_size); if (size < 0) return size; /* alignment checks will add in reg->off themselves */ err = check_ptr_alignment(env, reg, off, size); if (err) return err; /* for access checks, reg->off is just part of off */ off += reg->off; if (reg->type == PTR_TO_MAP_VALUE) { if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into map\n", value_regno); return -EACCES; } err = check_map_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else if (reg->type == PTR_TO_CTX) { enum bpf_reg_type reg_type = SCALAR_VALUE; if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into ctx\n", value_regno); return -EACCES; } /* ctx accesses must be at a fixed offset, so that we can * determine what type of data were returned. */ if (reg->off) { verbose(env, "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n", regno, reg->off, off - reg->off); return -EACCES; } if (!tnum_is_const(reg->var_off) || reg->var_off.value) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable ctx access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } err = check_ctx_access(env, insn_idx, off, size, t, &reg_type); if (!err && t == BPF_READ && value_regno >= 0) { /* ctx access returns either a scalar, or a * PTR_TO_PACKET[_META,_END]. In the latter * case, we know the offset is zero. */ if (reg_type == SCALAR_VALUE) mark_reg_unknown(env, regs, value_regno); else mark_reg_known_zero(env, regs, value_regno); regs[value_regno].id = 0; regs[value_regno].off = 0; regs[value_regno].range = 0; regs[value_regno].type = reg_type; } } else if (reg->type == PTR_TO_STACK) { /* stack accesses must be at a fixed offset, so that we can * determine what type of data were returned. * See check_stack_read(). */ if (!tnum_is_const(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable stack access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } off += reg->var_off.value; if (off >= 0 || off < -MAX_BPF_STACK) { verbose(env, "invalid stack off=%d size=%d\n", off, size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (t == BPF_WRITE) err = check_stack_write(env, state, off, size, value_regno); else err = check_stack_read(env, state, off, size, value_regno); } else if (reg_is_pkt_pointer(reg)) { if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { verbose(env, "cannot write into packet\n"); return -EACCES; } if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into packet\n", value_regno); return -EACCES; } err = check_packet_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else { verbose(env, "R%d invalid mem access '%s'\n", regno, reg_type_str[reg->type]); return -EACCES; } if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && regs[value_regno].type == SCALAR_VALUE) { /* b/h/w load zero-extends, mark upper bits as known 0 */ regs[value_regno].var_off = tnum_cast(regs[value_regno].var_off, size); __update_reg_bounds(&regs[value_regno]); } return err; } Commit Message: bpf: fix incorrect tracking of register size truncation Properly handle register truncation to a smaller size. The old code first mirrors the clearing of the high 32 bits in the bitwise tristate representation, which is correct. But then, it computes the new arithmetic bounds as the intersection between the old arithmetic bounds and the bounds resulting from the bitwise tristate representation. Therefore, when coerce_reg_to_32() is called on a number with bounds [0xffff'fff8, 0x1'0000'0007], the verifier computes [0xffff'fff8, 0xffff'ffff] as bounds of the truncated number. This is incorrect: The truncated number could also be in the range [0, 7], and no meaningful arithmetic bounds can be computed in that case apart from the obvious [0, 0xffff'ffff]. Starting with v4.14, this is exploitable by unprivileged users as long as the unprivileged_bpf_disabled sysctl isn't set. Debian assigned CVE-2017-16996 for this issue. v2: - flip the mask during arithmetic bounds calculation (Ben Hutchings) v3: - add CVE number (Ben Hutchings) Fixes: b03c9f9fdc37 ("bpf/verifier: track signed and unsigned min/max values") Signed-off-by: Jann Horn <[email protected]> Acked-by: Edward Cree <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-119
static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off, int bpf_size, enum bpf_access_type t, int value_regno) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = regs + regno; int size, err = 0; size = bpf_size_to_bytes(bpf_size); if (size < 0) return size; /* alignment checks will add in reg->off themselves */ err = check_ptr_alignment(env, reg, off, size); if (err) return err; /* for access checks, reg->off is just part of off */ off += reg->off; if (reg->type == PTR_TO_MAP_VALUE) { if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into map\n", value_regno); return -EACCES; } err = check_map_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else if (reg->type == PTR_TO_CTX) { enum bpf_reg_type reg_type = SCALAR_VALUE; if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into ctx\n", value_regno); return -EACCES; } /* ctx accesses must be at a fixed offset, so that we can * determine what type of data were returned. */ if (reg->off) { verbose(env, "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n", regno, reg->off, off - reg->off); return -EACCES; } if (!tnum_is_const(reg->var_off) || reg->var_off.value) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable ctx access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } err = check_ctx_access(env, insn_idx, off, size, t, &reg_type); if (!err && t == BPF_READ && value_regno >= 0) { /* ctx access returns either a scalar, or a * PTR_TO_PACKET[_META,_END]. In the latter * case, we know the offset is zero. */ if (reg_type == SCALAR_VALUE) mark_reg_unknown(env, regs, value_regno); else mark_reg_known_zero(env, regs, value_regno); regs[value_regno].id = 0; regs[value_regno].off = 0; regs[value_regno].range = 0; regs[value_regno].type = reg_type; } } else if (reg->type == PTR_TO_STACK) { /* stack accesses must be at a fixed offset, so that we can * determine what type of data were returned. * See check_stack_read(). */ if (!tnum_is_const(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable stack access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } off += reg->var_off.value; if (off >= 0 || off < -MAX_BPF_STACK) { verbose(env, "invalid stack off=%d size=%d\n", off, size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (t == BPF_WRITE) err = check_stack_write(env, state, off, size, value_regno); else err = check_stack_read(env, state, off, size, value_regno); } else if (reg_is_pkt_pointer(reg)) { if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { verbose(env, "cannot write into packet\n"); return -EACCES; } if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into packet\n", value_regno); return -EACCES; } err = check_packet_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else { verbose(env, "R%d invalid mem access '%s'\n", regno, reg_type_str[reg->type]); return -EACCES; } if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && regs[value_regno].type == SCALAR_VALUE) { /* b/h/w load zero-extends, mark upper bits as known 0 */ coerce_reg_to_size(&regs[value_regno], size); } return err; }
167,659
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: 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 } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1616 CWE ID: CWE-399
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) { insert_image=DestroyImage(insert_image); 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 }
170,198
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } else { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ZVAL_FALSE(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp(name, EL_NULL)) { wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } Commit Message: CWE ID: CWE-502
static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; ent.type = ST_BOOLEAN; SET_STACK_VARNAME; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } else { ZVAL_FALSE(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp(name, EL_NULL)) { wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); }
164,758
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jpc_pi_nextrlcp(register jpc_pi_t *pi) { jpc_pchg_t *pchg; int *prclyrno; pchg = pi->pchg; if (!pi->prgvolfirst) { assert(pi->prcno < pi->pirlvl->numprcs); prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; goto skip; } else { pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos; pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) { if (pi->lyrno >= *prclyrno) { *prclyrno = pi->lyrno; ++(*prclyrno); return 0; } skip: ; } } } } return 1; } Commit Message: Fixed numerous integer overflow problems in the code for packet iterators in the JPC decoder. CWE ID: CWE-125
static int jpc_pi_nextrlcp(register jpc_pi_t *pi) { jpc_pchg_t *pchg; int *prclyrno; pchg = pi->pchg; if (!pi->prgvolfirst) { assert(pi->prcno < pi->pirlvl->numprcs); prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; goto skip; } else { pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos; pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) { if (pi->lyrno >= *prclyrno) { *prclyrno = pi->lyrno; ++(*prclyrno); return 0; } skip: ; } } } } return 1; }
169,441
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep) { const struct icmp6_nodeinfo *ni6; const struct icmp6_hdr *dp; const u_char *cp; size_t siz, i; int needcomma; if (ep < bp) return; dp = (const struct icmp6_hdr *)bp; ni6 = (const struct icmp6_nodeinfo *)bp; siz = ep - bp; switch (ni6->ni_type) { case ICMP6_NI_QUERY: if (siz == sizeof(*dp) + 4) { /* KAME who-are-you */ ND_PRINT((ndo," who-are-you request")); break; } ND_PRINT((ndo," node information query")); ND_TCHECK2(*dp, sizeof(*ni6)); ni6 = (const struct icmp6_nodeinfo *)dp; ND_PRINT((ndo," (")); /*)*/ switch (EXTRACT_16BITS(&ni6->ni_qtype)) { case NI_QTYPE_NOOP: ND_PRINT((ndo,"noop")); break; case NI_QTYPE_SUPTYPES: ND_PRINT((ndo,"supported qtypes")); i = EXTRACT_16BITS(&ni6->ni_flags); if (i) ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : "")); break; case NI_QTYPE_FQDN: ND_PRINT((ndo,"DNS name")); break; case NI_QTYPE_NODEADDR: ND_PRINT((ndo,"node addresses")); i = ni6->ni_flags; if (!i) break; /* NI_NODEADDR_FLAG_TRUNCATE undefined for query */ ND_PRINT((ndo," [%s%s%s%s%s%s]", (i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "", (i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "", (i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "", (i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "", (i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "", (i & NI_NODEADDR_FLAG_ALL) ? "A" : "")); break; default: ND_PRINT((ndo,"unknown")); break; } if (ni6->ni_qtype == NI_QTYPE_NOOP || ni6->ni_qtype == NI_QTYPE_SUPTYPES) { if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid len")); /*(*/ ND_PRINT((ndo,")")); break; } /* XXX backward compat, icmp-name-lookup-03 */ if (siz == sizeof(*ni6)) { ND_PRINT((ndo,", 03 draft")); /*(*/ ND_PRINT((ndo,")")); break; } switch (ni6->ni_code) { case ICMP6_NI_SUBJ_IPV6: if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in6_addr))) break; if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) { if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid subject len")); break; } ND_PRINT((ndo,", subject=%s", ip6addr_string(ndo, ni6 + 1))); break; case ICMP6_NI_SUBJ_FQDN: ND_PRINT((ndo,", subject=DNS name")); cp = (const u_char *)(ni6 + 1); if (cp[0] == ep - cp - 1) { /* icmp-name-lookup-03, pascal string */ if (ndo->ndo_vflag) ND_PRINT((ndo,", 03 draft")); cp++; ND_PRINT((ndo,", \"")); while (cp < ep) { safeputchar(ndo, *cp); cp++; } ND_PRINT((ndo,"\"")); } else dnsname_print(ndo, cp, ep); break; case ICMP6_NI_SUBJ_IPV4: if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr))) break; if (siz != sizeof(*ni6) + sizeof(struct in_addr)) { if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid subject len")); break; } ND_PRINT((ndo,", subject=%s", ipaddr_string(ndo, ni6 + 1))); break; default: ND_PRINT((ndo,", unknown subject")); break; } /*(*/ ND_PRINT((ndo,")")); break; case ICMP6_NI_REPLY: if (icmp6len > siz) { ND_PRINT((ndo,"[|icmp6: node information reply]")); break; } needcomma = 0; ND_TCHECK2(*dp, sizeof(*ni6)); ni6 = (const struct icmp6_nodeinfo *)dp; ND_PRINT((ndo," node information reply")); ND_PRINT((ndo," (")); /*)*/ switch (ni6->ni_code) { case ICMP6_NI_SUCCESS: if (ndo->ndo_vflag) { ND_PRINT((ndo,"success")); needcomma++; } break; case ICMP6_NI_REFUSED: ND_PRINT((ndo,"refused")); needcomma++; if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid length")); break; case ICMP6_NI_UNKNOWN: ND_PRINT((ndo,"unknown")); needcomma++; if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid length")); break; } if (ni6->ni_code != ICMP6_NI_SUCCESS) { /*(*/ ND_PRINT((ndo,")")); break; } switch (EXTRACT_16BITS(&ni6->ni_qtype)) { case NI_QTYPE_NOOP: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"noop")); if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid length")); break; case NI_QTYPE_SUPTYPES: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"supported qtypes")); i = EXTRACT_16BITS(&ni6->ni_flags); if (i) ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : "")); break; case NI_QTYPE_FQDN: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"DNS name")); cp = (const u_char *)(ni6 + 1) + 4; ND_TCHECK(cp[0]); if (cp[0] == ep - cp - 1) { /* icmp-name-lookup-03, pascal string */ if (ndo->ndo_vflag) ND_PRINT((ndo,", 03 draft")); cp++; ND_PRINT((ndo,", \"")); while (cp < ep) { safeputchar(ndo, *cp); cp++; } ND_PRINT((ndo,"\"")); } else dnsname_print(ndo, cp, ep); if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0) ND_PRINT((ndo," [TTL=%u]", EXTRACT_32BITS(ni6 + 1))); break; case NI_QTYPE_NODEADDR: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"node addresses")); i = sizeof(*ni6); while (i < siz) { if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz) break; ND_PRINT((ndo," %s", ip6addr_string(ndo, bp + i))); i += sizeof(struct in6_addr); ND_PRINT((ndo,"(%d)", (int32_t)EXTRACT_32BITS(bp + i))); i += sizeof(int32_t); } i = ni6->ni_flags; if (!i) break; ND_PRINT((ndo," [%s%s%s%s%s%s%s]", (i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "", (i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "", (i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "", (i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "", (i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "", (i & NI_NODEADDR_FLAG_ALL) ? "A" : "", (i & NI_NODEADDR_FLAG_TRUNCATE) ? "T" : "")); break; default: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"unknown")); break; } /*(*/ ND_PRINT((ndo,")")); break; } return; trunc: ND_PRINT((ndo, "[|icmp6]")); } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep) { const struct icmp6_nodeinfo *ni6; const struct icmp6_hdr *dp; const u_char *cp; size_t siz, i; int needcomma; if (ep < bp) return; dp = (const struct icmp6_hdr *)bp; ni6 = (const struct icmp6_nodeinfo *)bp; siz = ep - bp; switch (ni6->ni_type) { case ICMP6_NI_QUERY: if (siz == sizeof(*dp) + 4) { /* KAME who-are-you */ ND_PRINT((ndo," who-are-you request")); break; } ND_PRINT((ndo," node information query")); ND_TCHECK2(*dp, sizeof(*ni6)); ni6 = (const struct icmp6_nodeinfo *)dp; ND_PRINT((ndo," (")); /*)*/ switch (EXTRACT_16BITS(&ni6->ni_qtype)) { case NI_QTYPE_NOOP: ND_PRINT((ndo,"noop")); break; case NI_QTYPE_SUPTYPES: ND_PRINT((ndo,"supported qtypes")); i = EXTRACT_16BITS(&ni6->ni_flags); if (i) ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : "")); break; case NI_QTYPE_FQDN: ND_PRINT((ndo,"DNS name")); break; case NI_QTYPE_NODEADDR: ND_PRINT((ndo,"node addresses")); i = ni6->ni_flags; if (!i) break; /* NI_NODEADDR_FLAG_TRUNCATE undefined for query */ ND_PRINT((ndo," [%s%s%s%s%s%s]", (i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "", (i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "", (i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "", (i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "", (i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "", (i & NI_NODEADDR_FLAG_ALL) ? "A" : "")); break; default: ND_PRINT((ndo,"unknown")); break; } if (ni6->ni_qtype == NI_QTYPE_NOOP || ni6->ni_qtype == NI_QTYPE_SUPTYPES) { if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid len")); /*(*/ ND_PRINT((ndo,")")); break; } /* XXX backward compat, icmp-name-lookup-03 */ if (siz == sizeof(*ni6)) { ND_PRINT((ndo,", 03 draft")); /*(*/ ND_PRINT((ndo,")")); break; } switch (ni6->ni_code) { case ICMP6_NI_SUBJ_IPV6: if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in6_addr))) break; if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) { if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid subject len")); break; } ND_PRINT((ndo,", subject=%s", ip6addr_string(ndo, ni6 + 1))); break; case ICMP6_NI_SUBJ_FQDN: ND_PRINT((ndo,", subject=DNS name")); cp = (const u_char *)(ni6 + 1); if (cp[0] == ep - cp - 1) { /* icmp-name-lookup-03, pascal string */ if (ndo->ndo_vflag) ND_PRINT((ndo,", 03 draft")); cp++; ND_PRINT((ndo,", \"")); while (cp < ep) { safeputchar(ndo, *cp); cp++; } ND_PRINT((ndo,"\"")); } else dnsname_print(ndo, cp, ep); break; case ICMP6_NI_SUBJ_IPV4: if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr))) break; if (siz != sizeof(*ni6) + sizeof(struct in_addr)) { if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid subject len")); break; } ND_PRINT((ndo,", subject=%s", ipaddr_string(ndo, ni6 + 1))); break; default: ND_PRINT((ndo,", unknown subject")); break; } /*(*/ ND_PRINT((ndo,")")); break; case ICMP6_NI_REPLY: if (icmp6len > siz) { ND_PRINT((ndo,"[|icmp6: node information reply]")); break; } needcomma = 0; ND_TCHECK2(*dp, sizeof(*ni6)); ni6 = (const struct icmp6_nodeinfo *)dp; ND_PRINT((ndo," node information reply")); ND_PRINT((ndo," (")); /*)*/ switch (ni6->ni_code) { case ICMP6_NI_SUCCESS: if (ndo->ndo_vflag) { ND_PRINT((ndo,"success")); needcomma++; } break; case ICMP6_NI_REFUSED: ND_PRINT((ndo,"refused")); needcomma++; if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid length")); break; case ICMP6_NI_UNKNOWN: ND_PRINT((ndo,"unknown")); needcomma++; if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid length")); break; } if (ni6->ni_code != ICMP6_NI_SUCCESS) { /*(*/ ND_PRINT((ndo,")")); break; } switch (EXTRACT_16BITS(&ni6->ni_qtype)) { case NI_QTYPE_NOOP: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"noop")); if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,", invalid length")); break; case NI_QTYPE_SUPTYPES: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"supported qtypes")); i = EXTRACT_16BITS(&ni6->ni_flags); if (i) ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : "")); break; case NI_QTYPE_FQDN: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"DNS name")); cp = (const u_char *)(ni6 + 1) + 4; ND_TCHECK(cp[0]); if (cp[0] == ep - cp - 1) { /* icmp-name-lookup-03, pascal string */ if (ndo->ndo_vflag) ND_PRINT((ndo,", 03 draft")); cp++; ND_PRINT((ndo,", \"")); while (cp < ep) { safeputchar(ndo, *cp); cp++; } ND_PRINT((ndo,"\"")); } else dnsname_print(ndo, cp, ep); if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0) ND_PRINT((ndo," [TTL=%u]", EXTRACT_32BITS(ni6 + 1))); break; case NI_QTYPE_NODEADDR: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"node addresses")); i = sizeof(*ni6); while (i < siz) { if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz) break; ND_PRINT((ndo," %s", ip6addr_string(ndo, bp + i))); i += sizeof(struct in6_addr); ND_PRINT((ndo,"(%d)", (int32_t)EXTRACT_32BITS(bp + i))); i += sizeof(int32_t); } i = ni6->ni_flags; if (!i) break; ND_PRINT((ndo," [%s%s%s%s%s%s%s]", (i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "", (i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "", (i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "", (i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "", (i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "", (i & NI_NODEADDR_FLAG_ALL) ? "A" : "", (i & NI_NODEADDR_FLAG_TRUNCATE) ? "T" : "")); break; default: if (needcomma) ND_PRINT((ndo,", ")); ND_PRINT((ndo,"unknown")); break; } /*(*/ ND_PRINT((ndo,")")); break; } return; trunc: ND_PRINT((ndo, "%s", icmp6_tstr)); }
169,822
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void vnc_async_encoding_start(VncState *orig, VncState *local) { local->vnc_encoding = orig->vnc_encoding; local->features = orig->features; local->ds = orig->ds; local->vd = orig->vd; local->lossy_rect = orig->lossy_rect; local->write_pixels = orig->write_pixels; local->clientds = orig->clientds; local->tight = orig->tight; local->zlib = orig->zlib; local->hextile = orig->hextile; local->output = queue->buffer; local->csock = -1; /* Don't do any network work on this thread */ buffer_reset(&local->output); } Commit Message: CWE ID: CWE-125
static void vnc_async_encoding_start(VncState *orig, VncState *local) { local->vnc_encoding = orig->vnc_encoding; local->features = orig->features; local->ds = orig->ds; local->vd = orig->vd; local->lossy_rect = orig->lossy_rect; local->write_pixels = orig->write_pixels; local->client_pf = orig->client_pf; local->client_be = orig->client_be; local->tight = orig->tight; local->zlib = orig->zlib; local->hextile = orig->hextile; local->output = queue->buffer; local->csock = -1; /* Don't do any network work on this thread */ buffer_reset(&local->output); }
165,469
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int vmci_transport_dgram_dequeue(struct kiocb *kiocb, struct vsock_sock *vsk, struct msghdr *msg, size_t len, int flags) { int err; int noblock; struct vmci_datagram *dg; size_t payload_len; struct sk_buff *skb; noblock = flags & MSG_DONTWAIT; if (flags & MSG_OOB || flags & MSG_ERRQUEUE) return -EOPNOTSUPP; /* Retrieve the head sk_buff from the socket's receive queue. */ err = 0; skb = skb_recv_datagram(&vsk->sk, flags, noblock, &err); if (err) return err; if (!skb) return -EAGAIN; dg = (struct vmci_datagram *)skb->data; if (!dg) /* err is 0, meaning we read zero bytes. */ goto out; payload_len = dg->payload_size; /* Ensure the sk_buff matches the payload size claimed in the packet. */ if (payload_len != skb->len - sizeof(*dg)) { err = -EINVAL; goto out; } if (payload_len > len) { payload_len = len; msg->msg_flags |= MSG_TRUNC; } /* Place the datagram payload in the user's iovec. */ err = skb_copy_datagram_iovec(skb, sizeof(*dg), msg->msg_iov, payload_len); if (err) goto out; msg->msg_namelen = 0; if (msg->msg_name) { struct sockaddr_vm *vm_addr; /* Provide the address of the sender. */ vm_addr = (struct sockaddr_vm *)msg->msg_name; vsock_addr_init(vm_addr, dg->src.context, dg->src.resource); msg->msg_namelen = sizeof(*vm_addr); } err = payload_len; out: skb_free_datagram(&vsk->sk, skb); return err; } Commit Message: VSOCK: vmci - fix possible info leak in vmci_transport_dgram_dequeue() In case we received no data on the call to skb_recv_datagram(), i.e. skb->data is NULL, vmci_transport_dgram_dequeue() will return with 0 without updating msg_namelen leading to net/socket.c leaking the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix this by moving the already existing msg_namelen assignment a few lines above. Cc: Andy King <[email protected]> Cc: Dmitry Torokhov <[email protected]> Cc: George Zhang <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int vmci_transport_dgram_dequeue(struct kiocb *kiocb, struct vsock_sock *vsk, struct msghdr *msg, size_t len, int flags) { int err; int noblock; struct vmci_datagram *dg; size_t payload_len; struct sk_buff *skb; noblock = flags & MSG_DONTWAIT; if (flags & MSG_OOB || flags & MSG_ERRQUEUE) return -EOPNOTSUPP; msg->msg_namelen = 0; /* Retrieve the head sk_buff from the socket's receive queue. */ err = 0; skb = skb_recv_datagram(&vsk->sk, flags, noblock, &err); if (err) return err; if (!skb) return -EAGAIN; dg = (struct vmci_datagram *)skb->data; if (!dg) /* err is 0, meaning we read zero bytes. */ goto out; payload_len = dg->payload_size; /* Ensure the sk_buff matches the payload size claimed in the packet. */ if (payload_len != skb->len - sizeof(*dg)) { err = -EINVAL; goto out; } if (payload_len > len) { payload_len = len; msg->msg_flags |= MSG_TRUNC; } /* Place the datagram payload in the user's iovec. */ err = skb_copy_datagram_iovec(skb, sizeof(*dg), msg->msg_iov, payload_len); if (err) goto out; if (msg->msg_name) { struct sockaddr_vm *vm_addr; /* Provide the address of the sender. */ vm_addr = (struct sockaddr_vm *)msg->msg_name; vsock_addr_init(vm_addr, dg->src.context, dg->src.resource); msg->msg_namelen = sizeof(*vm_addr); } err = payload_len; out: skb_free_datagram(&vsk->sk, skb); return err; }
166,029
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static v8::Handle<v8::Value> convert2Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.convert2"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(b*, , V8b::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8b::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert2(); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> convert2Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.convert2"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(b*, , V8b::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8b::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert2(); return v8::Handle<v8::Value>(); }
171,078
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int exfat_mount(struct exfat* ef, const char* spec, const char* options) { int rc; enum exfat_mode mode; exfat_tzset(); memset(ef, 0, sizeof(struct exfat)); parse_options(ef, options); if (match_option(options, "ro")) mode = EXFAT_MODE_RO; else if (match_option(options, "ro_fallback")) mode = EXFAT_MODE_ANY; else mode = EXFAT_MODE_RW; ef->dev = exfat_open(spec, mode); if (ef->dev == NULL) return -EIO; if (exfat_get_mode(ef->dev) == EXFAT_MODE_RO) { if (mode == EXFAT_MODE_ANY) ef->ro = -1; else ef->ro = 1; } ef->sb = malloc(sizeof(struct exfat_super_block)); if (ef->sb == NULL) { exfat_close(ef->dev); exfat_error("failed to allocate memory for the super block"); return -ENOMEM; } memset(ef->sb, 0, sizeof(struct exfat_super_block)); if (exfat_pread(ef->dev, ef->sb, sizeof(struct exfat_super_block), 0) < 0) { exfat_close(ef->dev); free(ef->sb); exfat_error("failed to read boot sector"); return -EIO; } if (memcmp(ef->sb->oem_name, "EXFAT ", 8) != 0) { exfat_close(ef->dev); free(ef->sb); exfat_error("exFAT file system is not found"); return -EIO; } ef->zero_cluster = malloc(CLUSTER_SIZE(*ef->sb)); if (ef->zero_cluster == NULL) { exfat_close(ef->dev); free(ef->sb); exfat_error("failed to allocate zero sector"); return -ENOMEM; } /* use zero_cluster as a temporary buffer for VBR checksum verification */ if (!verify_vbr_checksum(ef->dev, ef->zero_cluster, SECTOR_SIZE(*ef->sb))) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } memset(ef->zero_cluster, 0, CLUSTER_SIZE(*ef->sb)); if (ef->sb->version.major != 1 || ef->sb->version.minor != 0) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("unsupported exFAT version: %hhu.%hhu", ef->sb->version.major, ef->sb->version.minor); free(ef->sb); return -EIO; } if (ef->sb->fat_count != 1) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("unsupported FAT count: %hhu", ef->sb->fat_count); free(ef->sb); return -EIO; } /* officially exFAT supports cluster size up to 32 MB */ if ((int) ef->sb->sector_bits + (int) ef->sb->spc_bits > 25) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("too big cluster size: 2^%d", (int) ef->sb->sector_bits + (int) ef->sb->spc_bits); free(ef->sb); return -EIO; } if (le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb) > exfat_get_size(ef->dev)) { /* this can cause I/O errors later but we don't fail mounting to let user rescue data */ exfat_warn("file system is larger than underlying device: " "%"PRIu64" > %"PRIu64, le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb), exfat_get_size(ef->dev)); } ef->root = malloc(sizeof(struct exfat_node)); if (ef->root == NULL) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); exfat_error("failed to allocate root node"); return -ENOMEM; } memset(ef->root, 0, sizeof(struct exfat_node)); ef->root->flags = EXFAT_ATTRIB_DIR; ef->root->start_cluster = le32_to_cpu(ef->sb->rootdir_cluster); ef->root->fptr_cluster = ef->root->start_cluster; ef->root->name[0] = cpu_to_le16('\0'); ef->root->size = rootdir_size(ef); if (ef->root->size == 0) { free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } /* exFAT does not have time attributes for the root directory */ ef->root->mtime = 0; ef->root->atime = 0; /* always keep at least 1 reference to the root node */ exfat_get_node(ef->root); rc = exfat_cache_directory(ef, ef->root); if (rc != 0) goto error; if (ef->upcase == NULL) { exfat_error("upcase table is not found"); goto error; } if (ef->cmap.chunk == NULL) { exfat_error("clusters bitmap is not found"); goto error; } if (prepare_super_block(ef) != 0) goto error; return 0; error: exfat_put_node(ef, ef->root); exfat_reset_cache(ef); free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } Commit Message: Check sector and cluster size before use. Otherwise malformed FS can cause heap corruption. CWE ID: CWE-119
int exfat_mount(struct exfat* ef, const char* spec, const char* options) { int rc; enum exfat_mode mode; exfat_tzset(); memset(ef, 0, sizeof(struct exfat)); parse_options(ef, options); if (match_option(options, "ro")) mode = EXFAT_MODE_RO; else if (match_option(options, "ro_fallback")) mode = EXFAT_MODE_ANY; else mode = EXFAT_MODE_RW; ef->dev = exfat_open(spec, mode); if (ef->dev == NULL) return -EIO; if (exfat_get_mode(ef->dev) == EXFAT_MODE_RO) { if (mode == EXFAT_MODE_ANY) ef->ro = -1; else ef->ro = 1; } ef->sb = malloc(sizeof(struct exfat_super_block)); if (ef->sb == NULL) { exfat_close(ef->dev); exfat_error("failed to allocate memory for the super block"); return -ENOMEM; } memset(ef->sb, 0, sizeof(struct exfat_super_block)); if (exfat_pread(ef->dev, ef->sb, sizeof(struct exfat_super_block), 0) < 0) { exfat_close(ef->dev); free(ef->sb); exfat_error("failed to read boot sector"); return -EIO; } if (memcmp(ef->sb->oem_name, "EXFAT ", 8) != 0) { exfat_close(ef->dev); free(ef->sb); exfat_error("exFAT file system is not found"); return -EIO; } /* sector cannot be smaller than 512 bytes */ if (ef->sb->sector_bits < 9) { exfat_close(ef->dev); exfat_error("too small sector size: 2^%hhd", ef->sb->sector_bits); free(ef->sb); return -EIO; } /* officially exFAT supports cluster size up to 32 MB */ if ((int) ef->sb->sector_bits + (int) ef->sb->spc_bits > 25) { exfat_close(ef->dev); exfat_error("too big cluster size: 2^(%hhd+%hhd)", ef->sb->sector_bits, ef->sb->spc_bits); free(ef->sb); return -EIO; } ef->zero_cluster = malloc(CLUSTER_SIZE(*ef->sb)); if (ef->zero_cluster == NULL) { exfat_close(ef->dev); free(ef->sb); exfat_error("failed to allocate zero sector"); return -ENOMEM; } /* use zero_cluster as a temporary buffer for VBR checksum verification */ if (!verify_vbr_checksum(ef->dev, ef->zero_cluster, SECTOR_SIZE(*ef->sb))) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } memset(ef->zero_cluster, 0, CLUSTER_SIZE(*ef->sb)); if (ef->sb->version.major != 1 || ef->sb->version.minor != 0) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("unsupported exFAT version: %hhu.%hhu", ef->sb->version.major, ef->sb->version.minor); free(ef->sb); return -EIO; } if (ef->sb->fat_count != 1) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("unsupported FAT count: %hhu", ef->sb->fat_count); free(ef->sb); return -EIO; } if (le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb) > exfat_get_size(ef->dev)) { /* this can cause I/O errors later but we don't fail mounting to let user rescue data */ exfat_warn("file system is larger than underlying device: " "%"PRIu64" > %"PRIu64, le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb), exfat_get_size(ef->dev)); } ef->root = malloc(sizeof(struct exfat_node)); if (ef->root == NULL) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); exfat_error("failed to allocate root node"); return -ENOMEM; } memset(ef->root, 0, sizeof(struct exfat_node)); ef->root->flags = EXFAT_ATTRIB_DIR; ef->root->start_cluster = le32_to_cpu(ef->sb->rootdir_cluster); ef->root->fptr_cluster = ef->root->start_cluster; ef->root->name[0] = cpu_to_le16('\0'); ef->root->size = rootdir_size(ef); if (ef->root->size == 0) { free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } /* exFAT does not have time attributes for the root directory */ ef->root->mtime = 0; ef->root->atime = 0; /* always keep at least 1 reference to the root node */ exfat_get_node(ef->root); rc = exfat_cache_directory(ef, ef->root); if (rc != 0) goto error; if (ef->upcase == NULL) { exfat_error("upcase table is not found"); goto error; } if (ef->cmap.chunk == NULL) { exfat_error("clusters bitmap is not found"); goto error; } if (prepare_super_block(ef) != 0) goto error; return 0; error: exfat_put_node(ef, ef->root); exfat_reset_cache(ef); free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; }
168,867
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) { if (parcel == NULL) { SkDebugf("-------- unparcel parcel is NULL\n"); return NULL; } android::Parcel* p = android::parcelForJavaObject(env, parcel); const bool isMutable = p->readInt32() != 0; const SkColorType colorType = (SkColorType)p->readInt32(); const SkAlphaType alphaType = (SkAlphaType)p->readInt32(); const int width = p->readInt32(); const int height = p->readInt32(); const int rowBytes = p->readInt32(); const int density = p->readInt32(); if (kN32_SkColorType != colorType && kRGB_565_SkColorType != colorType && kARGB_4444_SkColorType != colorType && kIndex_8_SkColorType != colorType && kAlpha_8_SkColorType != colorType) { SkDebugf("Bitmap_createFromParcel unknown colortype: %d\n", colorType); return NULL; } SkBitmap* bitmap = new SkBitmap; bitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType), rowBytes); SkColorTable* ctable = NULL; if (colorType == kIndex_8_SkColorType) { int count = p->readInt32(); if (count > 0) { size_t size = count * sizeof(SkPMColor); const SkPMColor* src = (const SkPMColor*)p->readInplace(size); ctable = new SkColorTable(src, count); } } jbyteArray buffer = GraphicsJNI::allocateJavaPixelRef(env, bitmap, ctable); if (NULL == buffer) { SkSafeUnref(ctable); delete bitmap; return NULL; } SkSafeUnref(ctable); size_t size = bitmap->getSize(); android::Parcel::ReadableBlob blob; android::status_t status = p->readBlob(size, &blob); if (status) { doThrowRE(env, "Could not read bitmap from parcel blob."); delete bitmap; return NULL; } bitmap->lockPixels(); memcpy(bitmap->getPixels(), blob.data(), size); bitmap->unlockPixels(); blob.release(); return GraphicsJNI::createBitmap(env, bitmap, buffer, getPremulBitmapCreateFlags(isMutable), NULL, NULL, density); } Commit Message: Make Bitmap_createFromParcel check the color count. DO NOT MERGE When reading from the parcel, if the number of colors is invalid, early exit. Add two more checks: setInfo must return true, and Parcel::readInplace must return non-NULL. The former ensures that the previously read values (width, height, etc) were valid, and the latter checks that the Parcel had enough data even if the number of colors was reasonable. Also use an auto-deleter to handle deletion of the SkBitmap. Cherry pick from change-Id: Icbd562d6d1f131a723724883fd31822d337cf5a6 BUG=19666945 Change-Id: Iab0d218c41ae0c39606e333e44cda078eef32291 CWE ID: CWE-189
static jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) { if (parcel == NULL) { SkDebugf("-------- unparcel parcel is NULL\n"); return NULL; } android::Parcel* p = android::parcelForJavaObject(env, parcel); const bool isMutable = p->readInt32() != 0; const SkColorType colorType = (SkColorType)p->readInt32(); const SkAlphaType alphaType = (SkAlphaType)p->readInt32(); const int width = p->readInt32(); const int height = p->readInt32(); const int rowBytes = p->readInt32(); const int density = p->readInt32(); if (kN32_SkColorType != colorType && kRGB_565_SkColorType != colorType && kARGB_4444_SkColorType != colorType && kIndex_8_SkColorType != colorType && kAlpha_8_SkColorType != colorType) { SkDebugf("Bitmap_createFromParcel unknown colortype: %d\n", colorType); return NULL; } SkAutoTDelete<SkBitmap> bitmap(new SkBitmap); if (!bitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType), rowBytes)) { return NULL; } SkColorTable* ctable = NULL; if (colorType == kIndex_8_SkColorType) { int count = p->readInt32(); if (count < 0 || count > 256) { // The data is corrupt, since SkColorTable enforces a value between 0 and 256, // inclusive. return NULL; } if (count > 0) { size_t size = count * sizeof(SkPMColor); const SkPMColor* src = (const SkPMColor*)p->readInplace(size); if (src == NULL) { return NULL; } ctable = new SkColorTable(src, count); } } jbyteArray buffer = GraphicsJNI::allocateJavaPixelRef(env, bitmap.get(), ctable); if (NULL == buffer) { SkSafeUnref(ctable); return NULL; } SkSafeUnref(ctable); size_t size = bitmap->getSize(); android::Parcel::ReadableBlob blob; android::status_t status = p->readBlob(size, &blob); if (status) { doThrowRE(env, "Could not read bitmap from parcel blob."); return NULL; } bitmap->lockPixels(); memcpy(bitmap->getPixels(), blob.data(), size); bitmap->unlockPixels(); blob.release(); return GraphicsJNI::createBitmap(env, bitmap.detach(), buffer, getPremulBitmapCreateFlags(isMutable), NULL, NULL, density); }
173,372
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Chapters::Atom::Init() { m_string_uid = NULL; m_uid = 0; m_start_timecode = -1; m_stop_timecode = -1; m_displays = NULL; m_displays_size = 0; m_displays_count = 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Chapters::Atom::Init()
174,387
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Cluster::ParseBlockGroup( long long payload_size, long long& pos, long& len) { const long long payload_start = pos; const long long payload_stop = pos + payload_size; IMkvReader* const pReader = m_pSegment->m_pReader; long long total, avail; long status = pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); if ((total >= 0) && (payload_stop > total)) return E_FILE_FORMAT_INVALID; if (payload_stop > avail) { len = static_cast<long>(payload_size); return E_BUFFER_NOT_FULL; } long long discard_padding = 0; while (pos < payload_stop) { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((pos + len) > payload_stop) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return static_cast<long>(id); if (id == 0) //not a value ID return E_FILE_FORMAT_INVALID; pos += len; //consume ID field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((pos + len) > payload_stop) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast<long>(size); pos += len; //consume size field if (pos > payload_stop) return E_FILE_FORMAT_INVALID; if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; if (id == 0x35A2) //DiscardPadding { result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); status = UnserializeInt(pReader, pos, len, discard_padding); if (status < 0) //error return status; } if (id != 0x21) //sub-part of BlockGroup is not a Block { pos += size; //consume sub-part of block group if (pos > payload_stop) return E_FILE_FORMAT_INVALID; continue; } const long long block_stop = pos + size; if (block_stop > payload_stop) return E_FILE_FORMAT_INVALID; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((pos + len) > block_stop) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long track = ReadUInt(pReader, pos, len); if (track < 0) //error return static_cast<long>(track); if (track == 0) return E_FILE_FORMAT_INVALID; #if 0 const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast<long>(track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return E_FILE_FORMAT_INVALID; #endif pos += len; //consume track number if ((pos + 2) > block_stop) return E_FILE_FORMAT_INVALID; if ((pos + 2) > avail) { len = 2; return E_BUFFER_NOT_FULL; } pos += 2; //consume timecode if ((pos + 1) > block_stop) return E_FILE_FORMAT_INVALID; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } unsigned char flags; status = pReader->Read(pos, 1, &flags); if (status < 0) //error or underflow { len = 1; return status; } ++pos; //consume flags byte assert(pos <= avail); if (pos >= block_stop) return E_FILE_FORMAT_INVALID; const int lacing = int(flags & 0x06) >> 1; if ((lacing != 0) && (block_stop > avail)) { len = static_cast<long>(block_stop - pos); return E_BUFFER_NOT_FULL; } pos = block_stop; //consume block-part of block group assert(pos <= payload_stop); } assert(pos == payload_stop); status = CreateBlock(0x20, //BlockGroup ID payload_start, payload_size, discard_padding); if (status != 0) return status; m_pos = payload_stop; return 0; //success } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Cluster::ParseBlockGroup( IMkvReader* const pReader = m_pSegment->m_pReader; long long total, avail; long status = pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); if ((total >= 0) && (payload_stop > total)) return E_FILE_FORMAT_INVALID; if (payload_stop > avail) { len = static_cast<long>(payload_size); return E_BUFFER_NOT_FULL; } long long discard_padding = 0; while (pos < payload_stop) { // parse sub-block element ID if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((pos + len) > payload_stop) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast<long>(id); if (id == 0) // not a value ID return E_FILE_FORMAT_INVALID; pos += len; // consume ID field // Parse Size if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((pos + len) > payload_stop) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast<long>(size); pos += len; // consume size field // pos now points to start of sub-block group payload if (pos > payload_stop) return E_FILE_FORMAT_INVALID; if (size == 0) // weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; if (id == 0x35A2) { // DiscardPadding status = UnserializeInt(pReader, pos, size, discard_padding); if (status < 0) // error return status; } if (id != 0x21) { // sub-part of BlockGroup is not a Block pos += size; // consume sub-part of block group if (pos > payload_stop) return E_FILE_FORMAT_INVALID; continue; } const long long block_stop = pos + size; if (block_stop > payload_stop) return E_FILE_FORMAT_INVALID; // parse track number if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((pos + len) > block_stop) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long track = ReadUInt(pReader, pos, len); if (track < 0) // error return static_cast<long>(track); if (track == 0) return E_FILE_FORMAT_INVALID; #if 0 const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast<long>(track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return E_FILE_FORMAT_INVALID; #endif pos += len; // consume track number if ((pos + 2) > block_stop) return E_FILE_FORMAT_INVALID; if ((pos + 2) > avail) { len = 2; return E_BUFFER_NOT_FULL; } pos += 2; // consume timecode if ((pos + 1) > block_stop) return E_FILE_FORMAT_INVALID;
174,416
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: read_png(FILE *fp) { png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0); png_infop info_ptr = NULL; png_bytep row = NULL, display = NULL; if (png_ptr == NULL) return 0; if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); if (row != NULL) free(row); if (display != NULL) free(display); return 0; } png_init_io(png_ptr, fp); info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) png_error(png_ptr, "OOM allocating info structure"); png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, NULL, 0); png_read_info(png_ptr, info_ptr); { png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr); row = malloc(rowbytes); display = malloc(rowbytes); if (row == NULL || display == NULL) png_error(png_ptr, "OOM allocating row buffers"); { png_uint_32 height = png_get_image_height(png_ptr, info_ptr); int passes = png_set_interlace_handling(png_ptr); int pass; png_start_read_image(png_ptr); for (pass = 0; pass < passes; ++pass) { png_uint_32 y = height; /* NOTE: this trashes the row each time; interlace handling won't * work, but this avoids memory thrashing for speed testing. */ while (y-- > 0) png_read_row(png_ptr, row, display); } } } /* Make sure to read to the end of the file: */ png_read_end(png_ptr, info_ptr); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); free(row); free(display); return 1; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
read_png(FILE *fp) { png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0); png_infop info_ptr = NULL; png_bytep row = NULL, display = NULL; if (png_ptr == NULL) return 0; if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); if (row != NULL) free(row); if (display != NULL) free(display); return 0; } png_init_io(png_ptr, fp); info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) png_error(png_ptr, "OOM allocating info structure"); png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, NULL, 0); png_read_info(png_ptr, info_ptr); { png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr); /* Failure to initialize these is harmless */ row = malloc(rowbytes); display = malloc(rowbytes); if (row == NULL || display == NULL) png_error(png_ptr, "OOM allocating row buffers"); { png_uint_32 height = png_get_image_height(png_ptr, info_ptr); # ifdef PNG_READ_INTERLACING_SUPPORTED int passes = png_set_interlace_handling(png_ptr); # else /* !READ_INTERLACING */ int passes = png_get_interlace_type(png_ptr, info_ptr) == PNG_INTERLACE_ADAM7 ? PNG_INTERLACE_ADAM7_PASSES : 1; # endif /* !READ_INTERLACING */ int pass; png_start_read_image(png_ptr); for (pass = 0; pass < passes; ++pass) { png_uint_32 y = height; # ifndef PNG_READ_INTERLACING_SUPPORTED if (passes == PNG_INTERLACE_ADAM7_PASSES) y = PNG_PASS_ROWS(y, pass); # endif /* READ_INTERLACING */ /* NOTE: this trashes the row each time; interlace handling won't * work, but this avoids memory thrashing for speed testing. */ while (y-- > 0) png_read_row(png_ptr, row, display); } } } /* Make sure to read to the end of the file: */ png_read_end(png_ptr, info_ptr); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); free(row); free(display); return 1; }
173,719
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline signed short ReadPropertySignedShort(const EndianType endian, const unsigned char *buffer) { union { unsigned short unsigned_value; signed short signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) ((buffer[1] << 8) | buffer[0]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) | ((unsigned char *) buffer)[1]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static inline signed short ReadPropertySignedShort(const EndianType endian, const unsigned char *buffer) { union { unsigned short unsigned_value; signed short signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); }
169,955
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) { if (mNativeWindow != NULL && portIndex == kPortIndexOutput) { return allocateOutputBuffersFromNativeWindow(); } if ((mFlags & kEnableGrallocUsageProtected) && portIndex == kPortIndexOutput) { ALOGE("protected output buffers must be stent to an ANativeWindow"); return PERMISSION_DENIED; } status_t err = OK; if ((mFlags & kStoreMetaDataInVideoBuffers) && portIndex == kPortIndexInput) { err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE); if (err != OK) { ALOGE("Storing meta data in video buffers is not supported"); return err; } } OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = portIndex; err = mOMX->getParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); if (err != OK) { return err; } CODEC_LOGV("allocating %u buffers of size %u on %s port", def.nBufferCountActual, def.nBufferSize, portIndex == kPortIndexInput ? "input" : "output"); if (def.nBufferSize != 0 && def.nBufferCountActual > SIZE_MAX / def.nBufferSize) { return BAD_VALUE; } size_t totalSize = def.nBufferCountActual * def.nBufferSize; mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec"); for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) { sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize); CHECK(mem.get() != NULL); BufferInfo info; info.mData = NULL; info.mSize = def.nBufferSize; IOMX::buffer_id buffer; if (portIndex == kPortIndexInput && ((mQuirks & kRequiresAllocateBufferOnInputPorts) || (mFlags & kUseSecureInputBuffers))) { if (mOMXLivesLocally) { mem.clear(); err = mOMX->allocateBuffer( mNode, portIndex, def.nBufferSize, &buffer, &info.mData); } else { err = mOMX->allocateBufferWithBackup( mNode, portIndex, mem, &buffer, mem->size()); } } else if (portIndex == kPortIndexOutput && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) { if (mOMXLivesLocally) { mem.clear(); err = mOMX->allocateBuffer( mNode, portIndex, def.nBufferSize, &buffer, &info.mData); } else { err = mOMX->allocateBufferWithBackup( mNode, portIndex, mem, &buffer, mem->size()); } } else { err = mOMX->useBuffer(mNode, portIndex, mem, &buffer, mem->size()); } if (err != OK) { ALOGE("allocate_buffer_with_backup failed"); return err; } if (mem != NULL) { info.mData = mem->pointer(); } info.mBuffer = buffer; info.mStatus = OWNED_BY_US; info.mMem = mem; info.mMediaBuffer = NULL; if (portIndex == kPortIndexOutput) { LOG_ALWAYS_FATAL_IF((mOMXLivesLocally && (mQuirks & kRequiresAllocateBufferOnOutputPorts) && (mQuirks & kDefersOutputBufferAllocation)), "allocateBuffersOnPort cannot defer buffer allocation"); info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize); info.mMediaBuffer->setObserver(this); } mPortBuffers[portIndex].push(info); CODEC_LOGV("allocated buffer %u on %s port", buffer, portIndex == kPortIndexInput ? "input" : "output"); } if (portIndex == kPortIndexOutput) { sp<MetaData> meta = mSource->getFormat(); int32_t delay = 0; if (!meta->findInt32(kKeyEncoderDelay, &delay)) { delay = 0; } int32_t padding = 0; if (!meta->findInt32(kKeyEncoderPadding, &padding)) { padding = 0; } int32_t numchannels = 0; if (delay + padding) { if (mOutputFormat->findInt32(kKeyChannelCount, &numchannels)) { size_t frameSize = numchannels * sizeof(int16_t); if (mSkipCutBuffer != NULL) { size_t prevbuffersize = mSkipCutBuffer->size(); if (prevbuffersize != 0) { ALOGW("Replacing SkipCutBuffer holding %zu bytes", prevbuffersize); } } mSkipCutBuffer = new SkipCutBuffer(delay * frameSize, padding * frameSize); } } } if (portIndex == kPortIndexInput && (mFlags & kUseSecureInputBuffers)) { Vector<MediaBuffer *> buffers; for (size_t i = 0; i < def.nBufferCountActual; ++i) { const BufferInfo &info = mPortBuffers[kPortIndexInput].itemAt(i); MediaBuffer *mbuf = new MediaBuffer(info.mData, info.mSize); buffers.push(mbuf); } status_t err = mSource->setBuffers(buffers); if (err != OK) { for (size_t i = 0; i < def.nBufferCountActual; ++i) { buffers.editItemAt(i)->release(); } buffers.clear(); CODEC_LOGE( "Codec requested to use secure input buffers but " "upstream source didn't support that."); return err; } } return OK; } Commit Message: OMXCodec: check IMemory::pointer() before using allocation Bug: 29421811 Change-Id: I0a73ba12bae4122f1d89fc92e5ea4f6a96cd1ed1 CWE ID: CWE-284
status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) { if (mNativeWindow != NULL && portIndex == kPortIndexOutput) { return allocateOutputBuffersFromNativeWindow(); } if ((mFlags & kEnableGrallocUsageProtected) && portIndex == kPortIndexOutput) { ALOGE("protected output buffers must be stent to an ANativeWindow"); return PERMISSION_DENIED; } status_t err = OK; if ((mFlags & kStoreMetaDataInVideoBuffers) && portIndex == kPortIndexInput) { err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE); if (err != OK) { ALOGE("Storing meta data in video buffers is not supported"); return err; } } OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = portIndex; err = mOMX->getParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); if (err != OK) { return err; } CODEC_LOGV("allocating %u buffers of size %u on %s port", def.nBufferCountActual, def.nBufferSize, portIndex == kPortIndexInput ? "input" : "output"); if (def.nBufferSize != 0 && def.nBufferCountActual > SIZE_MAX / def.nBufferSize) { return BAD_VALUE; } size_t totalSize = def.nBufferCountActual * def.nBufferSize; mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec"); for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) { sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize); if (mem == NULL || mem->pointer() == NULL) { return NO_MEMORY; } BufferInfo info; info.mData = NULL; info.mSize = def.nBufferSize; IOMX::buffer_id buffer; if (portIndex == kPortIndexInput && ((mQuirks & kRequiresAllocateBufferOnInputPorts) || (mFlags & kUseSecureInputBuffers))) { if (mOMXLivesLocally) { mem.clear(); err = mOMX->allocateBuffer( mNode, portIndex, def.nBufferSize, &buffer, &info.mData); } else { err = mOMX->allocateBufferWithBackup( mNode, portIndex, mem, &buffer, mem->size()); } } else if (portIndex == kPortIndexOutput && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) { if (mOMXLivesLocally) { mem.clear(); err = mOMX->allocateBuffer( mNode, portIndex, def.nBufferSize, &buffer, &info.mData); } else { err = mOMX->allocateBufferWithBackup( mNode, portIndex, mem, &buffer, mem->size()); } } else { err = mOMX->useBuffer(mNode, portIndex, mem, &buffer, mem->size()); } if (err != OK) { ALOGE("allocate_buffer_with_backup failed"); return err; } if (mem != NULL) { info.mData = mem->pointer(); } info.mBuffer = buffer; info.mStatus = OWNED_BY_US; info.mMem = mem; info.mMediaBuffer = NULL; if (portIndex == kPortIndexOutput) { LOG_ALWAYS_FATAL_IF((mOMXLivesLocally && (mQuirks & kRequiresAllocateBufferOnOutputPorts) && (mQuirks & kDefersOutputBufferAllocation)), "allocateBuffersOnPort cannot defer buffer allocation"); info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize); info.mMediaBuffer->setObserver(this); } mPortBuffers[portIndex].push(info); CODEC_LOGV("allocated buffer %u on %s port", buffer, portIndex == kPortIndexInput ? "input" : "output"); } if (portIndex == kPortIndexOutput) { sp<MetaData> meta = mSource->getFormat(); int32_t delay = 0; if (!meta->findInt32(kKeyEncoderDelay, &delay)) { delay = 0; } int32_t padding = 0; if (!meta->findInt32(kKeyEncoderPadding, &padding)) { padding = 0; } int32_t numchannels = 0; if (delay + padding) { if (mOutputFormat->findInt32(kKeyChannelCount, &numchannels)) { size_t frameSize = numchannels * sizeof(int16_t); if (mSkipCutBuffer != NULL) { size_t prevbuffersize = mSkipCutBuffer->size(); if (prevbuffersize != 0) { ALOGW("Replacing SkipCutBuffer holding %zu bytes", prevbuffersize); } } mSkipCutBuffer = new SkipCutBuffer(delay * frameSize, padding * frameSize); } } } if (portIndex == kPortIndexInput && (mFlags & kUseSecureInputBuffers)) { Vector<MediaBuffer *> buffers; for (size_t i = 0; i < def.nBufferCountActual; ++i) { const BufferInfo &info = mPortBuffers[kPortIndexInput].itemAt(i); MediaBuffer *mbuf = new MediaBuffer(info.mData, info.mSize); buffers.push(mbuf); } status_t err = mSource->setBuffers(buffers); if (err != OK) { for (size_t i = 0; i < def.nBufferCountActual; ++i) { buffers.editItemAt(i)->release(); } buffers.clear(); CODEC_LOGE( "Codec requested to use secure input buffers but " "upstream source didn't support that."); return err; } } return OK; }
173,404
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PassRefPtr<RTCSessionDescriptionDescriptor> RTCPeerConnectionHandlerChromium::remoteDescription() { if (!m_webHandler) return 0; return m_webHandler->remoteDescription(); } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
PassRefPtr<RTCSessionDescriptionDescriptor> RTCPeerConnectionHandlerChromium::remoteDescription()
170,353
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LocalFileSystem::resolveURL(ExecutionContext* context, const KURL& fileSystemURL, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context); RefPtr<CallbackWrapper> wrapper = adoptRef(new CallbackWrapper(callbacks)); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::resolveURLInternal, this, contextPtr, fileSystemURL, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void LocalFileSystem::resolveURL(ExecutionContext* context, const KURL& fileSystemURL, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context); CallbackWrapper* wrapper = new CallbackWrapper(callbacks); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::resolveURLInternal, this, contextPtr, fileSystemURL, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); }
171,430
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, struct inode **delegated_inode, unsigned int flags) { int error; bool is_dir = d_is_dir(old_dentry); const unsigned char *old_name; struct inode *source = old_dentry->d_inode; struct inode *target = new_dentry->d_inode; bool new_is_dir = false; unsigned max_links = new_dir->i_sb->s_max_links; if (source == target) return 0; error = may_delete(old_dir, old_dentry, is_dir); if (error) return error; if (!target) { error = may_create(new_dir, new_dentry); } else { new_is_dir = d_is_dir(new_dentry); if (!(flags & RENAME_EXCHANGE)) error = may_delete(new_dir, new_dentry, is_dir); else error = may_delete(new_dir, new_dentry, new_is_dir); } if (error) return error; if (!old_dir->i_op->rename) return -EPERM; /* * If we are going to change the parent - check write permissions, * we'll need to flip '..'. */ if (new_dir != old_dir) { if (is_dir) { error = inode_permission(source, MAY_WRITE); if (error) return error; } if ((flags & RENAME_EXCHANGE) && new_is_dir) { error = inode_permission(target, MAY_WRITE); if (error) return error; } } error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry, flags); if (error) return error; old_name = fsnotify_oldname_init(old_dentry->d_name.name); dget(new_dentry); if (!is_dir || (flags & RENAME_EXCHANGE)) lock_two_nondirectories(source, target); else if (target) inode_lock(target); error = -EBUSY; if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry)) goto out; if (max_links && new_dir != old_dir) { error = -EMLINK; if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links) goto out; if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir && old_dir->i_nlink >= max_links) goto out; } if (is_dir && !(flags & RENAME_EXCHANGE) && target) shrink_dcache_parent(new_dentry); if (!is_dir) { error = try_break_deleg(source, delegated_inode); if (error) goto out; } if (target && !new_is_dir) { error = try_break_deleg(target, delegated_inode); if (error) goto out; } error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry, flags); if (error) goto out; if (!(flags & RENAME_EXCHANGE) && target) { if (is_dir) target->i_flags |= S_DEAD; dont_mount(new_dentry); detach_mounts(new_dentry); } if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) { if (!(flags & RENAME_EXCHANGE)) d_move(old_dentry, new_dentry); else d_exchange(old_dentry, new_dentry); } out: if (!is_dir || (flags & RENAME_EXCHANGE)) unlock_two_nondirectories(source, target); else if (target) inode_unlock(target); dput(new_dentry); if (!error) { fsnotify_move(old_dir, new_dir, old_name, is_dir, !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry); if (flags & RENAME_EXCHANGE) { fsnotify_move(new_dir, old_dir, old_dentry->d_name.name, new_is_dir, NULL, new_dentry); } } fsnotify_oldname_free(old_name); return error; } Commit Message: dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-362
int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, struct inode **delegated_inode, unsigned int flags) { int error; bool is_dir = d_is_dir(old_dentry); struct inode *source = old_dentry->d_inode; struct inode *target = new_dentry->d_inode; bool new_is_dir = false; unsigned max_links = new_dir->i_sb->s_max_links; struct name_snapshot old_name; if (source == target) return 0; error = may_delete(old_dir, old_dentry, is_dir); if (error) return error; if (!target) { error = may_create(new_dir, new_dentry); } else { new_is_dir = d_is_dir(new_dentry); if (!(flags & RENAME_EXCHANGE)) error = may_delete(new_dir, new_dentry, is_dir); else error = may_delete(new_dir, new_dentry, new_is_dir); } if (error) return error; if (!old_dir->i_op->rename) return -EPERM; /* * If we are going to change the parent - check write permissions, * we'll need to flip '..'. */ if (new_dir != old_dir) { if (is_dir) { error = inode_permission(source, MAY_WRITE); if (error) return error; } if ((flags & RENAME_EXCHANGE) && new_is_dir) { error = inode_permission(target, MAY_WRITE); if (error) return error; } } error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry, flags); if (error) return error; take_dentry_name_snapshot(&old_name, old_dentry); dget(new_dentry); if (!is_dir || (flags & RENAME_EXCHANGE)) lock_two_nondirectories(source, target); else if (target) inode_lock(target); error = -EBUSY; if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry)) goto out; if (max_links && new_dir != old_dir) { error = -EMLINK; if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links) goto out; if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir && old_dir->i_nlink >= max_links) goto out; } if (is_dir && !(flags & RENAME_EXCHANGE) && target) shrink_dcache_parent(new_dentry); if (!is_dir) { error = try_break_deleg(source, delegated_inode); if (error) goto out; } if (target && !new_is_dir) { error = try_break_deleg(target, delegated_inode); if (error) goto out; } error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry, flags); if (error) goto out; if (!(flags & RENAME_EXCHANGE) && target) { if (is_dir) target->i_flags |= S_DEAD; dont_mount(new_dentry); detach_mounts(new_dentry); } if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) { if (!(flags & RENAME_EXCHANGE)) d_move(old_dentry, new_dentry); else d_exchange(old_dentry, new_dentry); } out: if (!is_dir || (flags & RENAME_EXCHANGE)) unlock_two_nondirectories(source, target); else if (target) inode_unlock(target); dput(new_dentry); if (!error) { fsnotify_move(old_dir, new_dir, old_name.name, is_dir, !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry); if (flags & RENAME_EXCHANGE) { fsnotify_move(new_dir, old_dir, old_dentry->d_name.name, new_is_dir, NULL, new_dentry); } } release_dentry_name_snapshot(&old_name); return error; }
168,263
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: TabStyle::TabColors GM2TabStyle::CalculateColors() const { const ui::ThemeProvider* theme_provider = tab_->GetThemeProvider(); constexpr float kMinimumActiveContrastRatio = 6.05f; constexpr float kMinimumInactiveContrastRatio = 4.61f; constexpr float kMinimumHoveredContrastRatio = 5.02f; constexpr float kMinimumPressedContrastRatio = 4.41f; float expected_opacity = 0.0f; if (tab_->IsActive()) { expected_opacity = 1.0f; } else if (tab_->IsSelected()) { expected_opacity = kSelectedTabOpacity; } else if (tab_->mouse_hovered()) { expected_opacity = GetHoverOpacity(); } const SkColor bg_color = color_utils::AlphaBlend( tab_->controller()->GetTabBackgroundColor(TAB_ACTIVE), tab_->controller()->GetTabBackgroundColor(TAB_INACTIVE), expected_opacity); SkColor title_color = tab_->controller()->GetTabForegroundColor( expected_opacity > 0.5f ? TAB_ACTIVE : TAB_INACTIVE, bg_color); title_color = color_utils::GetColorWithMinimumContrast(title_color, bg_color); const SkColor base_hovered_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_HOVER); const SkColor base_pressed_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_PRESSED); const auto get_color_for_contrast_ratio = [](SkColor fg_color, SkColor bg_color, float contrast_ratio) { const SkAlpha blend_alpha = color_utils::GetBlendValueWithMinimumContrast( bg_color, fg_color, bg_color, contrast_ratio); return color_utils::AlphaBlend(fg_color, bg_color, blend_alpha); }; const SkColor generated_icon_color = get_color_for_contrast_ratio( title_color, bg_color, tab_->IsActive() ? kMinimumActiveContrastRatio : kMinimumInactiveContrastRatio); const SkColor generated_hovered_color = get_color_for_contrast_ratio( base_hovered_color, bg_color, kMinimumHoveredContrastRatio); const SkColor generated_pressed_color = get_color_for_contrast_ratio( base_pressed_color, bg_color, kMinimumPressedContrastRatio); const SkColor generated_hovered_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_hovered_color); const SkColor generated_pressed_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_pressed_color); return {bg_color, title_color, generated_icon_color, generated_hovered_icon_color, generated_pressed_icon_color, generated_hovered_color, generated_pressed_color}; } Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <[email protected]> Reviewed-by: Taylor Bergquist <[email protected]> Cr-Commit-Position: refs/heads/master@{#660498} CWE ID: CWE-20
TabStyle::TabColors GM2TabStyle::CalculateColors() const { const ui::ThemeProvider* theme_provider = tab_->GetThemeProvider(); constexpr float kMinimumActiveContrastRatio = 6.05f; constexpr float kMinimumInactiveContrastRatio = 4.61f; constexpr float kMinimumHoveredContrastRatio = 5.02f; constexpr float kMinimumPressedContrastRatio = 4.41f; float expected_opacity = 0.0f; if (tab_->IsActive()) { expected_opacity = 1.0f; } else if (tab_->IsSelected()) { expected_opacity = kSelectedTabOpacity; } else if (tab_->mouse_hovered()) { expected_opacity = GetHoverOpacity(); } const SkColor bg_color = color_utils::AlphaBlend( GetTabBackgroundColor(TAB_ACTIVE), GetTabBackgroundColor(TAB_INACTIVE), expected_opacity); SkColor title_color = tab_->controller()->GetTabForegroundColor( expected_opacity > 0.5f ? TAB_ACTIVE : TAB_INACTIVE, bg_color); title_color = color_utils::GetColorWithMinimumContrast(title_color, bg_color); const SkColor base_hovered_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_HOVER); const SkColor base_pressed_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_PRESSED); const auto get_color_for_contrast_ratio = [](SkColor fg_color, SkColor bg_color, float contrast_ratio) { const SkAlpha blend_alpha = color_utils::GetBlendValueWithMinimumContrast( bg_color, fg_color, bg_color, contrast_ratio); return color_utils::AlphaBlend(fg_color, bg_color, blend_alpha); }; const SkColor generated_icon_color = get_color_for_contrast_ratio( title_color, bg_color, tab_->IsActive() ? kMinimumActiveContrastRatio : kMinimumInactiveContrastRatio); const SkColor generated_hovered_color = get_color_for_contrast_ratio( base_hovered_color, bg_color, kMinimumHoveredContrastRatio); const SkColor generated_pressed_color = get_color_for_contrast_ratio( base_pressed_color, bg_color, kMinimumPressedContrastRatio); const SkColor generated_hovered_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_hovered_color); const SkColor generated_pressed_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_pressed_color); return {bg_color, title_color, generated_icon_color, generated_hovered_icon_color, generated_pressed_icon_color, generated_hovered_color, generated_pressed_color}; }
172,521
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) { size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0); icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length); if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) == ustr_host.length()) transliterator_.get()->transliterate(ustr_host); UErrorCode status = U_ZERO_ERROR; icu::UnicodeString ustr_skeleton; uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton, &status); if (U_FAILURE(status)) return false; std::string skeleton; ustr_skeleton.toUTF8String(skeleton); return LookupMatchInTopDomains(skeleton); } Commit Message: Add a few more confusable map entries 1. Map Malaylam U+0D1F to 's'. 2. Map 'small-cap-like' Cyrillic letters to "look-alike" Latin lowercase letters. The characters in new confusable map entries are replaced by their Latin "look-alike" characters before the skeleton is calculated to compare with top domain names. Bug: 784761,773930 Test: components_unittests --gtest_filter=*IDNToUni* Change-Id: Ib26664e21ac5eb290e4a2993b01cbf0edaade0ee Reviewed-on: https://chromium-review.googlesource.com/805214 Reviewed-by: Peter Kasting <[email protected]> Commit-Queue: Jungshik Shin <[email protected]> Cr-Commit-Position: refs/heads/master@{#521648} CWE ID: CWE-20
bool IDNSpoofChecker::SimilarToTopDomains(base::StringPiece16 hostname) { size_t hostname_length = hostname.length() - (hostname.back() == '.' ? 1 : 0); icu::UnicodeString ustr_host(FALSE, hostname.data(), hostname_length); if (lgc_letters_n_ascii_.span(ustr_host, 0, USET_SPAN_CONTAINED) == ustr_host.length()) diacritic_remover_.get()->transliterate(ustr_host); extra_confusable_mapper_.get()->transliterate(ustr_host); UErrorCode status = U_ZERO_ERROR; icu::UnicodeString ustr_skeleton; uspoof_getSkeletonUnicodeString(checker_, 0, ustr_host, ustr_skeleton, &status); if (U_FAILURE(status)) return false; std::string skeleton; return LookupMatchInTopDomains(ustr_skeleton.toUTF8String(skeleton)); }
172,686
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeContentBrowserClient::ShouldSwapProcessesForNavigation( const GURL& current_url, const GURL& new_url) { if (current_url.is_empty()) { if (new_url.SchemeIs(extensions::kExtensionScheme)) return true; return false; } if (current_url.SchemeIs(extensions::kExtensionScheme) || new_url.SchemeIs(extensions::kExtensionScheme)) { if (current_url.GetOrigin() != new_url.GetOrigin()) return true; } return false; } Commit Message: Ensure extensions and the Chrome Web Store are loaded in new BrowsingInstances. BUG=174943 TEST=Can't post message to CWS. See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/12301013 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184208 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ChromeContentBrowserClient::ShouldSwapProcessesForNavigation( SiteInstance* site_instance, const GURL& current_url, const GURL& new_url) { if (current_url.is_empty()) { if (new_url.SchemeIs(extensions::kExtensionScheme)) return true; return false; } if (current_url.SchemeIs(extensions::kExtensionScheme) || new_url.SchemeIs(extensions::kExtensionScheme)) { if (current_url.GetOrigin() != new_url.GetOrigin()) return true; } // The checks below only matter if we can retrieve which extensions are // installed. Profile* profile = Profile::FromBrowserContext(site_instance->GetBrowserContext()); ExtensionService* service = extensions::ExtensionSystem::Get(profile)->extension_service(); if (!service) return false; // We must swap if the URL is for an extension and we are not using an // extension process. const Extension* new_extension = service->extensions()->GetExtensionOrAppByURL(ExtensionURLInfo(new_url)); // Ignore all hosted apps except the Chrome Web Store, since they do not // require their own BrowsingInstance (e.g., postMessage is ok). if (new_extension && new_extension->is_hosted_app() && new_extension->id() != extension_misc::kWebStoreAppId) new_extension = NULL; if (new_extension && site_instance->HasProcess() && !service->process_map()->Contains(new_extension->id(), site_instance->GetProcess()->GetID())) return true; return false; }
171,436
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt, u16 selector, int seg) { u8 cpl = ctxt->ops->cpl(ctxt); return __load_segment_descriptor(ctxt, selector, seg, cpl, X86_TRANSFER_NONE, NULL); } Commit Message: KVM: x86: fix emulation of "MOV SS, null selector" This is CVE-2017-2583. On Intel this causes a failed vmentry because SS's type is neither 3 nor 7 (even though the manual says this check is only done for usable SS, and the dmesg splat says that SS is unusable!). On AMD it's worse: svm.c is confused and sets CPL to 0 in the vmcb. The fix fabricates a data segment descriptor when SS is set to a null selector, so that CPL and SS.DPL are set correctly in the VMCS/vmcb. Furthermore, only allow setting SS to a NULL selector if SS.RPL < 3; this in turn ensures CPL < 3 because RPL must be equal to CPL. Thanks to Andy Lutomirski and Willy Tarreau for help in analyzing the bug and deciphering the manuals. Reported-by: Xiaohan Zhang <[email protected]> Fixes: 79d5b4c3cd809c770d4bf9812635647016c56011 Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID:
static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt, u16 selector, int seg) { u8 cpl = ctxt->ops->cpl(ctxt); /* * None of MOV, POP and LSS can load a NULL selector in CPL=3, but * they can load it at CPL<3 (Intel's manual says only LSS can, * but it's wrong). * * However, the Intel manual says that putting IST=1/DPL=3 in * an interrupt gate will result in SS=3 (the AMD manual instead * says it doesn't), so allow SS=3 in __load_segment_descriptor * and only forbid it here. */ if (seg == VCPU_SREG_SS && selector == 3 && ctxt->mode == X86EMUL_MODE_PROT64) return emulate_exception(ctxt, GP_VECTOR, 0, true); return __load_segment_descriptor(ctxt, selector, seg, cpl, X86_TRANSFER_NONE, NULL); }
168,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: log2vis_encoded_string (PyObject * string, const char *encoding, FriBidiParType base_direction, int clean, int reordernsm) { PyObject *logical = NULL; /* logical unicode object */ PyObject *result = NULL; /* output string object */ /* Always needed for the string length */ logical = PyUnicode_Decode (PyString_AS_STRING (string), PyString_GET_SIZE (string), encoding, "strict"); if (logical == NULL) return NULL; if (strcmp (encoding, "utf-8") == 0) /* Shortcut for utf8 strings (little faster) */ result = log2vis_utf8 (string, PyUnicode_GET_SIZE (logical), base_direction, clean, reordernsm); else { /* Invoke log2vis_unicode and encode back to encoding */ PyObject *visual = log2vis_unicode (logical, base_direction, clean, reordernsm); if (visual) { result = PyUnicode_Encode (PyUnicode_AS_UNICODE (visual), PyUnicode_GET_SIZE (visual), encoding, "strict"); Py_DECREF (visual); } } Py_DECREF (logical); return result; } Commit Message: refactor pyfribidi.c module pyfribidi.c is now compiled as _pyfribidi. This module only handles unicode internally and doesn't use the fribidi_utf8_to_unicode function (which can't handle 4 byte utf-8 sequences). This fixes the buffer overflow in issue #2. The code is now also much simpler: pyfribidi.c is down from 280 to 130 lines of code. We now ship a pure python pyfribidi that handles the case when non-unicode strings are passed in. We now also adapt the size of the output string if clean=True is passed. CWE ID: CWE-119
log2vis_encoded_string (PyObject * string, const char *encoding,
165,640
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string PrintPreviewUI::GetPrintPreviewUIAddress() const { char preview_ui_addr[2 + (2 * sizeof(this)) + 1]; base::snprintf(preview_ui_addr, sizeof(preview_ui_addr), "%p", this); return preview_ui_addr; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
std::string PrintPreviewUI::GetPrintPreviewUIAddress() const { int32 PrintPreviewUI::GetIDForPrintPreviewUI() const { return id_; }
170,835
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DefragIPv4TooLargeTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* Create a fragment that would extend past the max allowable size * for an IPv4 packet. */ p = BuildTestPacket(1, 8183, 0, 'A', 71); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; if (!ENGINE_ISSET_EVENT(p, IPV4_FRAG_PKT_TOO_LARGE)) goto end; /* The fragment should have been ignored so no fragments should have * been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
DefragIPv4TooLargeTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* Create a fragment that would extend past the max allowable size * for an IPv4 packet. */ p = BuildTestPacket(IPPROTO_ICMP, 1, 8183, 0, 'A', 71); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; if (!ENGINE_ISSET_EVENT(p, IPV4_FRAG_PKT_TOO_LARGE)) goto end; /* The fragment should have been ignored so no fragments should have * been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; }
168,297
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunFwdTxfm(int16_t *in, int16_t *out, int stride) { fwd_txfm_(in, out, stride); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunFwdTxfm(int16_t *in, int16_t *out, int stride) { void RunFwdTxfm(int16_t *in, tran_low_t *out, int stride) { fwd_txfm_(in, out, stride); }
174,521
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: mobility_print(netdissect_options *ndo, const u_char *bp, const u_char *bp2 _U_) { const struct ip6_mobility *mh; const u_char *ep; unsigned mhlen, hlen; uint8_t type; mh = (const struct ip6_mobility *)bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if (!ND_TTEST(mh->ip6m_len)) { /* * There's not enough captured data to include the * mobility header length. * * Our caller expects us to return the length, however, * so return a value that will run to the end of the * captured data. * * XXX - "ip6_print()" doesn't do anything with the * returned length, however, as it breaks out of the * header-processing loop. */ mhlen = ep - bp; goto trunc; } mhlen = (mh->ip6m_len + 1) << 3; /* XXX ip6m_cksum */ ND_TCHECK(mh->ip6m_type); type = mh->ip6m_type; if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) { ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type)); goto trunc; } ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type))); switch (type) { case IP6M_BINDING_REQUEST: hlen = IP6M_MINLEN; break; case IP6M_HOME_TEST_INIT: case IP6M_CAREOF_TEST_INIT: hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_HOME_TEST: case IP6M_CAREOF_TEST: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Keygen Token=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_BINDING_UPDATE: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 1); if (bp[hlen] & 0xf0) ND_PRINT((ndo, " ")); if (bp[hlen] & 0x80) ND_PRINT((ndo, "A")); if (bp[hlen] & 0x40) ND_PRINT((ndo, "H")); if (bp[hlen] & 0x20) ND_PRINT((ndo, "L")); if (bp[hlen] & 0x10) ND_PRINT((ndo, "K")); /* Reserved (4bits) */ hlen += 1; /* Reserved (8bits) */ hlen += 1; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ACK: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); if (mh->ip6m_data8[1] & 0x80) ND_PRINT((ndo, " K")); /* Reserved (7bits) */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 2); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen]))); hlen += 2; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ERROR: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); /* Reserved */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 16); ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen]))); hlen += 16; break; default: ND_PRINT((ndo, " len=%u", mh->ip6m_len)); return(mhlen); break; } if (ndo->ndo_vflag) if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen)) goto trunc; return(mhlen); trunc: ND_PRINT((ndo, "%s", tstr)); return(mhlen); } Commit Message: CVE-2017-12985/IPv6: Check for print routines returning -1 when running past the end. rt6_print(), ah_print(), and esp_print() return -1 if they run up against the end of the packet while dissecting; if that happens, stop dissecting, don't try to fetch the next header value, because 1) *it* might be past the end of the packet and 2) we won't be using it in any case, as we'll be exiting the loop. Also, change mobility_print() to return -1 if it runs up against the end of the packet, and stop dissecting if it does so. This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
mobility_print(netdissect_options *ndo, const u_char *bp, const u_char *bp2 _U_) { const struct ip6_mobility *mh; const u_char *ep; unsigned mhlen, hlen; uint8_t type; mh = (const struct ip6_mobility *)bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if (!ND_TTEST(mh->ip6m_len)) { /* * There's not enough captured data to include the * mobility header length. * * Our caller expects us to return the length, however, * so return a value that will run to the end of the * captured data. * * XXX - "ip6_print()" doesn't do anything with the * returned length, however, as it breaks out of the * header-processing loop. */ mhlen = ep - bp; goto trunc; } mhlen = (mh->ip6m_len + 1) << 3; /* XXX ip6m_cksum */ ND_TCHECK(mh->ip6m_type); type = mh->ip6m_type; if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) { ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type)); goto trunc; } ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type))); switch (type) { case IP6M_BINDING_REQUEST: hlen = IP6M_MINLEN; break; case IP6M_HOME_TEST_INIT: case IP6M_CAREOF_TEST_INIT: hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_HOME_TEST: case IP6M_CAREOF_TEST: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Keygen Token=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_BINDING_UPDATE: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 1); if (bp[hlen] & 0xf0) ND_PRINT((ndo, " ")); if (bp[hlen] & 0x80) ND_PRINT((ndo, "A")); if (bp[hlen] & 0x40) ND_PRINT((ndo, "H")); if (bp[hlen] & 0x20) ND_PRINT((ndo, "L")); if (bp[hlen] & 0x10) ND_PRINT((ndo, "K")); /* Reserved (4bits) */ hlen += 1; /* Reserved (8bits) */ hlen += 1; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ACK: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); if (mh->ip6m_data8[1] & 0x80) ND_PRINT((ndo, " K")); /* Reserved (7bits) */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 2); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen]))); hlen += 2; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ERROR: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); /* Reserved */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 16); ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen]))); hlen += 16; break; default: ND_PRINT((ndo, " len=%u", mh->ip6m_len)); return(mhlen); break; } if (ndo->ndo_vflag) if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen)) goto trunc; return(mhlen); trunc: ND_PRINT((ndo, "%s", tstr)); return(-1); }
167,931
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ProcessBackingStore(HeapObjectHeader* header) { EXPECT_TRUE(header->IsValid()); EXPECT_TRUE(header->IsMarked()); header->Unmark(); ThreadHeap::GcInfo(header->GcInfoIndex())->trace_(this, header->Payload()); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void ProcessBackingStore(HeapObjectHeader* header) { EXPECT_TRUE(header->IsValid()); EXPECT_TRUE(header->IsMarked()); header->Unmark(); GCInfoTable::Get() .GCInfoFromIndex(header->GcInfoIndex()) ->trace_(this, header->Payload()); }
173,140
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt) { struct f_midi *midi = func_to_midi(f); unsigned i; int err; /* we only set alt for MIDIStreaming interface */ if (intf != midi->ms_id) return 0; err = f_midi_start_ep(midi, f, midi->in_ep); if (err) return err; err = f_midi_start_ep(midi, f, midi->out_ep); if (err) return err; /* pre-allocate write usb requests to use on f_midi_transmit. */ while (kfifo_avail(&midi->in_req_fifo)) { struct usb_request *req = midi_alloc_ep_req(midi->in_ep, midi->buflen); if (req == NULL) return -ENOMEM; req->length = 0; req->complete = f_midi_complete; kfifo_put(&midi->in_req_fifo, req); } /* allocate a bunch of read buffers and queue them all at once. */ for (i = 0; i < midi->qlen && err == 0; i++) { struct usb_request *req = midi_alloc_ep_req(midi->out_ep, midi->buflen); if (req == NULL) return -ENOMEM; req->complete = f_midi_complete; err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC); if (err) { ERROR(midi, "%s: couldn't enqueue request: %d\n", midi->out_ep->name, err); free_ep_req(midi->out_ep, req); return err; } } return 0; } Commit Message: USB: gadget: f_midi: fixing a possible double-free in f_midi It looks like there is a possibility of a double-free vulnerability on an error path of the f_midi_set_alt function in the f_midi driver. If the path is feasible then free_ep_req gets called twice: req->complete = f_midi_complete; err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC); => ... usb_gadget_giveback_request => f_midi_complete (CALLBACK) (inside f_midi_complete, for various cases of status) free_ep_req(ep, req); // first kfree if (err) { ERROR(midi, "%s: couldn't enqueue request: %d\n", midi->out_ep->name, err); free_ep_req(midi->out_ep, req); // second kfree return err; } The double-free possibility was introduced with commit ad0d1a058eac ("usb: gadget: f_midi: fix leak on failed to enqueue out requests"). Found by MOXCAFE tool. Signed-off-by: Tuba Yavuz <[email protected]> Fixes: ad0d1a058eac ("usb: gadget: f_midi: fix leak on failed to enqueue out requests") Acked-by: Felipe Balbi <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-415
static int f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt) { struct f_midi *midi = func_to_midi(f); unsigned i; int err; /* we only set alt for MIDIStreaming interface */ if (intf != midi->ms_id) return 0; err = f_midi_start_ep(midi, f, midi->in_ep); if (err) return err; err = f_midi_start_ep(midi, f, midi->out_ep); if (err) return err; /* pre-allocate write usb requests to use on f_midi_transmit. */ while (kfifo_avail(&midi->in_req_fifo)) { struct usb_request *req = midi_alloc_ep_req(midi->in_ep, midi->buflen); if (req == NULL) return -ENOMEM; req->length = 0; req->complete = f_midi_complete; kfifo_put(&midi->in_req_fifo, req); } /* allocate a bunch of read buffers and queue them all at once. */ for (i = 0; i < midi->qlen && err == 0; i++) { struct usb_request *req = midi_alloc_ep_req(midi->out_ep, midi->buflen); if (req == NULL) return -ENOMEM; req->complete = f_midi_complete; err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC); if (err) { ERROR(midi, "%s: couldn't enqueue request: %d\n", midi->out_ep->name, err); if (req->buf != NULL) free_ep_req(midi->out_ep, req); return err; } } return 0; }
169,761
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost( RenderWidgetHostImpl* receiving_widget) { if (!SiteIsolationPolicy::AreCrossProcessFramesPossible()) return receiving_widget; if (receiving_widget != GetMainFrame()->GetRenderWidgetHost()) return receiving_widget; WebContentsImpl* focused_contents = GetFocusedWebContents(); if (focused_contents->ShowingInterstitialPage()) { return static_cast<RenderFrameHostImpl*>( focused_contents->GetRenderManager() ->interstitial_page() ->GetMainFrame()) ->GetRenderWidgetHost(); } FrameTreeNode* focused_frame = nullptr; if (focused_contents->browser_plugin_guest_ && !GuestMode::IsCrossProcessFrameGuest(focused_contents)) { focused_frame = frame_tree_.GetFocusedFrame(); } else { focused_frame = GetFocusedWebContents()->frame_tree_.GetFocusedFrame(); } if (!focused_frame) return receiving_widget; RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView(); if (!view) return nullptr; return RenderWidgetHostImpl::From(view->GetRenderWidgetHost()); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost( RenderWidgetHostImpl* receiving_widget) { if (!SiteIsolationPolicy::AreCrossProcessFramesPossible()) return receiving_widget; if (receiving_widget != GetMainFrame()->GetRenderWidgetHost()) return receiving_widget; WebContentsImpl* focused_contents = GetFocusedWebContents(); if (focused_contents->ShowingInterstitialPage()) { return static_cast<RenderFrameHostImpl*>( focused_contents->interstitial_page_->GetMainFrame()) ->GetRenderWidgetHost(); } FrameTreeNode* focused_frame = nullptr; if (focused_contents->browser_plugin_guest_ && !GuestMode::IsCrossProcessFrameGuest(focused_contents)) { focused_frame = frame_tree_.GetFocusedFrame(); } else { focused_frame = GetFocusedWebContents()->frame_tree_.GetFocusedFrame(); } if (!focused_frame) return receiving_widget; RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView(); if (!view) return nullptr; return RenderWidgetHostImpl::From(view->GetRenderWidgetHost()); }
172,328
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { ChannelType channel; const char *option; ImageInfo *mogrify_info; MagickStatusType status; 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); mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); channel=mogrify_info->channel; 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); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL); InheritException(exception,&(*images)->exception); break; } i++; break; } if (LocaleCompare("append",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images); 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); 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",option+1) == 0) { if (*option == '+') { channel=DefaultChannels; break; } channel=(ChannelType) ParseChannelOption(argv[i+1]); break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { status=MagickFalse; break; } (void) ClutImageChannel(image,channel,clut_image); clut_image=DestroyImage(clut_image); InheritException(exception,&image->exception); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("coalesce",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images); 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) { Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images); combine_image=CombineImages(*images,channel,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare("compare",option+1) == 0) { const char *option; 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); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { status=MagickFalse; break; } metric=UndefinedMetric; option=GetImageOption(image_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImageChannels(image,reconstruct_image, channel,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); 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) { Image *mask_image, *composite_image, *image; RectangleInfo geometry; (void) SyncImagesSettings(mogrify_info,*images); image=RemoveFirstImageFromList(images); composite_image=RemoveFirstImageFromList(images); if (composite_image == (Image *) NULL) { status=MagickFalse; break; } (void) TransformImage(&composite_image,(char *) NULL, composite_image->geometry); SetGeometry(composite_image,&geometry); (void) ParseAbsoluteGeometry(composite_image->geometry,&geometry); GravityAdjustGeometry(image->columns,image->rows,image->gravity, &geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image != (Image *) NULL) { if ((image->compose == DisplaceCompositeOp) || (image->compose == DistortCompositeOp)) { /* Merge Y displacement into X displacement image. */ (void) CompositeImage(composite_image,CopyGreenCompositeOp, mask_image,0,0); mask_image=DestroyImage(mask_image); } else { /* Set a blending mask for the composition. */ if (image->mask != (Image *) NULL) image->mask=DestroyImage(image->mask); image->mask=mask_image; (void) NegateImage(image->mask,MagickFalse); } } (void) CompositeImageChannel(image,channel,image->compose, composite_image,geometry.x,geometry.y); if (mask_image != (Image *) NULL) { image->mask=DestroyImage(image->mask); mask_image=image->mask; } composite_image=DestroyImage(composite_image); InheritException(exception,&image->exception); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images); (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); deconstruct_image=DeconstructImages(*images,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=MagickFalse; break; } quantize_info->dither=MagickTrue; 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); break; } break; } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images); 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); 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); 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); fx_image=FxImageChannel(*images,channel,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); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { status=MagickFalse; break; } (void) HaldClutImageChannel(image,channel,hald_image); hald_image=DestroyImage(hald_image); InheritException(exception,&image->exception); 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); 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; } break; } case 'l': { if (LocaleCompare("layers",option+1) == 0) { Image *layers; ImageLayerMethod method; (void) SyncImagesSettings(mogrify_info,*images); layers=(Image *) NULL; method=(ImageLayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImageLayers(*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; } InheritException(exception,&layers->exception); *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } InheritException(exception,&layers->exception); *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); InheritException(exception,&(*images)->exception); (void) RemapImages(quantize_info,*images,(Image *) NULL); 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; InheritException(exception,&layers->exception); *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare("map",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL); InheritException(exception,&(*images)->exception); break; } i++; break; } if (LocaleCompare("maximum",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images); 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); 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); 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); 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[MaxTextExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images); args=InterpretImageProperties(mogrify_info,*images,argv[i+1]); InheritException(exception,&(*images)->exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\0'; x++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,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,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImageChannel(*images,channel, number_arguments >> 1,arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; break; } if (LocaleCompare("print",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images); string=InterpretImageProperties(mogrify_info,*images,argv[i+1]); if (string == (char *) NULL) break; InheritException(exception,&(*images)->exception); (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); 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 *arguments; int next, status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MaxTextExtent-1)) token=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; arguments=argv[i+1]; 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; } break; } case 'r': { if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(images); InheritException(exception,&(*images)->exception); break; } break; } case 's': { if (LocaleCompare("smush",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images); 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[MaxTextExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images); (void) FormatLocaleString(key,MaxTextExtent,"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); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1616 CWE ID: CWE-399
WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { ChannelType channel; const char *option; ImageInfo *mogrify_info; MagickStatusType status; 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); mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); channel=mogrify_info->channel; 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); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL); InheritException(exception,&(*images)->exception); break; } i++; break; } if (LocaleCompare("append",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images); 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); 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",option+1) == 0) { if (*option == '+') { channel=DefaultChannels; break; } channel=(ChannelType) ParseChannelOption(argv[i+1]); break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { status=MagickFalse; break; } (void) ClutImageChannel(image,channel,clut_image); clut_image=DestroyImage(clut_image); InheritException(exception,&image->exception); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("coalesce",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images); 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) { Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images); combine_image=CombineImages(*images,channel,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare("compare",option+1) == 0) { const char *option; 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); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { status=MagickFalse; break; } metric=UndefinedMetric; option=GetImageOption(image_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImageChannels(image,reconstruct_image, channel,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); 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) { Image *mask_image, *composite_image, *image; RectangleInfo geometry; (void) SyncImagesSettings(mogrify_info,*images); image=RemoveFirstImageFromList(images); composite_image=RemoveFirstImageFromList(images); if (composite_image == (Image *) NULL) { status=MagickFalse; break; } (void) TransformImage(&composite_image,(char *) NULL, composite_image->geometry); SetGeometry(composite_image,&geometry); (void) ParseAbsoluteGeometry(composite_image->geometry,&geometry); GravityAdjustGeometry(image->columns,image->rows,image->gravity, &geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image != (Image *) NULL) { if ((image->compose == DisplaceCompositeOp) || (image->compose == DistortCompositeOp)) { /* Merge Y displacement into X displacement image. */ (void) CompositeImage(composite_image,CopyGreenCompositeOp, mask_image,0,0); mask_image=DestroyImage(mask_image); } else { /* Set a blending mask for the composition. */ if (image->mask != (Image *) NULL) image->mask=DestroyImage(image->mask); image->mask=mask_image; (void) NegateImage(image->mask,MagickFalse); } } (void) CompositeImageChannel(image,channel,image->compose, composite_image,geometry.x,geometry.y); if (mask_image != (Image *) NULL) { image->mask=DestroyImage(image->mask); mask_image=image->mask; } composite_image=DestroyImage(composite_image); InheritException(exception,&image->exception); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images); (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); deconstruct_image=DeconstructImages(*images,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=MagickFalse; break; } quantize_info->dither=MagickTrue; 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); break; } break; } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images); 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); 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); 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); fx_image=FxImageChannel(*images,channel,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); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { status=MagickFalse; break; } (void) HaldClutImageChannel(image,channel,hald_image); hald_image=DestroyImage(hald_image); InheritException(exception,&image->exception); 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); 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; } break; } case 'l': { if (LocaleCompare("layers",option+1) == 0) { Image *layers; ImageLayerMethod method; (void) SyncImagesSettings(mogrify_info,*images); layers=(Image *) NULL; method=(ImageLayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImageLayers(*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; } InheritException(exception,&layers->exception); *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } InheritException(exception,&layers->exception); *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); InheritException(exception,&(*images)->exception); (void) RemapImages(quantize_info,*images,(Image *) NULL); 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; InheritException(exception,&layers->exception); *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare("map",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL); InheritException(exception,&(*images)->exception); break; } i++; break; } if (LocaleCompare("maximum",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images); 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); 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); 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); 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[MaxTextExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images); args=InterpretImageProperties(mogrify_info,*images,argv[i+1]); InheritException(exception,&(*images)->exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\0'; x++) { GetNextToken(p,&p,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,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,MaxTextExtent,token); if (*token == ',') GetNextToken(p,&p,MaxTextExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImageChannel(*images,channel, number_arguments >> 1,arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; break; } if (LocaleCompare("print",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images); string=InterpretImageProperties(mogrify_info,*images,argv[i+1]); if (string == (char *) NULL) break; InheritException(exception,&(*images)->exception); (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); 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 *arguments; int next, status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MaxTextExtent-1)) token=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; arguments=argv[i+1]; 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; } break; } case 'r': { if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(images); InheritException(exception,&(*images)->exception); break; } break; } case 's': { if (LocaleCompare("smush",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images); 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[MaxTextExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images); (void) FormatLocaleString(key,MaxTextExtent,"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); }
169,592
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Address LargeObjectArena::doAllocateLargeObjectPage(size_t allocationSize, size_t gcInfoIndex) { size_t largeObjectSize = LargeObjectPage::pageHeaderSize() + allocationSize; #if defined(ADDRESS_SANITIZER) largeObjectSize += allocationGranularity; #endif getThreadState()->shouldFlushHeapDoesNotContainCache(); PageMemory* pageMemory = PageMemory::allocate( largeObjectSize, getThreadState()->heap().getRegionTree()); Address largeObjectAddress = pageMemory->writableStart(); Address headerAddress = largeObjectAddress + LargeObjectPage::pageHeaderSize(); #if DCHECK_IS_ON() for (size_t i = 0; i < largeObjectSize; ++i) ASSERT(!largeObjectAddress[i]); #endif ASSERT(gcInfoIndex > 0); HeapObjectHeader* header = new (NotNull, headerAddress) HeapObjectHeader(largeObjectSizeInHeader, gcInfoIndex); Address result = headerAddress + sizeof(*header); ASSERT(!(reinterpret_cast<uintptr_t>(result) & allocationMask)); LargeObjectPage* largeObject = new (largeObjectAddress) LargeObjectPage(pageMemory, this, allocationSize); ASSERT(header->checkHeader()); ASAN_POISON_MEMORY_REGION(header, sizeof(*header)); ASAN_POISON_MEMORY_REGION(largeObject->getAddress() + largeObject->size(), allocationGranularity); largeObject->link(&m_firstPage); getThreadState()->heap().heapStats().increaseAllocatedSpace( largeObject->size()); getThreadState()->increaseAllocatedObjectSize(largeObject->size()); return result; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
Address LargeObjectArena::doAllocateLargeObjectPage(size_t allocationSize, size_t gcInfoIndex) { size_t largeObjectSize = LargeObjectPage::pageHeaderSize() + allocationSize; #if defined(ADDRESS_SANITIZER) largeObjectSize += allocationGranularity; #endif getThreadState()->shouldFlushHeapDoesNotContainCache(); PageMemory* pageMemory = PageMemory::allocate( largeObjectSize, getThreadState()->heap().getRegionTree()); Address largeObjectAddress = pageMemory->writableStart(); Address headerAddress = largeObjectAddress + LargeObjectPage::pageHeaderSize(); #if DCHECK_IS_ON() for (size_t i = 0; i < largeObjectSize; ++i) ASSERT(!largeObjectAddress[i]); #endif ASSERT(gcInfoIndex > 0); HeapObjectHeader* header = new (NotNull, headerAddress) HeapObjectHeader(largeObjectSizeInHeader, gcInfoIndex); Address result = headerAddress + sizeof(*header); ASSERT(!(reinterpret_cast<uintptr_t>(result) & allocationMask)); LargeObjectPage* largeObject = new (largeObjectAddress) LargeObjectPage(pageMemory, this, allocationSize); header->checkHeader(); ASAN_POISON_MEMORY_REGION(header, sizeof(*header)); ASAN_POISON_MEMORY_REGION(largeObject->getAddress() + largeObject->size(), allocationGranularity); largeObject->link(&m_firstPage); getThreadState()->heap().heapStats().increaseAllocatedSpace( largeObject->size()); getThreadState()->increaseAllocatedObjectSize(largeObject->size()); return result; }
172,709
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ScriptProcessorHandler::Process(size_t frames_to_process) { AudioBus* input_bus = Input(0).Bus(); AudioBus* output_bus = Output(0).Bus(); unsigned double_buffer_index = this->DoubleBufferIndex(); bool is_double_buffer_index_good = double_buffer_index < 2 && double_buffer_index < input_buffers_.size() && double_buffer_index < output_buffers_.size(); DCHECK(is_double_buffer_index_good); if (!is_double_buffer_index_good) return; AudioBuffer* input_buffer = input_buffers_[double_buffer_index].Get(); AudioBuffer* output_buffer = output_buffers_[double_buffer_index].Get(); unsigned number_of_input_channels = internal_input_bus_->NumberOfChannels(); bool buffers_are_good = output_buffer && BufferSize() == output_buffer->length() && buffer_read_write_index_ + frames_to_process <= BufferSize(); if (internal_input_bus_->NumberOfChannels()) buffers_are_good = buffers_are_good && input_buffer && BufferSize() == input_buffer->length(); DCHECK(buffers_are_good); if (!buffers_are_good) return; bool is_frames_to_process_good = frames_to_process && BufferSize() >= frames_to_process && !(BufferSize() % frames_to_process); DCHECK(is_frames_to_process_good); if (!is_frames_to_process_good) return; unsigned number_of_output_channels = output_bus->NumberOfChannels(); bool channels_are_good = (number_of_input_channels == number_of_input_channels_) && (number_of_output_channels == number_of_output_channels_); DCHECK(channels_are_good); if (!channels_are_good) return; for (unsigned i = 0; i < number_of_input_channels; ++i) internal_input_bus_->SetChannelMemory( i, input_buffer->getChannelData(i).View()->Data() + buffer_read_write_index_, frames_to_process); if (number_of_input_channels) internal_input_bus_->CopyFrom(*input_bus); for (unsigned i = 0; i < number_of_output_channels; ++i) { memcpy(output_bus->Channel(i)->MutableData(), output_buffer->getChannelData(i).View()->Data() + buffer_read_write_index_, sizeof(float) * frames_to_process); } buffer_read_write_index_ = (buffer_read_write_index_ + frames_to_process) % BufferSize(); if (!buffer_read_write_index_) { MutexTryLocker try_locker(process_event_lock_); if (!try_locker.Locked()) { output_buffer->Zero(); } else if (Context()->GetExecutionContext()) { if (Context()->HasRealtimeConstraint()) { TaskRunnerHelper::Get(TaskType::kMediaElementEvent, Context()->GetExecutionContext()) ->PostTask(BLINK_FROM_HERE, CrossThreadBind( &ScriptProcessorHandler::FireProcessEvent, CrossThreadUnretained(this), double_buffer_index_)); } else { std::unique_ptr<WaitableEvent> waitable_event = WTF::MakeUnique<WaitableEvent>(); TaskRunnerHelper::Get(TaskType::kMediaElementEvent, Context()->GetExecutionContext()) ->PostTask(BLINK_FROM_HERE, CrossThreadBind( &ScriptProcessorHandler:: FireProcessEventForOfflineAudioContext, CrossThreadUnretained(this), double_buffer_index_, CrossThreadUnretained(waitable_event.get()))); waitable_event->Wait(); } } SwapBuffers(); } } Commit Message: Keep ScriptProcessorHandler alive across threads When posting a task from the ScriptProcessorHandler::Process to fire a process event, we need to keep the handler alive in case the ScriptProcessorNode goes away (because it has no onaudioprocess handler) and removes the its handler. Bug: 765495 Test: Change-Id: Ib4fa39d7b112c7051897700a1eff9f59a4a7a054 Reviewed-on: https://chromium-review.googlesource.com/677137 Reviewed-by: Hongchan Choi <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Commit-Queue: Raymond Toy <[email protected]> Cr-Commit-Position: refs/heads/master@{#503629} CWE ID: CWE-416
void ScriptProcessorHandler::Process(size_t frames_to_process) { AudioBus* input_bus = Input(0).Bus(); AudioBus* output_bus = Output(0).Bus(); unsigned double_buffer_index = this->DoubleBufferIndex(); bool is_double_buffer_index_good = double_buffer_index < 2 && double_buffer_index < input_buffers_.size() && double_buffer_index < output_buffers_.size(); DCHECK(is_double_buffer_index_good); if (!is_double_buffer_index_good) return; AudioBuffer* input_buffer = input_buffers_[double_buffer_index].Get(); AudioBuffer* output_buffer = output_buffers_[double_buffer_index].Get(); unsigned number_of_input_channels = internal_input_bus_->NumberOfChannels(); bool buffers_are_good = output_buffer && BufferSize() == output_buffer->length() && buffer_read_write_index_ + frames_to_process <= BufferSize(); if (internal_input_bus_->NumberOfChannels()) buffers_are_good = buffers_are_good && input_buffer && BufferSize() == input_buffer->length(); DCHECK(buffers_are_good); if (!buffers_are_good) return; bool is_frames_to_process_good = frames_to_process && BufferSize() >= frames_to_process && !(BufferSize() % frames_to_process); DCHECK(is_frames_to_process_good); if (!is_frames_to_process_good) return; unsigned number_of_output_channels = output_bus->NumberOfChannels(); bool channels_are_good = (number_of_input_channels == number_of_input_channels_) && (number_of_output_channels == number_of_output_channels_); DCHECK(channels_are_good); if (!channels_are_good) return; for (unsigned i = 0; i < number_of_input_channels; ++i) internal_input_bus_->SetChannelMemory( i, input_buffer->getChannelData(i).View()->Data() + buffer_read_write_index_, frames_to_process); if (number_of_input_channels) internal_input_bus_->CopyFrom(*input_bus); for (unsigned i = 0; i < number_of_output_channels; ++i) { memcpy(output_bus->Channel(i)->MutableData(), output_buffer->getChannelData(i).View()->Data() + buffer_read_write_index_, sizeof(float) * frames_to_process); } buffer_read_write_index_ = (buffer_read_write_index_ + frames_to_process) % BufferSize(); if (!buffer_read_write_index_) { MutexTryLocker try_locker(process_event_lock_); if (!try_locker.Locked()) { output_buffer->Zero(); } else if (Context()->GetExecutionContext()) { if (Context()->HasRealtimeConstraint()) { TaskRunnerHelper::Get(TaskType::kMediaElementEvent, Context()->GetExecutionContext()) ->PostTask( BLINK_FROM_HERE, CrossThreadBind(&ScriptProcessorHandler::FireProcessEvent, WrapRefPtr(this), double_buffer_index_)); } else { std::unique_ptr<WaitableEvent> waitable_event = WTF::MakeUnique<WaitableEvent>(); TaskRunnerHelper::Get(TaskType::kMediaElementEvent, Context()->GetExecutionContext()) ->PostTask( BLINK_FROM_HERE, CrossThreadBind(&ScriptProcessorHandler:: FireProcessEventForOfflineAudioContext, WrapRefPtr(this), double_buffer_index_, CrossThreadUnretained(waitable_event.get()))); waitable_event->Wait(); } } SwapBuffers(); } }
172,943
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PropertyTreeManager::SetupRootTransformNode() { cc::TransformTree& transform_tree = property_trees_.transform_tree; transform_tree.clear(); property_trees_.element_id_to_transform_node_index.clear(); cc::TransformNode& transform_node = *transform_tree.Node( transform_tree.Insert(cc::TransformNode(), kRealRootNodeId)); DCHECK_EQ(transform_node.id, kSecondaryRootNodeId); transform_node.source_node_id = transform_node.parent_id; float device_scale_factor = root_layer_->layer_tree_host()->device_scale_factor(); gfx::Transform to_screen; to_screen.Scale(device_scale_factor, device_scale_factor); transform_tree.SetToScreen(kRealRootNodeId, to_screen); gfx::Transform from_screen; bool invertible = to_screen.GetInverse(&from_screen); DCHECK(invertible); transform_tree.SetFromScreen(kRealRootNodeId, from_screen); transform_tree.set_needs_update(true); transform_node_map_.Set(TransformPaintPropertyNode::Root(), transform_node.id); root_layer_->SetTransformTreeIndex(transform_node.id); } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
void PropertyTreeManager::SetupRootTransformNode() { cc::TransformTree& transform_tree = property_trees_.transform_tree; transform_tree.clear(); property_trees_.element_id_to_transform_node_index.clear(); cc::TransformNode& transform_node = *transform_tree.Node( transform_tree.Insert(cc::TransformNode(), kRealRootNodeId)); DCHECK_EQ(transform_node.id, kSecondaryRootNodeId); transform_node.source_node_id = transform_node.parent_id; float device_scale_factor = root_layer_->layer_tree_host()->device_scale_factor(); gfx::Transform to_screen; to_screen.Scale(device_scale_factor, device_scale_factor); transform_tree.SetToScreen(kRealRootNodeId, to_screen); gfx::Transform from_screen; bool invertible = to_screen.GetInverse(&from_screen); DCHECK(invertible); transform_tree.SetFromScreen(kRealRootNodeId, from_screen); transform_tree.set_needs_update(true); transform_node_map_.Set(&TransformPaintPropertyNode::Root(), transform_node.id); root_layer_->SetTransformTreeIndex(transform_node.id); }
171,831
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void DetectFlow(ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { /* No need to perform any detection on this packet, if the the given flag is set.*/ if ((p->flags & PKT_NOPACKET_INSPECTION) || (PACKET_TEST_ACTION(p, ACTION_DROP))) { /* hack: if we are in pass the entire flow mode, we need to still * update the inspect_id forward. So test for the condition here, * and call the update code if necessary. */ const int pass = ((p->flow->flags & FLOW_NOPACKET_INSPECTION)); const AppProto alproto = FlowGetAppProtocol(p->flow); if (pass && AppLayerParserProtocolSupportsTxs(p->proto, alproto)) { uint8_t flags; if (p->flowflags & FLOW_PKT_TOSERVER) { flags = STREAM_TOSERVER; } else { flags = STREAM_TOCLIENT; } flags = FlowGetDisruptionFlags(p->flow, flags); DeStateUpdateInspectTransactionId(p->flow, flags, true); } return; } /* see if the packet matches one or more of the sigs */ (void)DetectRun(tv, de_ctx, det_ctx, p); } Commit Message: stream: still inspect packets dropped by stream The detect engine would bypass packets that are set as dropped. This seems sane, as these packets are going to be dropped anyway. However, it lead to the following corner case: stream events that triggered the drop could not be matched on the rules. The packet with the event wouldn't make it to the detect engine due to the bypass. This patch changes the logic to not bypass DROP packets anymore. Packets that are dropped by the stream engine will set the no payload inspection flag, so avoid needless cost. CWE ID: CWE-693
static void DetectFlow(ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { if (p->flags & PKT_NOPACKET_INSPECTION) { /* hack: if we are in pass the entire flow mode, we need to still * update the inspect_id forward. So test for the condition here, * and call the update code if necessary. */ const int pass = ((p->flow->flags & FLOW_NOPACKET_INSPECTION)); const AppProto alproto = FlowGetAppProtocol(p->flow); if (pass && AppLayerParserProtocolSupportsTxs(p->proto, alproto)) { uint8_t flags; if (p->flowflags & FLOW_PKT_TOSERVER) { flags = STREAM_TOSERVER; } else { flags = STREAM_TOCLIENT; } flags = FlowGetDisruptionFlags(p->flow, flags); DeStateUpdateInspectTransactionId(p->flow, flags, true); } SCLogDebug("p->pcap %"PRIu64": no detection on packet, " "PKT_NOPACKET_INSPECTION is set", p->pcap_cnt); return; } /* see if the packet matches one or more of the sigs */ (void)DetectRun(tv, de_ctx, det_ctx, p); }
169,332
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: mp_capable_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_capable *mpc = (const struct mp_capable *) opt; if (!(opt_len == 12 && flags & TH_SYN) && !(opt_len == 20 && (flags & (TH_SYN | TH_ACK)) == TH_ACK)) return 0; if (MP_CAPABLE_OPT_VERSION(mpc->sub_ver) != 0) { ND_PRINT((ndo, " Unknown Version (%d)", MP_CAPABLE_OPT_VERSION(mpc->sub_ver))); return 1; } if (mpc->flags & MP_CAPABLE_C) ND_PRINT((ndo, " csum")); ND_PRINT((ndo, " {0x%" PRIx64, EXTRACT_64BITS(mpc->sender_key))); if (opt_len == 20) /* ACK */ ND_PRINT((ndo, ",0x%" PRIx64, EXTRACT_64BITS(mpc->receiver_key))); ND_PRINT((ndo, "}")); return 1; } Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption. Do the length checking inline; that means we print stuff up to the point at which we run out of option data. First check to make sure we have at least 4 bytes of option, so we have flags to check. This fixes a buffer over-read discovered by Kim Gwan Yeong. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
mp_capable_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_capable *mpc = (const struct mp_capable *) opt; if (!(opt_len == 12 && (flags & TH_SYN)) && !(opt_len == 20 && (flags & (TH_SYN | TH_ACK)) == TH_ACK)) return 0; if (MP_CAPABLE_OPT_VERSION(mpc->sub_ver) != 0) { ND_PRINT((ndo, " Unknown Version (%d)", MP_CAPABLE_OPT_VERSION(mpc->sub_ver))); return 1; } if (mpc->flags & MP_CAPABLE_C) ND_PRINT((ndo, " csum")); ND_PRINT((ndo, " {0x%" PRIx64, EXTRACT_64BITS(mpc->sender_key))); if (opt_len == 20) /* ACK */ ND_PRINT((ndo, ",0x%" PRIx64, EXTRACT_64BITS(mpc->receiver_key))); ND_PRINT((ndo, "}")); return 1; }
167,835
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ~ScopedRequest() { if (requested_) { owner_->delegate_->StopEnumerateDevices(request_id_); } } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399
~ScopedRequest() { if (requested_ && owner_->delegate_) { owner_->delegate_->StopEnumerateDevices(request_id_); } }
171,606
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec) { struct drm_vc4_submit_cl *args = exec->args; void *temp = NULL; void *bin; int ret = 0; uint32_t bin_offset = 0; uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size, 16); uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size; uint32_t exec_size = uniforms_offset + args->uniforms_size; uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) * args->shader_rec_count); struct vc4_bo *bo; if (shader_rec_offset < args->bin_cl_size || uniforms_offset < shader_rec_offset || exec_size < uniforms_offset || args->shader_rec_count >= (UINT_MAX / sizeof(struct vc4_shader_state)) || temp_size < exec_size) { DRM_ERROR("overflow in exec arguments\n"); goto fail; } /* Allocate space where we'll store the copied in user command lists * and shader records. * * We don't just copy directly into the BOs because we need to * read the contents back for validation, and I think the * bo->vaddr is uncached access. */ temp = drm_malloc_ab(temp_size, 1); if (!temp) { DRM_ERROR("Failed to allocate storage for copying " "in bin/render CLs.\n"); ret = -ENOMEM; goto fail; } bin = temp + bin_offset; exec->shader_rec_u = temp + shader_rec_offset; exec->uniforms_u = temp + uniforms_offset; exec->shader_state = temp + exec_size; exec->shader_state_size = args->shader_rec_count; if (copy_from_user(bin, (void __user *)(uintptr_t)args->bin_cl, args->bin_cl_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->shader_rec_u, (void __user *)(uintptr_t)args->shader_rec, args->shader_rec_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->uniforms_u, (void __user *)(uintptr_t)args->uniforms, args->uniforms_size)) { ret = -EFAULT; goto fail; } bo = vc4_bo_create(dev, exec_size, true); if (IS_ERR(bo)) { DRM_ERROR("Couldn't allocate BO for binning\n"); ret = PTR_ERR(bo); goto fail; } exec->exec_bo = &bo->base; list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head, &exec->unref_list); exec->ct0ca = exec->exec_bo->paddr + bin_offset; exec->bin_u = bin; exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset; exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset; exec->shader_rec_size = args->shader_rec_size; exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset; exec->uniforms_p = exec->exec_bo->paddr + uniforms_offset; exec->uniforms_size = args->uniforms_size; ret = vc4_validate_bin_cl(dev, exec->exec_bo->vaddr + bin_offset, bin, exec); if (ret) goto fail; ret = vc4_validate_shader_recs(dev, exec); if (ret) goto fail; /* Block waiting on any previous rendering into the CS's VBO, * IB, or textures, so that pixels are actually written by the * time we try to read them. */ ret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true); fail: drm_free_large(temp); return ret; } Commit Message: drm/vc4: Return -EINVAL on the overflow checks failing. By failing to set the errno, we'd continue on to trying to set up the RCL, and then oops on trying to dereference the tile_bo that binning validation should have set up. Reported-by: Ingo Molnar <[email protected]> Signed-off-by: Eric Anholt <[email protected]> Fixes: d5b1a78a772f ("drm/vc4: Add support for drawing 3D frames.") CWE ID: CWE-388
vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec) { struct drm_vc4_submit_cl *args = exec->args; void *temp = NULL; void *bin; int ret = 0; uint32_t bin_offset = 0; uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size, 16); uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size; uint32_t exec_size = uniforms_offset + args->uniforms_size; uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) * args->shader_rec_count); struct vc4_bo *bo; if (shader_rec_offset < args->bin_cl_size || uniforms_offset < shader_rec_offset || exec_size < uniforms_offset || args->shader_rec_count >= (UINT_MAX / sizeof(struct vc4_shader_state)) || temp_size < exec_size) { DRM_ERROR("overflow in exec arguments\n"); ret = -EINVAL; goto fail; } /* Allocate space where we'll store the copied in user command lists * and shader records. * * We don't just copy directly into the BOs because we need to * read the contents back for validation, and I think the * bo->vaddr is uncached access. */ temp = drm_malloc_ab(temp_size, 1); if (!temp) { DRM_ERROR("Failed to allocate storage for copying " "in bin/render CLs.\n"); ret = -ENOMEM; goto fail; } bin = temp + bin_offset; exec->shader_rec_u = temp + shader_rec_offset; exec->uniforms_u = temp + uniforms_offset; exec->shader_state = temp + exec_size; exec->shader_state_size = args->shader_rec_count; if (copy_from_user(bin, (void __user *)(uintptr_t)args->bin_cl, args->bin_cl_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->shader_rec_u, (void __user *)(uintptr_t)args->shader_rec, args->shader_rec_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->uniforms_u, (void __user *)(uintptr_t)args->uniforms, args->uniforms_size)) { ret = -EFAULT; goto fail; } bo = vc4_bo_create(dev, exec_size, true); if (IS_ERR(bo)) { DRM_ERROR("Couldn't allocate BO for binning\n"); ret = PTR_ERR(bo); goto fail; } exec->exec_bo = &bo->base; list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head, &exec->unref_list); exec->ct0ca = exec->exec_bo->paddr + bin_offset; exec->bin_u = bin; exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset; exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset; exec->shader_rec_size = args->shader_rec_size; exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset; exec->uniforms_p = exec->exec_bo->paddr + uniforms_offset; exec->uniforms_size = args->uniforms_size; ret = vc4_validate_bin_cl(dev, exec->exec_bo->vaddr + bin_offset, bin, exec); if (ret) goto fail; ret = vc4_validate_shader_recs(dev, exec); if (ret) goto fail; /* Block waiting on any previous rendering into the CS's VBO, * IB, or textures, so that pixels are actually written by the * time we try to read them. */ ret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true); fail: drm_free_large(temp); return ret; }
168,384
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SendAutomationJSONRequest(AutomationMessageSender* sender, const DictionaryValue& request_dict, DictionaryValue* reply_dict, std::string* error_msg) { std::string request, reply; base::JSONWriter::Write(&request_dict, false, &request); bool success = false; int timeout_ms = TestTimeouts::action_max_timeout_ms(); base::Time before_sending = base::Time::Now(); if (!SendAutomationJSONRequest( sender, request, timeout_ms, &reply, &success)) { int64 elapsed_ms = (base::Time::Now() - before_sending).InMilliseconds(); std::string command; request_dict.GetString("command", &command); if (elapsed_ms >= timeout_ms) { *error_msg = base::StringPrintf( "Chrome did not respond to '%s'. Request may have timed out. " "Elapsed time was %" PRId64 " ms. Request timeout was %d ms. " "Request details: (%s).", command.c_str(), elapsed_ms, timeout_ms, request.c_str()); } else { *error_msg = base::StringPrintf( "Chrome did not respond to '%s'. Elapsed time was %" PRId64 " ms. " "Request details: (%s).", command.c_str(), elapsed_ms, request.c_str()); } return false; } scoped_ptr<Value> value(base::JSONReader::Read(reply, true)); if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) { std::string command; request_dict.GetString("command", &command); LOG(ERROR) << "JSON request did not return dict: " << command << "\n"; return false; } DictionaryValue* dict = static_cast<DictionaryValue*>(value.get()); if (!success) { std::string command, error; request_dict.GetString("command", &command); dict->GetString("error", &error); *error_msg = base::StringPrintf( "Internal Chrome error during '%s': (%s). Request details: (%s).", command.c_str(), error.c_str(), request.c_str()); LOG(ERROR) << "JSON request failed: " << command << "\n" << " with error: " << error; return false; } reply_dict->MergeDictionary(dict); return true; } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool SendAutomationJSONRequest(AutomationMessageSender* sender, const DictionaryValue& request_dict, DictionaryValue* reply_dict, std::string* error_msg) { std::string request, reply; base::JSONWriter::Write(&request_dict, false, &request); std::string command; request_dict.GetString("command", &command); LOG(INFO) << "Sending '" << command << "' command."; base::Time before_sending = base::Time::Now(); bool success = false; if (!SendAutomationJSONRequestWithDefaultTimeout( sender, request, &reply, &success)) { *error_msg = base::StringPrintf( "Chrome did not respond to '%s'. Elapsed time was %" PRId64 " ms. " "Request details: (%s).", command.c_str(), (base::Time::Now() - before_sending).InMilliseconds(), request.c_str()); return false; } scoped_ptr<Value> value(base::JSONReader::Read(reply, true)); if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) { LOG(ERROR) << "JSON request did not return dict: " << command << "\n"; return false; } DictionaryValue* dict = static_cast<DictionaryValue*>(value.get()); if (!success) { std::string error; dict->GetString("error", &error); *error_msg = base::StringPrintf( "Internal Chrome error during '%s': (%s). Request details: (%s).", command.c_str(), error.c_str(), request.c_str()); LOG(ERROR) << "JSON request failed: " << command << "\n" << " with error: " << error; return false; } reply_dict->MergeDictionary(dict); return true; }
170,451
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int phar_verify_signature(php_stream *fp, size_t end_of_phar, php_uint32 sig_type, char *sig, int sig_len, char *fname, char **signature, int *signature_len, char **error) /* {{{ */ { int read_size, len; zend_off_t read_len; unsigned char buf[1024]; php_stream_rewind(fp); switch (sig_type) { case PHAR_SIG_OPENSSL: { #ifdef PHAR_HAVE_OPENSSL BIO *in; EVP_PKEY *key; EVP_MD *mdtype = (EVP_MD *) EVP_sha1(); EVP_MD_CTX md_ctx; #else int tempsig; #endif zend_string *pubkey = NULL; char *pfile; php_stream *pfp; #ifndef PHAR_HAVE_OPENSSL if (!zend_hash_str_exists(&module_registry, "openssl", sizeof("openssl")-1)) { if (error) { spprintf(error, 0, "openssl not loaded"); } return FAILURE; } #endif /* use __FILE__ . '.pubkey' for public key file */ spprintf(&pfile, 0, "%s.pubkey", fname); pfp = php_stream_open_wrapper(pfile, "rb", 0, NULL); efree(pfile); if (!pfp || !(pubkey = php_stream_copy_to_mem(pfp, PHP_STREAM_COPY_ALL, 0)) || !ZSTR_LEN(pubkey)) { if (pfp) { php_stream_close(pfp); } if (error) { spprintf(error, 0, "openssl public key could not be read"); } return FAILURE; } php_stream_close(pfp); #ifndef PHAR_HAVE_OPENSSL tempsig = sig_len; if (FAILURE == phar_call_openssl_signverify(0, fp, end_of_phar, pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0, &sig, &tempsig)) { if (pubkey) { zend_string_release(pubkey); } if (error) { spprintf(error, 0, "openssl signature could not be verified"); } return FAILURE; } if (pubkey) { zend_string_release(pubkey); } sig_len = tempsig; #else in = BIO_new_mem_buf(pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0); if (NULL == in) { zend_string_release(pubkey); if (error) { spprintf(error, 0, "openssl signature could not be processed"); } return FAILURE; } key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL); BIO_free(in); zend_string_release(pubkey); if (NULL == key) { if (error) { spprintf(error, 0, "openssl signature could not be processed"); } return FAILURE; } EVP_VerifyInit(&md_ctx, mdtype); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } php_stream_seek(fp, 0, SEEK_SET); while (read_size && (len = php_stream_read(fp, (char*)buf, read_size)) > 0) { EVP_VerifyUpdate (&md_ctx, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } if (EVP_VerifyFinal(&md_ctx, (unsigned char *)sig, sig_len, key) != 1) { /* 1: signature verified, 0: signature does not match, -1: failed signature operation */ EVP_MD_CTX_cleanup(&md_ctx); if (error) { spprintf(error, 0, "broken openssl signature"); } return FAILURE; } EVP_MD_CTX_cleanup(&md_ctx); #endif *signature_len = phar_hex_str((const char*)sig, sig_len, signature); } break; #ifdef PHAR_HASH_OK case PHAR_SIG_SHA512: { unsigned char digest[64]; PHP_SHA512_CTX context; PHP_SHA512Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA512Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA512Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } case PHAR_SIG_SHA256: { unsigned char digest[32]; PHP_SHA256_CTX context; PHP_SHA256Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA256Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA256Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } #else case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: if (error) { spprintf(error, 0, "unsupported signature"); } return FAILURE; #endif case PHAR_SIG_SHA1: { unsigned char digest[20]; PHP_SHA1_CTX context; PHP_SHA1Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA1Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA1Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } case PHAR_SIG_MD5: { unsigned char digest[16]; PHP_MD5_CTX context; PHP_MD5Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_MD5Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_MD5Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } default: if (error) { spprintf(error, 0, "broken or unsupported signature"); } return FAILURE; } return SUCCESS; } /* }}} */ Commit Message: Fix bug #72928 - Out of bound when verify signature of zip phar in phar_parse_zipfile (cherry picked from commit 19484ab77466f99c78fc0e677f7e03da0584d6a2) CWE ID: CWE-119
int phar_verify_signature(php_stream *fp, size_t end_of_phar, php_uint32 sig_type, char *sig, int sig_len, char *fname, char **signature, int *signature_len, char **error) /* {{{ */ { int read_size, len; zend_off_t read_len; unsigned char buf[1024]; php_stream_rewind(fp); switch (sig_type) { case PHAR_SIG_OPENSSL: { #ifdef PHAR_HAVE_OPENSSL BIO *in; EVP_PKEY *key; EVP_MD *mdtype = (EVP_MD *) EVP_sha1(); EVP_MD_CTX md_ctx; #else int tempsig; #endif zend_string *pubkey = NULL; char *pfile; php_stream *pfp; #ifndef PHAR_HAVE_OPENSSL if (!zend_hash_str_exists(&module_registry, "openssl", sizeof("openssl")-1)) { if (error) { spprintf(error, 0, "openssl not loaded"); } return FAILURE; } #endif /* use __FILE__ . '.pubkey' for public key file */ spprintf(&pfile, 0, "%s.pubkey", fname); pfp = php_stream_open_wrapper(pfile, "rb", 0, NULL); efree(pfile); if (!pfp || !(pubkey = php_stream_copy_to_mem(pfp, PHP_STREAM_COPY_ALL, 0)) || !ZSTR_LEN(pubkey)) { if (pfp) { php_stream_close(pfp); } if (error) { spprintf(error, 0, "openssl public key could not be read"); } return FAILURE; } php_stream_close(pfp); #ifndef PHAR_HAVE_OPENSSL tempsig = sig_len; if (FAILURE == phar_call_openssl_signverify(0, fp, end_of_phar, pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0, &sig, &tempsig)) { if (pubkey) { zend_string_release(pubkey); } if (error) { spprintf(error, 0, "openssl signature could not be verified"); } return FAILURE; } if (pubkey) { zend_string_release(pubkey); } sig_len = tempsig; #else in = BIO_new_mem_buf(pubkey ? ZSTR_VAL(pubkey) : NULL, pubkey ? ZSTR_LEN(pubkey) : 0); if (NULL == in) { zend_string_release(pubkey); if (error) { spprintf(error, 0, "openssl signature could not be processed"); } return FAILURE; } key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL); BIO_free(in); zend_string_release(pubkey); if (NULL == key) { if (error) { spprintf(error, 0, "openssl signature could not be processed"); } return FAILURE; } EVP_VerifyInit(&md_ctx, mdtype); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } php_stream_seek(fp, 0, SEEK_SET); while (read_size && (len = php_stream_read(fp, (char*)buf, read_size)) > 0) { EVP_VerifyUpdate (&md_ctx, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } if (EVP_VerifyFinal(&md_ctx, (unsigned char *)sig, sig_len, key) != 1) { /* 1: signature verified, 0: signature does not match, -1: failed signature operation */ EVP_MD_CTX_cleanup(&md_ctx); if (error) { spprintf(error, 0, "broken openssl signature"); } return FAILURE; } EVP_MD_CTX_cleanup(&md_ctx); #endif *signature_len = phar_hex_str((const char*)sig, sig_len, signature); } break; #ifdef PHAR_HASH_OK case PHAR_SIG_SHA512: { unsigned char digest[64]; PHP_SHA512_CTX context; if (sig_len < sizeof(digest)) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } PHP_SHA512Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA512Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA512Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } case PHAR_SIG_SHA256: { unsigned char digest[32]; PHP_SHA256_CTX context; if (sig_len < sizeof(digest)) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } PHP_SHA256Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA256Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA256Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } #else case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: if (error) { spprintf(error, 0, "unsupported signature"); } return FAILURE; #endif case PHAR_SIG_SHA1: { unsigned char digest[20]; PHP_SHA1_CTX context; if (sig_len < sizeof(digest)) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } PHP_SHA1Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_SHA1Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_SHA1Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } case PHAR_SIG_MD5: { unsigned char digest[16]; PHP_MD5_CTX context; if (sig_len < sizeof(digest)) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } PHP_MD5Init(&context); read_len = end_of_phar; if (read_len > sizeof(buf)) { read_size = sizeof(buf); } else { read_size = (int)read_len; } while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) { PHP_MD5Update(&context, buf, len); read_len -= (zend_off_t)len; if (read_len < read_size) { read_size = (int)read_len; } } PHP_MD5Final(digest, &context); if (memcmp(digest, sig, sizeof(digest))) { if (error) { spprintf(error, 0, "broken signature"); } return FAILURE; } *signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature); break; } default: if (error) { spprintf(error, 0, "broken or unsupported signature"); } return FAILURE; } return SUCCESS; } /* }}} */
166,934
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char* allocFromUTF16(const char16_t* in, size_t len) { if (len == 0) return getEmptyString(); const ssize_t bytes = utf16_to_utf8_length(in, len); if (bytes < 0) { return getEmptyString(); } SharedBuffer* buf = SharedBuffer::alloc(bytes+1); ALOG_ASSERT(buf, "Unable to allocate shared buffer"); if (!buf) { return getEmptyString(); } char* str = (char*)buf->data(); utf16_to_utf8(in, len, str); return str; } Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8 Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length is causing a heap overflow. Correcting the length computation and adding bound checks to the conversion functions. Test: ran libutils_tests Bug: 29250543 Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb (cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1) CWE ID: CWE-119
static char* allocFromUTF16(const char16_t* in, size_t len) { if (len == 0) return getEmptyString(); // Allow for closing '\0' const ssize_t resultStrLen = utf16_to_utf8_length(in, len) + 1; if (resultStrLen < 1) { return getEmptyString(); } SharedBuffer* buf = SharedBuffer::alloc(resultStrLen); ALOG_ASSERT(buf, "Unable to allocate shared buffer"); if (!buf) { return getEmptyString(); } char* resultStr = (char*)buf->data(); utf16_to_utf8(in, len, resultStr, resultStrLen); return resultStr; }
173,417
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebNotificationData createWebNotificationData(ExecutionContext* executionContext, const String& title, const NotificationOptions& options, ExceptionState& exceptionState) { if (options.hasVibrate() && options.silent()) { exceptionState.throwTypeError("Silent notifications must not specify vibration patterns."); return WebNotificationData(); } WebNotificationData webData; webData.title = title; webData.direction = toDirectionEnumValue(options.dir()); webData.lang = options.lang(); webData.body = options.body(); webData.tag = options.tag(); KURL iconUrl; iconUrl = executionContext->completeURL(options.icon()); if (!iconUrl.isValid()) iconUrl = KURL(); } webData.icon = iconUrl; webData.vibrate = NavigatorVibration::sanitizeVibrationPattern(options.vibrate()); webData.timestamp = options.hasTimestamp() ? static_cast<double>(options.timestamp()) : WTF::currentTimeMS(); webData.silent = options.silent(); webData.requireInteraction = options.requireInteraction(); if (options.hasData()) { RefPtr<SerializedScriptValue> serializedScriptValue = SerializedScriptValueFactory::instance().create(options.data().isolate(), options.data(), nullptr, exceptionState); if (exceptionState.hadException()) return WebNotificationData(); Vector<char> serializedData; serializedScriptValue->toWireBytes(serializedData); webData.data = serializedData; } Vector<WebNotificationAction> actions; const size_t maxActions = Notification::maxActions(); for (const NotificationAction& action : options.actions()) { if (actions.size() >= maxActions) break; WebNotificationAction webAction; webAction.action = action.action(); webAction.title = action.title(); actions.append(webAction); } webData.actions = actions; return webData; } Commit Message: Notification actions may have an icon url. This is behind a runtime flag for two reasons: * The implementation is incomplete. * We're still evaluating the API design. Intent to Implement and Ship: Notification Action Icons https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ BUG=581336 Review URL: https://codereview.chromium.org/1644573002 Cr-Commit-Position: refs/heads/master@{#374649} CWE ID:
WebNotificationData createWebNotificationData(ExecutionContext* executionContext, const String& title, const NotificationOptions& options, ExceptionState& exceptionState) { if (options.hasVibrate() && options.silent()) { exceptionState.throwTypeError("Silent notifications must not specify vibration patterns."); return WebNotificationData(); } WebNotificationData webData; webData.title = title; webData.direction = toDirectionEnumValue(options.dir()); webData.lang = options.lang(); webData.body = options.body(); webData.tag = options.tag(); KURL iconUrl; iconUrl = executionContext->completeURL(options.icon()); if (!iconUrl.isValid()) iconUrl = KURL(); } webData.icon = iconUrl; webData.vibrate = NavigatorVibration::sanitizeVibrationPattern(options.vibrate()); webData.timestamp = options.hasTimestamp() ? static_cast<double>(options.timestamp()) : WTF::currentTimeMS(); webData.silent = options.silent(); webData.requireInteraction = options.requireInteraction(); if (options.hasData()) { RefPtr<SerializedScriptValue> serializedScriptValue = SerializedScriptValueFactory::instance().create(options.data().isolate(), options.data(), nullptr, exceptionState); if (exceptionState.hadException()) return WebNotificationData(); Vector<char> serializedData; serializedScriptValue->toWireBytes(serializedData); webData.data = serializedData; } Vector<WebNotificationAction> actions; const size_t maxActions = Notification::maxActions(); for (const NotificationAction& action : options.actions()) { if (actions.size() >= maxActions) break; WebNotificationAction webAction; webAction.action = action.action(); webAction.title = action.title(); KURL iconUrl; if (action.hasIcon() && !action.icon().isEmpty()) { iconUrl = executionContext->completeURL(action.icon()); if (!iconUrl.isValid()) iconUrl = KURL(); } webAction.icon = iconUrl; actions.append(webAction); } webData.actions = actions; return webData; }
171,634
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: svc_rdma_is_backchannel_reply(struct svc_xprt *xprt, struct rpcrdma_msg *rmsgp) { __be32 *p = (__be32 *)rmsgp; if (!xprt->xpt_bc_xprt) return false; if (rmsgp->rm_type != rdma_msg) return false; if (rmsgp->rm_body.rm_chunks[0] != xdr_zero) return false; if (rmsgp->rm_body.rm_chunks[1] != xdr_zero) return false; if (rmsgp->rm_body.rm_chunks[2] != xdr_zero) return false; /* sanity */ if (p[7] != rmsgp->rm_xid) return false; /* call direction */ if (p[8] == cpu_to_be32(RPC_CALL)) return false; return true; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
svc_rdma_is_backchannel_reply(struct svc_xprt *xprt, struct rpcrdma_msg *rmsgp) static bool svc_rdma_is_backchannel_reply(struct svc_xprt *xprt, __be32 *rdma_resp) { __be32 *p; if (!xprt->xpt_bc_xprt) return false; p = rdma_resp + 3; if (*p++ != rdma_msg) return false; if (*p++ != xdr_zero) return false; if (*p++ != xdr_zero) return false; if (*p++ != xdr_zero) return false; /* XID sanity */ if (*p++ != *rdma_resp) return false; /* call direction */ if (*p == cpu_to_be32(RPC_CALL)) return false; return true; }
168,164
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FolderHeaderView::SetFolderItem(AppListFolderItem* folder_item) { if (folder_item_) folder_item_->RemoveObserver(this); folder_item_ = folder_item; if (!folder_item_) return; folder_item_->AddObserver(this); folder_name_view_->SetEnabled(folder_item->folder_type() != AppListFolderItem::FOLDER_TYPE_OEM); Update(); } Commit Message: Enforce the maximum length of the folder name in UI. BUG=355797 [email protected] Review URL: https://codereview.chromium.org/203863005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260156 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void FolderHeaderView::SetFolderItem(AppListFolderItem* folder_item) { if (folder_item_) folder_item_->RemoveObserver(this); folder_item_ = folder_item; if (!folder_item_) return; folder_item_->AddObserver(this); folder_name_view_->SetEnabled(folder_item_->folder_type() != AppListFolderItem::FOLDER_TYPE_OEM); Update(); }
171,201
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ConfigureQuicParams(base::StringPiece quic_trial_group, const VariationParameters& quic_trial_params, bool is_quic_force_disabled, bool is_quic_force_enabled, const std::string& quic_user_agent_id, net::HttpNetworkSession::Params* params) { params->enable_quic = ShouldEnableQuic(quic_trial_group, quic_trial_params, is_quic_force_disabled, is_quic_force_enabled); params->mark_quic_broken_when_network_blackholes = ShouldMarkQuicBrokenWhenNetworkBlackholes(quic_trial_params); params->enable_server_push_cancellation = ShouldEnableServerPushCancelation(quic_trial_params); params->retry_without_alt_svc_on_quic_errors = ShouldRetryWithoutAltSvcOnQuicErrors(quic_trial_params); params->support_ietf_format_quic_altsvc = ShouldSupportIetfFormatQuicAltSvc(quic_trial_params); if (params->enable_quic) { params->enable_quic_proxies_for_https_urls = ShouldEnableQuicProxiesForHttpsUrls(quic_trial_params); params->enable_quic_proxies_for_https_urls = false; params->quic_connection_options = GetQuicConnectionOptions(quic_trial_params); params->quic_client_connection_options = GetQuicClientConnectionOptions(quic_trial_params); params->quic_close_sessions_on_ip_change = ShouldQuicCloseSessionsOnIpChange(quic_trial_params); params->quic_goaway_sessions_on_ip_change = ShouldQuicGoAwaySessionsOnIpChange(quic_trial_params); int idle_connection_timeout_seconds = GetQuicIdleConnectionTimeoutSeconds(quic_trial_params); if (idle_connection_timeout_seconds != 0) { params->quic_idle_connection_timeout_seconds = idle_connection_timeout_seconds; } int reduced_ping_timeout_seconds = GetQuicReducedPingTimeoutSeconds(quic_trial_params); if (reduced_ping_timeout_seconds > 0 && reduced_ping_timeout_seconds < quic::kPingTimeoutSecs) { params->quic_reduced_ping_timeout_seconds = reduced_ping_timeout_seconds; } int max_time_before_crypto_handshake_seconds = GetQuicMaxTimeBeforeCryptoHandshakeSeconds(quic_trial_params); if (max_time_before_crypto_handshake_seconds > 0) { params->quic_max_time_before_crypto_handshake_seconds = max_time_before_crypto_handshake_seconds; } int max_idle_time_before_crypto_handshake_seconds = GetQuicMaxIdleTimeBeforeCryptoHandshakeSeconds(quic_trial_params); if (max_idle_time_before_crypto_handshake_seconds > 0) { params->quic_max_idle_time_before_crypto_handshake_seconds = max_idle_time_before_crypto_handshake_seconds; } params->quic_race_cert_verification = ShouldQuicRaceCertVerification(quic_trial_params); params->quic_estimate_initial_rtt = ShouldQuicEstimateInitialRtt(quic_trial_params); params->quic_headers_include_h2_stream_dependency = ShouldQuicHeadersIncludeH2StreamDependencies(quic_trial_params); params->quic_migrate_sessions_on_network_change_v2 = ShouldQuicMigrateSessionsOnNetworkChangeV2(quic_trial_params); params->quic_migrate_sessions_early_v2 = ShouldQuicMigrateSessionsEarlyV2(quic_trial_params); params->quic_retry_on_alternate_network_before_handshake = ShouldQuicRetryOnAlternateNetworkBeforeHandshake(quic_trial_params); params->quic_go_away_on_path_degrading = ShouldQuicGoawayOnPathDegrading(quic_trial_params); params->quic_race_stale_dns_on_connection = ShouldQuicRaceStaleDNSOnConnection(quic_trial_params); int max_time_on_non_default_network_seconds = GetQuicMaxTimeOnNonDefaultNetworkSeconds(quic_trial_params); if (max_time_on_non_default_network_seconds > 0) { params->quic_max_time_on_non_default_network = base::TimeDelta::FromSeconds(max_time_on_non_default_network_seconds); } int max_migrations_to_non_default_network_on_write_error = GetQuicMaxNumMigrationsToNonDefaultNetworkOnWriteError( quic_trial_params); if (max_migrations_to_non_default_network_on_write_error > 0) { params->quic_max_migrations_to_non_default_network_on_write_error = max_migrations_to_non_default_network_on_write_error; } int max_migrations_to_non_default_network_on_path_degrading = GetQuicMaxNumMigrationsToNonDefaultNetworkOnPathDegrading( quic_trial_params); if (max_migrations_to_non_default_network_on_path_degrading > 0) { params->quic_max_migrations_to_non_default_network_on_path_degrading = max_migrations_to_non_default_network_on_path_degrading; } params->quic_allow_server_migration = ShouldQuicAllowServerMigration(quic_trial_params); params->quic_host_whitelist = GetQuicHostWhitelist(quic_trial_params); } size_t max_packet_length = GetQuicMaxPacketLength(quic_trial_params); if (max_packet_length != 0) { params->quic_max_packet_length = max_packet_length; } params->quic_user_agent_id = quic_user_agent_id; quic::QuicTransportVersionVector supported_versions = GetQuicVersions(quic_trial_params); if (!supported_versions.empty()) params->quic_supported_versions = supported_versions; } Commit Message: Fix a bug in network_session_configurator.cc in which support for HTTPS URLS in QUIC proxies was always set to false. BUG=914497 Change-Id: I56ad16088168302598bb448553ba32795eee3756 Reviewed-on: https://chromium-review.googlesource.com/c/1417356 Auto-Submit: Ryan Hamilton <[email protected]> Commit-Queue: Zhongyi Shi <[email protected]> Reviewed-by: Zhongyi Shi <[email protected]> Cr-Commit-Position: refs/heads/master@{#623763} CWE ID: CWE-310
void ConfigureQuicParams(base::StringPiece quic_trial_group, const VariationParameters& quic_trial_params, bool is_quic_force_disabled, bool is_quic_force_enabled, const std::string& quic_user_agent_id, net::HttpNetworkSession::Params* params) { params->enable_quic = ShouldEnableQuic(quic_trial_group, quic_trial_params, is_quic_force_disabled, is_quic_force_enabled); params->mark_quic_broken_when_network_blackholes = ShouldMarkQuicBrokenWhenNetworkBlackholes(quic_trial_params); params->enable_server_push_cancellation = ShouldEnableServerPushCancelation(quic_trial_params); params->retry_without_alt_svc_on_quic_errors = ShouldRetryWithoutAltSvcOnQuicErrors(quic_trial_params); params->support_ietf_format_quic_altsvc = ShouldSupportIetfFormatQuicAltSvc(quic_trial_params); if (params->enable_quic) { params->enable_quic_proxies_for_https_urls = ShouldEnableQuicProxiesForHttpsUrls(quic_trial_params); params->quic_connection_options = GetQuicConnectionOptions(quic_trial_params); params->quic_client_connection_options = GetQuicClientConnectionOptions(quic_trial_params); params->quic_close_sessions_on_ip_change = ShouldQuicCloseSessionsOnIpChange(quic_trial_params); params->quic_goaway_sessions_on_ip_change = ShouldQuicGoAwaySessionsOnIpChange(quic_trial_params); int idle_connection_timeout_seconds = GetQuicIdleConnectionTimeoutSeconds(quic_trial_params); if (idle_connection_timeout_seconds != 0) { params->quic_idle_connection_timeout_seconds = idle_connection_timeout_seconds; } int reduced_ping_timeout_seconds = GetQuicReducedPingTimeoutSeconds(quic_trial_params); if (reduced_ping_timeout_seconds > 0 && reduced_ping_timeout_seconds < quic::kPingTimeoutSecs) { params->quic_reduced_ping_timeout_seconds = reduced_ping_timeout_seconds; } int max_time_before_crypto_handshake_seconds = GetQuicMaxTimeBeforeCryptoHandshakeSeconds(quic_trial_params); if (max_time_before_crypto_handshake_seconds > 0) { params->quic_max_time_before_crypto_handshake_seconds = max_time_before_crypto_handshake_seconds; } int max_idle_time_before_crypto_handshake_seconds = GetQuicMaxIdleTimeBeforeCryptoHandshakeSeconds(quic_trial_params); if (max_idle_time_before_crypto_handshake_seconds > 0) { params->quic_max_idle_time_before_crypto_handshake_seconds = max_idle_time_before_crypto_handshake_seconds; } params->quic_race_cert_verification = ShouldQuicRaceCertVerification(quic_trial_params); params->quic_estimate_initial_rtt = ShouldQuicEstimateInitialRtt(quic_trial_params); params->quic_headers_include_h2_stream_dependency = ShouldQuicHeadersIncludeH2StreamDependencies(quic_trial_params); params->quic_migrate_sessions_on_network_change_v2 = ShouldQuicMigrateSessionsOnNetworkChangeV2(quic_trial_params); params->quic_migrate_sessions_early_v2 = ShouldQuicMigrateSessionsEarlyV2(quic_trial_params); params->quic_retry_on_alternate_network_before_handshake = ShouldQuicRetryOnAlternateNetworkBeforeHandshake(quic_trial_params); params->quic_go_away_on_path_degrading = ShouldQuicGoawayOnPathDegrading(quic_trial_params); params->quic_race_stale_dns_on_connection = ShouldQuicRaceStaleDNSOnConnection(quic_trial_params); int max_time_on_non_default_network_seconds = GetQuicMaxTimeOnNonDefaultNetworkSeconds(quic_trial_params); if (max_time_on_non_default_network_seconds > 0) { params->quic_max_time_on_non_default_network = base::TimeDelta::FromSeconds(max_time_on_non_default_network_seconds); } int max_migrations_to_non_default_network_on_write_error = GetQuicMaxNumMigrationsToNonDefaultNetworkOnWriteError( quic_trial_params); if (max_migrations_to_non_default_network_on_write_error > 0) { params->quic_max_migrations_to_non_default_network_on_write_error = max_migrations_to_non_default_network_on_write_error; } int max_migrations_to_non_default_network_on_path_degrading = GetQuicMaxNumMigrationsToNonDefaultNetworkOnPathDegrading( quic_trial_params); if (max_migrations_to_non_default_network_on_path_degrading > 0) { params->quic_max_migrations_to_non_default_network_on_path_degrading = max_migrations_to_non_default_network_on_path_degrading; } params->quic_allow_server_migration = ShouldQuicAllowServerMigration(quic_trial_params); params->quic_host_whitelist = GetQuicHostWhitelist(quic_trial_params); } size_t max_packet_length = GetQuicMaxPacketLength(quic_trial_params); if (max_packet_length != 0) { params->quic_max_packet_length = max_packet_length; } params->quic_user_agent_id = quic_user_agent_id; quic::QuicTransportVersionVector supported_versions = GetQuicVersions(quic_trial_params); if (!supported_versions.empty()) params->quic_supported_versions = supported_versions; }
173,064
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *print_object( cJSON *item, int depth, int fmt ) { char **entries = 0, **names = 0; char *out = 0, *ptr, *ret, *str; int len = 7, i = 0, j; cJSON *child = item->child; int numentries = 0, fail = 0; /* Count the number of entries. */ while ( child ) { ++numentries; child = child->next; } /* Allocate space for the names and the objects. */ if ( ! ( entries = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) ) return 0; if ( ! ( names = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) ) { cJSON_free( entries ); return 0; } memset( entries, 0, sizeof(char*) * numentries ); memset( names, 0, sizeof(char*) * numentries ); /* Collect all the results into our arrays. */ child = item->child; ++depth; if ( fmt ) len += depth; while ( child ) { names[i] = str = print_string_ptr( child->string ); entries[i++] = ret = print_value( child, depth, fmt ); if ( str && ret ) len += strlen( ret ) + strlen( str ) + 2 + ( fmt ? 2 + depth : 0 ); else fail = 1; child = child->next; } /* Try to allocate the output string. */ if ( ! fail ) { out = (char*) cJSON_malloc( len ); if ( ! out ) fail = 1; } /* Handle failure. */ if ( fail ) { for ( i = 0; i < numentries; ++i ) { if ( names[i] ) cJSON_free( names[i] ); if ( entries[i] ) cJSON_free( entries[i] ); } cJSON_free( names ); cJSON_free( entries ); return 0; } /* Compose the output. */ *out = '{'; ptr = out + 1; if ( fmt ) *ptr++ = '\n'; *ptr = 0; for ( i = 0; i < numentries; ++i ) { if ( fmt ) for ( j = 0; j < depth; ++j ) *ptr++ = '\t'; strcpy( ptr, names[i] ); ptr += strlen( names[i] ); *ptr++ = ':'; if ( fmt ) *ptr++ = '\t'; strcpy( ptr, entries[i] ); ptr += strlen( entries[i] ); if ( i != numentries - 1 ) *ptr++ = ','; if ( fmt ) *ptr++ = '\n'; *ptr = 0; cJSON_free( names[i] ); cJSON_free( entries[i] ); } cJSON_free( names ); cJSON_free( entries ); if ( fmt ) for ( i = 0; i < depth - 1; ++i ) *ptr++ = '\t'; *ptr++ = '}'; *ptr++ = 0; return out; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static char *print_object( cJSON *item, int depth, int fmt ) static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p) { char **entries=0,**names=0; char *out=0,*ptr,*ret,*str;int len=7,i=0,j; cJSON *child=item->child; int numentries=0,fail=0; size_t tmplen=0; /* Count the number of entries. */ while (child) numentries++,child=child->next; /* Explicitly handle empty object case */ if (!numentries) { if (p) out=ensure(p,fmt?depth+4:3); else out=(char*)cJSON_malloc(fmt?depth+4:3); if (!out) return 0; ptr=out;*ptr++='{'; if (fmt) {*ptr++='\n';for (i=0;i<depth;i++) *ptr++='\t';} *ptr++='}';*ptr++=0; return out; } if (p) { /* Compose the output: */ i=p->offset; len=fmt?2:1; ptr=ensure(p,len+1); if (!ptr) return 0; *ptr++='{'; if (fmt) *ptr++='\n'; *ptr=0; p->offset+=len; child=item->child;depth++; while (child) { if (fmt) { ptr=ensure(p,depth); if (!ptr) return 0; for (j=0;j<depth;j++) *ptr++='\t'; p->offset+=depth; } print_string_ptr(child->string,p); p->offset=update(p); len=fmt?2:1; ptr=ensure(p,len); if (!ptr) return 0; *ptr++=':';if (fmt) *ptr++='\t'; p->offset+=len; print_value(child,depth,fmt,p); p->offset=update(p); len=(fmt?1:0)+(child->next?1:0); ptr=ensure(p,len+1); if (!ptr) return 0; if (child->next) *ptr++=','; if (fmt) *ptr++='\n';*ptr=0; p->offset+=len; child=child->next; } ptr=ensure(p,fmt?(depth+1):2); if (!ptr) return 0; if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t'; *ptr++='}';*ptr=0; out=(p->buffer)+i; } else { /* Allocate space for the names and the objects */ entries=(char**)cJSON_malloc(numentries*sizeof(char*)); if (!entries) return 0; names=(char**)cJSON_malloc(numentries*sizeof(char*)); if (!names) {cJSON_free(entries);return 0;} memset(entries,0,sizeof(char*)*numentries); memset(names,0,sizeof(char*)*numentries); /* Collect all the results into our arrays: */ child=item->child;depth++;if (fmt) len+=depth; while (child && !fail) { names[i]=str=print_string_ptr(child->string,0); entries[i++]=ret=print_value(child,depth,fmt,0); if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1; child=child->next; } /* Try to allocate the output string */ if (!fail) out=(char*)cJSON_malloc(len); if (!out) fail=1; /* Handle failure */ if (fail) { for (i=0;i<numentries;i++) {if (names[i]) cJSON_free(names[i]);if (entries[i]) cJSON_free(entries[i]);} cJSON_free(names);cJSON_free(entries); return 0; } /* Compose the output: */ *out='{';ptr=out+1;if (fmt)*ptr++='\n';*ptr=0; for (i=0;i<numentries;i++) { if (fmt) for (j=0;j<depth;j++) *ptr++='\t'; tmplen=strlen(names[i]);memcpy(ptr,names[i],tmplen);ptr+=tmplen; *ptr++=':';if (fmt) *ptr++='\t'; strcpy(ptr,entries[i]);ptr+=strlen(entries[i]); if (i!=numentries-1) *ptr++=','; if (fmt) *ptr++='\n';*ptr=0; cJSON_free(names[i]);cJSON_free(entries[i]); } cJSON_free(names);cJSON_free(entries); if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t'; *ptr++='}';*ptr++=0; } return out; }
167,308
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: __xfs_get_blocks( struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create, bool direct, bool dax_fault) { struct xfs_inode *ip = XFS_I(inode); struct xfs_mount *mp = ip->i_mount; xfs_fileoff_t offset_fsb, end_fsb; int error = 0; int lockmode = 0; struct xfs_bmbt_irec imap; int nimaps = 1; xfs_off_t offset; ssize_t size; int new = 0; bool is_cow = false; bool need_alloc = false; BUG_ON(create && !direct); if (XFS_FORCED_SHUTDOWN(mp)) return -EIO; offset = (xfs_off_t)iblock << inode->i_blkbits; ASSERT(bh_result->b_size >= (1 << inode->i_blkbits)); size = bh_result->b_size; if (!create && offset >= i_size_read(inode)) return 0; /* * Direct I/O is usually done on preallocated files, so try getting * a block mapping without an exclusive lock first. */ lockmode = xfs_ilock_data_map_shared(ip); ASSERT(offset <= mp->m_super->s_maxbytes); if (offset + size > mp->m_super->s_maxbytes) size = mp->m_super->s_maxbytes - offset; end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + size); offset_fsb = XFS_B_TO_FSBT(mp, offset); if (create && direct && xfs_is_reflink_inode(ip)) is_cow = xfs_reflink_find_cow_mapping(ip, offset, &imap, &need_alloc); if (!is_cow) { error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap, &nimaps, XFS_BMAPI_ENTIRE); /* * Truncate an overwrite extent if there's a pending CoW * reservation before the end of this extent. This * forces us to come back to get_blocks to take care of * the CoW. */ if (create && direct && nimaps && imap.br_startblock != HOLESTARTBLOCK && imap.br_startblock != DELAYSTARTBLOCK && !ISUNWRITTEN(&imap)) xfs_reflink_trim_irec_to_next_cow(ip, offset_fsb, &imap); } ASSERT(!need_alloc); if (error) goto out_unlock; /* for DAX, we convert unwritten extents directly */ if (create && (!nimaps || (imap.br_startblock == HOLESTARTBLOCK || imap.br_startblock == DELAYSTARTBLOCK) || (IS_DAX(inode) && ISUNWRITTEN(&imap)))) { /* * xfs_iomap_write_direct() expects the shared lock. It * is unlocked on return. */ if (lockmode == XFS_ILOCK_EXCL) xfs_ilock_demote(ip, lockmode); error = xfs_iomap_write_direct(ip, offset, size, &imap, nimaps); if (error) return error; new = 1; trace_xfs_get_blocks_alloc(ip, offset, size, ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN : XFS_IO_DELALLOC, &imap); } else if (nimaps) { trace_xfs_get_blocks_found(ip, offset, size, ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN : XFS_IO_OVERWRITE, &imap); xfs_iunlock(ip, lockmode); } else { trace_xfs_get_blocks_notfound(ip, offset, size); goto out_unlock; } if (IS_DAX(inode) && create) { ASSERT(!ISUNWRITTEN(&imap)); /* zeroing is not needed at a higher layer */ new = 0; } /* trim mapping down to size requested */ xfs_map_trim_size(inode, iblock, bh_result, &imap, offset, size); /* * For unwritten extents do not report a disk address in the buffered * read case (treat as if we're reading into a hole). */ if (imap.br_startblock != HOLESTARTBLOCK && imap.br_startblock != DELAYSTARTBLOCK && (create || !ISUNWRITTEN(&imap))) { if (create && direct && !is_cow) { error = xfs_bounce_unaligned_dio_write(ip, offset_fsb, &imap); if (error) return error; } xfs_map_buffer(inode, bh_result, &imap, offset); if (ISUNWRITTEN(&imap)) set_buffer_unwritten(bh_result); /* direct IO needs special help */ if (create) { if (dax_fault) ASSERT(!ISUNWRITTEN(&imap)); else xfs_map_direct(inode, bh_result, &imap, offset, is_cow); } } /* * If this is a realtime file, data may be on a different device. * to that pointed to from the buffer_head b_bdev currently. */ bh_result->b_bdev = xfs_find_bdev_for_inode(inode); /* * If we previously allocated a block out beyond eof and we are now * coming back to use it then we will need to flag it as new even if it * has a disk address. * * With sub-block writes into unwritten extents we also need to mark * the buffer as new so that the unwritten parts of the buffer gets * correctly zeroed. */ if (create && ((!buffer_mapped(bh_result) && !buffer_uptodate(bh_result)) || (offset >= i_size_read(inode)) || (new || ISUNWRITTEN(&imap)))) set_buffer_new(bh_result); BUG_ON(direct && imap.br_startblock == DELAYSTARTBLOCK); return 0; out_unlock: xfs_iunlock(ip, lockmode); return error; } Commit Message: xfs: don't BUG() on mixed direct and mapped I/O We've had reports of generic/095 causing XFS to BUG() in __xfs_get_blocks() due to the existence of delalloc blocks on a direct I/O read. generic/095 issues a mix of various types of I/O, including direct and memory mapped I/O to a single file. This is clearly not supported behavior and is known to lead to such problems. E.g., the lack of exclusion between the direct I/O and write fault paths means that a write fault can allocate delalloc blocks in a region of a file that was previously a hole after the direct read has attempted to flush/inval the file range, but before it actually reads the block mapping. In turn, the direct read discovers a delalloc extent and cannot proceed. While the appropriate solution here is to not mix direct and memory mapped I/O to the same regions of the same file, the current BUG_ON() behavior is probably overkill as it can crash the entire system. Instead, localize the failure to the I/O in question by returning an error for a direct I/O that cannot be handled safely due to delalloc blocks. Be careful to allow the case of a direct write to post-eof delalloc blocks. This can occur due to speculative preallocation and is safe as post-eof blocks are not accompanied by dirty pages in pagecache (conversely, preallocation within eof must have been zeroed, and thus dirtied, before the inode size could have been increased beyond said blocks). Finally, provide an additional warning if a direct I/O write occurs while the file is memory mapped. This may not catch all problematic scenarios, but provides a hint that some known-to-be-problematic I/O methods are in use. Signed-off-by: Brian Foster <[email protected]> Reviewed-by: Dave Chinner <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-362
__xfs_get_blocks( struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create, bool direct, bool dax_fault) { struct xfs_inode *ip = XFS_I(inode); struct xfs_mount *mp = ip->i_mount; xfs_fileoff_t offset_fsb, end_fsb; int error = 0; int lockmode = 0; struct xfs_bmbt_irec imap; int nimaps = 1; xfs_off_t offset; ssize_t size; int new = 0; bool is_cow = false; bool need_alloc = false; BUG_ON(create && !direct); if (XFS_FORCED_SHUTDOWN(mp)) return -EIO; offset = (xfs_off_t)iblock << inode->i_blkbits; ASSERT(bh_result->b_size >= (1 << inode->i_blkbits)); size = bh_result->b_size; if (!create && offset >= i_size_read(inode)) return 0; /* * Direct I/O is usually done on preallocated files, so try getting * a block mapping without an exclusive lock first. */ lockmode = xfs_ilock_data_map_shared(ip); ASSERT(offset <= mp->m_super->s_maxbytes); if (offset + size > mp->m_super->s_maxbytes) size = mp->m_super->s_maxbytes - offset; end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + size); offset_fsb = XFS_B_TO_FSBT(mp, offset); if (create && direct && xfs_is_reflink_inode(ip)) is_cow = xfs_reflink_find_cow_mapping(ip, offset, &imap, &need_alloc); if (!is_cow) { error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap, &nimaps, XFS_BMAPI_ENTIRE); /* * Truncate an overwrite extent if there's a pending CoW * reservation before the end of this extent. This * forces us to come back to get_blocks to take care of * the CoW. */ if (create && direct && nimaps && imap.br_startblock != HOLESTARTBLOCK && imap.br_startblock != DELAYSTARTBLOCK && !ISUNWRITTEN(&imap)) xfs_reflink_trim_irec_to_next_cow(ip, offset_fsb, &imap); } ASSERT(!need_alloc); if (error) goto out_unlock; /* * The only time we can ever safely find delalloc blocks on direct I/O * is a dio write to post-eof speculative preallocation. All other * scenarios are indicative of a problem or misuse (such as mixing * direct and mapped I/O). * * The file may be unmapped by the time we get here so we cannot * reliably fail the I/O based on mapping. Instead, fail the I/O if this * is a read or a write within eof. Otherwise, carry on but warn as a * precuation if the file happens to be mapped. */ if (direct && imap.br_startblock == DELAYSTARTBLOCK) { if (!create || offset < i_size_read(VFS_I(ip))) { WARN_ON_ONCE(1); error = -EIO; goto out_unlock; } WARN_ON_ONCE(mapping_mapped(VFS_I(ip)->i_mapping)); } /* for DAX, we convert unwritten extents directly */ if (create && (!nimaps || (imap.br_startblock == HOLESTARTBLOCK || imap.br_startblock == DELAYSTARTBLOCK) || (IS_DAX(inode) && ISUNWRITTEN(&imap)))) { /* * xfs_iomap_write_direct() expects the shared lock. It * is unlocked on return. */ if (lockmode == XFS_ILOCK_EXCL) xfs_ilock_demote(ip, lockmode); error = xfs_iomap_write_direct(ip, offset, size, &imap, nimaps); if (error) return error; new = 1; trace_xfs_get_blocks_alloc(ip, offset, size, ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN : XFS_IO_DELALLOC, &imap); } else if (nimaps) { trace_xfs_get_blocks_found(ip, offset, size, ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN : XFS_IO_OVERWRITE, &imap); xfs_iunlock(ip, lockmode); } else { trace_xfs_get_blocks_notfound(ip, offset, size); goto out_unlock; } if (IS_DAX(inode) && create) { ASSERT(!ISUNWRITTEN(&imap)); /* zeroing is not needed at a higher layer */ new = 0; } /* trim mapping down to size requested */ xfs_map_trim_size(inode, iblock, bh_result, &imap, offset, size); /* * For unwritten extents do not report a disk address in the buffered * read case (treat as if we're reading into a hole). */ if (imap.br_startblock != HOLESTARTBLOCK && imap.br_startblock != DELAYSTARTBLOCK && (create || !ISUNWRITTEN(&imap))) { if (create && direct && !is_cow) { error = xfs_bounce_unaligned_dio_write(ip, offset_fsb, &imap); if (error) return error; } xfs_map_buffer(inode, bh_result, &imap, offset); if (ISUNWRITTEN(&imap)) set_buffer_unwritten(bh_result); /* direct IO needs special help */ if (create) { if (dax_fault) ASSERT(!ISUNWRITTEN(&imap)); else xfs_map_direct(inode, bh_result, &imap, offset, is_cow); } } /* * If this is a realtime file, data may be on a different device. * to that pointed to from the buffer_head b_bdev currently. */ bh_result->b_bdev = xfs_find_bdev_for_inode(inode); /* * If we previously allocated a block out beyond eof and we are now * coming back to use it then we will need to flag it as new even if it * has a disk address. * * With sub-block writes into unwritten extents we also need to mark * the buffer as new so that the unwritten parts of the buffer gets * correctly zeroed. */ if (create && ((!buffer_mapped(bh_result) && !buffer_uptodate(bh_result)) || (offset >= i_size_read(inode)) || (new || ISUNWRITTEN(&imap)))) set_buffer_new(bh_result); return 0; out_unlock: xfs_iunlock(ip, lockmode); return error; }
169,864
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void copyStereo8( short *dst, const int *const *src, unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i] << 8; *dst++ = src[1][i] << 8; } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyStereo8( short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i] << 8; *dst++ = src[1][i] << 8; } }
174,023
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_get_val (MyObject *obj, guint *ret, GError **error) { *ret = obj->val; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_get_val (MyObject *obj, guint *ret, GError **error)
165,103
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields, unsigned int field_count, const MYSQLND_FIELD * fields_metadata, zend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC) { unsigned int i; zend_bool last_field_was_string = FALSE; zval **current_field, **end_field, **start_field; zend_uchar * p = row_buffer->ptr; size_t data_size = row_buffer->app; zend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */ DBG_ENTER("php_mysqlnd_rowp_read_text_protocol_aux"); if (!fields) { DBG_RETURN(FAIL); } end_field = (start_field = fields) + field_count; for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { DBG_INF("Directly creating zval"); MAKE_STD_ZVAL(*current_field); if (!*current_field) { DBG_RETURN(FAIL); } } for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { /* Don't reverse the order. It is significant!*/ zend_uchar *this_field_len_pos = p; /* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */ unsigned long len = php_mysqlnd_net_field_length(&p); if (copy_data == FALSE && current_field > start_field && last_field_was_string) { /* Normal queries: We have to put \0 now to the end of the previous field, if it was a string. IS_NULL doesn't matter. Because we have already read our length, then we can overwrite it in the row buffer. This statement terminates the previous field, not the current one. NULL_LENGTH is encoded in one byte, so we can stick a \0 there. Any string's length is encoded in at least one byte, so we can stick a \0 there. */ *this_field_len_pos = '\0'; } /* NULL or NOT NULL, this is the question! */ if (len == MYSQLND_NULL_LENGTH) { ZVAL_NULL(*current_field); last_field_was_string = FALSE; } else { #if defined(MYSQLND_STRING_TO_INT_CONVERSION) struct st_mysqlnd_perm_bind perm_bind = mysqlnd_ps_fetch_functions[fields_metadata[i].type]; #endif if (MYSQLND_G(collect_statistics)) { enum_mysqlnd_collected_stats statistic; switch (fields_metadata[i].type) { case MYSQL_TYPE_DECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_TINY: statistic = STAT_TEXT_TYPE_FETCHED_INT8; break; case MYSQL_TYPE_SHORT: statistic = STAT_TEXT_TYPE_FETCHED_INT16; break; case MYSQL_TYPE_LONG: statistic = STAT_TEXT_TYPE_FETCHED_INT32; break; case MYSQL_TYPE_FLOAT: statistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break; case MYSQL_TYPE_DOUBLE: statistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break; case MYSQL_TYPE_NULL: statistic = STAT_TEXT_TYPE_FETCHED_NULL; break; case MYSQL_TYPE_TIMESTAMP: statistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break; case MYSQL_TYPE_LONGLONG: statistic = STAT_TEXT_TYPE_FETCHED_INT64; break; case MYSQL_TYPE_INT24: statistic = STAT_TEXT_TYPE_FETCHED_INT24; break; case MYSQL_TYPE_DATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_TIME: statistic = STAT_TEXT_TYPE_FETCHED_TIME; break; case MYSQL_TYPE_DATETIME: statistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break; case MYSQL_TYPE_YEAR: statistic = STAT_TEXT_TYPE_FETCHED_YEAR; break; case MYSQL_TYPE_NEWDATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_VARCHAR: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_BIT: statistic = STAT_TEXT_TYPE_FETCHED_BIT; break; case MYSQL_TYPE_NEWDECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_ENUM: statistic = STAT_TEXT_TYPE_FETCHED_ENUM; break; case MYSQL_TYPE_SET: statistic = STAT_TEXT_TYPE_FETCHED_SET; break; case MYSQL_TYPE_JSON: statistic = STAT_TEXT_TYPE_FETCHED_JSON; break; case MYSQL_TYPE_TINY_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_LONG_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_VAR_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_GEOMETRY: statistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break; default: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break; } MYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len); } #ifdef MYSQLND_STRING_TO_INT_CONVERSION if (as_int_or_float && perm_bind.php_type == IS_LONG) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; if (perm_bind.pack_len < SIZEOF_LONG) { /* direct conversion */ int64_t v = #ifndef PHP_WIN32 atoll((char *) p); #else _atoi64((char *) p); #endif ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } else { uint64_t v = #ifndef PHP_WIN32 (uint64_t) atoll((char *) p); #else (uint64_t) _atoi64((char *) p); #endif zend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE; /* We have to make it ASCIIZ temporarily */ #if SIZEOF_LONG==8 if (uns == TRUE && v > 9223372036854775807L) #elif SIZEOF_LONG==4 if ((uns == TRUE && v > L64(2147483647)) || (uns == FALSE && (( L64(2147483647) < (int64_t) v) || (L64(-2147483648) > (int64_t) v)))) #else #error Need fix for this architecture #endif /* SIZEOF */ { ZVAL_STRINGL(*current_field, (char *)p, len, 0); } else { ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } } *(p + len) = save; } else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; ZVAL_DOUBLE(*current_field, atof((char *) p)); *(p + len) = save; } else #endif /* MYSQLND_STRING_TO_INT_CONVERSION */ if (fields_metadata[i].type == MYSQL_TYPE_BIT) { /* BIT fields are specially handled. As they come as bit mask, we have to convert it to human-readable representation. As the bits take less space in the protocol than the numbers they represent, we don't have enough space in the packet buffer to overwrite inside. Thus, a bit more space is pre-allocated at the end of the buffer, see php_mysqlnd_rowp_read(). And we add the strings at the end. Definitely not nice, _hackish_ :(, but works. */ zend_uchar *start = bit_area; ps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC); /* We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because later in this function there will be an advancement. */ p -= len; if (Z_TYPE_PP(current_field) == IS_LONG) { bit_area += 1 + sprintf((char *)start, "%ld", Z_LVAL_PP(current_field)); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } else if (Z_TYPE_PP(current_field) == IS_STRING){ memcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field)); bit_area += Z_STRLEN_PP(current_field); *bit_area++ = '\0'; zval_dtor(*current_field); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } } else { ZVAL_STRINGL(*current_field, (char *)p, len, copy_data); } p += len; last_field_was_string = TRUE; } } if (copy_data == FALSE && last_field_was_string) { /* Normal queries: The buffer has one more byte at the end, because we need it */ row_buffer->ptr[data_size] = '\0'; } DBG_RETURN(PASS); } Commit Message: Fix bug #72293 - Heap overflow in mysqlnd related to BIT fields CWE ID: CWE-119
php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields, unsigned int field_count, const MYSQLND_FIELD * fields_metadata, zend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC) { unsigned int i; zend_bool last_field_was_string = FALSE; zval **current_field, **end_field, **start_field; zend_uchar * p = row_buffer->ptr; size_t data_size = row_buffer->app; zend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */ const zend_uchar * const packet_end = (zend_uchar*) row_buffer->ptr + data_size; DBG_ENTER("php_mysqlnd_rowp_read_text_protocol_aux"); if (!fields) { DBG_RETURN(FAIL); } end_field = (start_field = fields) + field_count; for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { DBG_INF("Directly creating zval"); MAKE_STD_ZVAL(*current_field); if (!*current_field) { DBG_RETURN(FAIL); } } for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { /* Don't reverse the order. It is significant!*/ zend_uchar *this_field_len_pos = p; /* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */ const unsigned long len = php_mysqlnd_net_field_length(&p); if (len != MYSQLND_NULL_LENGTH && ((p + len) > packet_end)) { php_error_docref(NULL, E_WARNING, "Malformed server packet. Field length pointing "MYSQLND_SZ_T_SPEC " bytes after end of packet", (p + len) - packet_end - 1); DBG_RETURN(FAIL); } if (copy_data == FALSE && current_field > start_field && last_field_was_string) { /* Normal queries: We have to put \0 now to the end of the previous field, if it was a string. IS_NULL doesn't matter. Because we have already read our length, then we can overwrite it in the row buffer. This statement terminates the previous field, not the current one. NULL_LENGTH is encoded in one byte, so we can stick a \0 there. Any string's length is encoded in at least one byte, so we can stick a \0 there. */ *this_field_len_pos = '\0'; } /* NULL or NOT NULL, this is the question! */ if (len == MYSQLND_NULL_LENGTH) { ZVAL_NULL(*current_field); last_field_was_string = FALSE; } else { #if defined(MYSQLND_STRING_TO_INT_CONVERSION) struct st_mysqlnd_perm_bind perm_bind = mysqlnd_ps_fetch_functions[fields_metadata[i].type]; #endif if (MYSQLND_G(collect_statistics)) { enum_mysqlnd_collected_stats statistic; switch (fields_metadata[i].type) { case MYSQL_TYPE_DECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_TINY: statistic = STAT_TEXT_TYPE_FETCHED_INT8; break; case MYSQL_TYPE_SHORT: statistic = STAT_TEXT_TYPE_FETCHED_INT16; break; case MYSQL_TYPE_LONG: statistic = STAT_TEXT_TYPE_FETCHED_INT32; break; case MYSQL_TYPE_FLOAT: statistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break; case MYSQL_TYPE_DOUBLE: statistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break; case MYSQL_TYPE_NULL: statistic = STAT_TEXT_TYPE_FETCHED_NULL; break; case MYSQL_TYPE_TIMESTAMP: statistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break; case MYSQL_TYPE_LONGLONG: statistic = STAT_TEXT_TYPE_FETCHED_INT64; break; case MYSQL_TYPE_INT24: statistic = STAT_TEXT_TYPE_FETCHED_INT24; break; case MYSQL_TYPE_DATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_TIME: statistic = STAT_TEXT_TYPE_FETCHED_TIME; break; case MYSQL_TYPE_DATETIME: statistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break; case MYSQL_TYPE_YEAR: statistic = STAT_TEXT_TYPE_FETCHED_YEAR; break; case MYSQL_TYPE_NEWDATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break; case MYSQL_TYPE_VARCHAR: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_BIT: statistic = STAT_TEXT_TYPE_FETCHED_BIT; break; case MYSQL_TYPE_NEWDECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break; case MYSQL_TYPE_ENUM: statistic = STAT_TEXT_TYPE_FETCHED_ENUM; break; case MYSQL_TYPE_SET: statistic = STAT_TEXT_TYPE_FETCHED_SET; break; case MYSQL_TYPE_JSON: statistic = STAT_TEXT_TYPE_FETCHED_JSON; break; case MYSQL_TYPE_TINY_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_LONG_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break; case MYSQL_TYPE_VAR_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break; case MYSQL_TYPE_GEOMETRY: statistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break; default: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break; } MYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len); } #ifdef MYSQLND_STRING_TO_INT_CONVERSION if (as_int_or_float && perm_bind.php_type == IS_LONG) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; if (perm_bind.pack_len < SIZEOF_LONG) { /* direct conversion */ int64_t v = #ifndef PHP_WIN32 atoll((char *) p); #else _atoi64((char *) p); #endif ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } else { uint64_t v = #ifndef PHP_WIN32 (uint64_t) atoll((char *) p); #else (uint64_t) _atoi64((char *) p); #endif zend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE; /* We have to make it ASCIIZ temporarily */ #if SIZEOF_LONG==8 if (uns == TRUE && v > 9223372036854775807L) #elif SIZEOF_LONG==4 if ((uns == TRUE && v > L64(2147483647)) || (uns == FALSE && (( L64(2147483647) < (int64_t) v) || (L64(-2147483648) > (int64_t) v)))) #else #error Need fix for this architecture #endif /* SIZEOF */ { ZVAL_STRINGL(*current_field, (char *)p, len, 0); } else { ZVAL_LONG(*current_field, (long) v); /* the cast is safe */ } } *(p + len) = save; } else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) { zend_uchar save = *(p + len); /* We have to make it ASCIIZ temporarily */ *(p + len) = '\0'; ZVAL_DOUBLE(*current_field, atof((char *) p)); *(p + len) = save; } else #endif /* MYSQLND_STRING_TO_INT_CONVERSION */ if (fields_metadata[i].type == MYSQL_TYPE_BIT) { /* BIT fields are specially handled. As they come as bit mask, we have to convert it to human-readable representation. As the bits take less space in the protocol than the numbers they represent, we don't have enough space in the packet buffer to overwrite inside. Thus, a bit more space is pre-allocated at the end of the buffer, see php_mysqlnd_rowp_read(). And we add the strings at the end. Definitely not nice, _hackish_ :(, but works. */ zend_uchar *start = bit_area; ps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC); /* We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because later in this function there will be an advancement. */ p -= len; if (Z_TYPE_PP(current_field) == IS_LONG) { bit_area += 1 + sprintf((char *)start, "%ld", Z_LVAL_PP(current_field)); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } else if (Z_TYPE_PP(current_field) == IS_STRING){ memcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field)); bit_area += Z_STRLEN_PP(current_field); *bit_area++ = '\0'; zval_dtor(*current_field); ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data); } } else { ZVAL_STRINGL(*current_field, (char *)p, len, copy_data); } p += len; last_field_was_string = TRUE; } } if (copy_data == FALSE && last_field_was_string) { /* Normal queries: The buffer has one more byte at the end, because we need it */ row_buffer->ptr[data_size] = '\0'; } DBG_RETURN(PASS); }
166,937
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { int ret = 0; int avail, tlen; xmlChar cur, next; const xmlChar *lastlt, *lastgt; if (ctxt->input == NULL) return(0); #ifdef DEBUG_PUSH switch (ctxt->instate) { case XML_PARSER_EOF: xmlGenericError(xmlGenericErrorContext, "PP: try EOF\n"); break; case XML_PARSER_START: xmlGenericError(xmlGenericErrorContext, "PP: try START\n"); break; case XML_PARSER_MISC: xmlGenericError(xmlGenericErrorContext, "PP: try MISC\n");break; case XML_PARSER_COMMENT: xmlGenericError(xmlGenericErrorContext, "PP: try COMMENT\n");break; case XML_PARSER_PROLOG: xmlGenericError(xmlGenericErrorContext, "PP: try PROLOG\n");break; case XML_PARSER_START_TAG: xmlGenericError(xmlGenericErrorContext, "PP: try START_TAG\n");break; case XML_PARSER_CONTENT: xmlGenericError(xmlGenericErrorContext, "PP: try CONTENT\n");break; case XML_PARSER_CDATA_SECTION: xmlGenericError(xmlGenericErrorContext, "PP: try CDATA_SECTION\n");break; case XML_PARSER_END_TAG: xmlGenericError(xmlGenericErrorContext, "PP: try END_TAG\n");break; case XML_PARSER_ENTITY_DECL: xmlGenericError(xmlGenericErrorContext, "PP: try ENTITY_DECL\n");break; case XML_PARSER_ENTITY_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: try ENTITY_VALUE\n");break; case XML_PARSER_ATTRIBUTE_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: try ATTRIBUTE_VALUE\n");break; case XML_PARSER_DTD: xmlGenericError(xmlGenericErrorContext, "PP: try DTD\n");break; case XML_PARSER_EPILOG: xmlGenericError(xmlGenericErrorContext, "PP: try EPILOG\n");break; case XML_PARSER_PI: xmlGenericError(xmlGenericErrorContext, "PP: try PI\n");break; case XML_PARSER_IGNORE: xmlGenericError(xmlGenericErrorContext, "PP: try IGNORE\n");break; } #endif if ((ctxt->input != NULL) && (ctxt->input->cur - ctxt->input->base > 4096)) { xmlSHRINK(ctxt); ctxt->checkIndex = 0; } xmlParseGetLasts(ctxt, &lastlt, &lastgt); while (1) { if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(0); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if (ctxt->input == NULL) break; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else { /* * If we are operating on converted input, try to flush * remainng chars to avoid them stalling in the non-converted * buffer. */ if ((ctxt->input->buf->raw != NULL) && (ctxt->input->buf->raw->use > 0)) { int base = ctxt->input->base - ctxt->input->buf->buffer->content; int current = ctxt->input->cur - ctxt->input->base; xmlParserInputBufferPush(ctxt->input->buf, 0, ""); ctxt->input->base = ctxt->input->buf->buffer->content + base; ctxt->input->cur = ctxt->input->base + current; ctxt->input->end = &ctxt->input->buf->buffer->content[ ctxt->input->buf->buffer->use]; } avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); } if (avail < 1) goto done; switch (ctxt->instate) { case XML_PARSER_EOF: /* * Document parsing is done ! */ goto done; case XML_PARSER_START: if (ctxt->charset == XML_CHAR_ENCODING_NONE) { xmlChar start[4]; xmlCharEncoding enc; /* * Very first chars read from the document flow. */ if (avail < 4) goto done; /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines, * else xmlSwitchEncoding will set to (default) * UTF8. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); xmlSwitchEncoding(ctxt, enc); break; } if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if (cur == 0) { if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); ctxt->instate = XML_PARSER_EOF; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering EOF\n"); #endif if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } if ((cur == '<') && (next == '?')) { /* PI or XML decl */ if (avail < 5) return(ret); if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) return(ret); if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if ((ctxt->input->cur[2] == 'x') && (ctxt->input->cur[3] == 'm') && (ctxt->input->cur[4] == 'l') && (IS_BLANK_CH(ctxt->input->cur[5]))) { ret += 5; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing XML Decl\n"); #endif xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right * here */ ctxt->instate = XML_PARSER_EOF; return(0); } ctxt->standalone = ctxt->input->standalone; if ((ctxt->encoding == NULL) && (ctxt->input->encoding != NULL)) ctxt->encoding = xmlStrdup(ctxt->input->encoding); if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } } else { if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); if (ctxt->version == NULL) { xmlErrMemory(ctxt, NULL); break; } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } break; case XML_PARSER_START_TAG: { const xmlChar *name; const xmlChar *prefix = NULL; const xmlChar *URI = NULL; int nsNr = ctxt->nsNr; if ((avail < 2) && (ctxt->inputNr == 1)) goto done; cur = ctxt->input->cur[0]; if (cur != '<') { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); ctxt->instate = XML_PARSER_EOF; if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } if (!terminate) { if (ctxt->progressive) { /* > can be found unescaped in attribute values */ if ((lastgt == NULL) || (ctxt->input->cur >= lastgt)) goto done; } else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) { goto done; } } if (ctxt->spaceNr == 0) spacePush(ctxt, -1); else if (*ctxt->space == -2) spacePush(ctxt, -1); else spacePush(ctxt, *ctxt->space); #ifdef LIBXML_SAX1_ENABLED if (ctxt->sax2) #endif /* LIBXML_SAX1_ENABLED */ name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen); #ifdef LIBXML_SAX1_ENABLED else name = xmlParseStartTag(ctxt); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) goto done; if (name == NULL) { spacePop(ctxt); ctxt->instate = XML_PARSER_EOF; if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } #ifdef LIBXML_VALID_ENABLED /* * [ VC: Root Element Type ] * The Name in the document type declaration must match * the element type of the root element. */ if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc && ctxt->node && (ctxt->node == ctxt->myDoc->children)) ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc); #endif /* LIBXML_VALID_ENABLED */ /* * Check for an Empty Element. */ if ((RAW == '/') && (NXT(1) == '>')) { SKIP(2); if (ctxt->sax2) { if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI); if (ctxt->nsNr - nsNr > 0) nsPop(ctxt, ctxt->nsNr - nsNr); #ifdef LIBXML_SAX1_ENABLED } else { if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElement(ctxt->userData, name); #endif /* LIBXML_SAX1_ENABLED */ } spacePop(ctxt); if (ctxt->nameNr == 0) { ctxt->instate = XML_PARSER_EPILOG; } else { ctxt->instate = XML_PARSER_CONTENT; } break; } if (RAW == '>') { NEXT; } else { xmlFatalErrMsgStr(ctxt, XML_ERR_GT_REQUIRED, "Couldn't find end of Start Tag %s\n", name); nodePop(ctxt); spacePop(ctxt); } if (ctxt->sax2) nameNsPush(ctxt, name, prefix, URI, ctxt->nsNr - nsNr); #ifdef LIBXML_SAX1_ENABLED else namePush(ctxt, name); #endif /* LIBXML_SAX1_ENABLED */ ctxt->instate = XML_PARSER_CONTENT; break; } case XML_PARSER_CONTENT: { const xmlChar *test; unsigned int cons; if ((avail < 2) && (ctxt->inputNr == 1)) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; test = CUR_PTR; cons = ctxt->input->consumed; if ((cur == '<') && (next == '/')) { ctxt->instate = XML_PARSER_END_TAG; break; } else if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; xmlParsePI(ctxt); } else if ((cur == '<') && (next != '!')) { ctxt->instate = XML_PARSER_START_TAG; break; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { int term; if (avail < 4) goto done; ctxt->input->cur += 4; term = xmlParseLookupSequence(ctxt, '-', '-', '>'); ctxt->input->cur -= 4; if ((!terminate) && (term < 0)) goto done; xmlParseComment(ctxt); ctxt->instate = XML_PARSER_CONTENT; } else if ((cur == '<') && (ctxt->input->cur[1] == '!') && (ctxt->input->cur[2] == '[') && (ctxt->input->cur[3] == 'C') && (ctxt->input->cur[4] == 'D') && (ctxt->input->cur[5] == 'A') && (ctxt->input->cur[6] == 'T') && (ctxt->input->cur[7] == 'A') && (ctxt->input->cur[8] == '[')) { SKIP(9); ctxt->instate = XML_PARSER_CDATA_SECTION; break; } else if ((cur == '<') && (next == '!') && (avail < 9)) { goto done; } else if (cur == '&') { if ((!terminate) && (xmlParseLookupSequence(ctxt, ';', 0, 0) < 0)) goto done; xmlParseReference(ctxt); } else { /* TODO Avoid the extra copy, handle directly !!! */ /* * Goal of the following test is: * - minimize calls to the SAX 'character' callback * when they are mergeable * - handle an problem for isBlank when we only parse * a sequence of blank chars and the next one is * not available to check against '<' presence. * - tries to homogenize the differences in SAX * callbacks between the push and pull versions * of the parser. */ if ((ctxt->inputNr == 1) && (avail < XML_PARSER_BIG_BUFFER_SIZE)) { if (!terminate) { if (ctxt->progressive) { if ((lastlt == NULL) || (ctxt->input->cur > lastlt)) goto done; } else if (xmlParseLookupSequence(ctxt, '<', 0, 0) < 0) { goto done; } } } ctxt->checkIndex = 0; xmlParseCharData(ctxt, 0); } /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((cons == ctxt->input->consumed) && (test == CUR_PTR)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "detected an error in element content\n"); ctxt->instate = XML_PARSER_EOF; break; } break; } case XML_PARSER_END_TAG: if (avail < 2) goto done; if (!terminate) { if (ctxt->progressive) { /* > can be found unescaped in attribute values */ if ((lastgt == NULL) || (ctxt->input->cur >= lastgt)) goto done; } else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) { goto done; } } if (ctxt->sax2) { xmlParseEndTag2(ctxt, (void *) ctxt->pushTab[ctxt->nameNr * 3 - 3], (void *) ctxt->pushTab[ctxt->nameNr * 3 - 2], 0, (int) (long) ctxt->pushTab[ctxt->nameNr * 3 - 1], 0); nameNsPop(ctxt); } #ifdef LIBXML_SAX1_ENABLED else xmlParseEndTag1(ctxt, 0); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) { /* Nothing */ } else if (ctxt->nameNr == 0) { ctxt->instate = XML_PARSER_EPILOG; } else { ctxt->instate = XML_PARSER_CONTENT; } break; case XML_PARSER_CDATA_SECTION: { /* * The Push mode need to have the SAX callback for * cdataBlock merge back contiguous callbacks. */ int base; base = xmlParseLookupSequence(ctxt, ']', ']', '>'); if (base < 0) { if (avail >= XML_PARSER_BIG_BUFFER_SIZE + 2) { int tmp; tmp = xmlCheckCdataPush(ctxt->input->cur, XML_PARSER_BIG_BUFFER_SIZE); if (tmp < 0) { tmp = -tmp; ctxt->input->cur += tmp; goto encoding_error; } if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, ctxt->input->cur, tmp); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, tmp); } SKIPL(tmp); ctxt->checkIndex = 0; } goto done; } else { int tmp; tmp = xmlCheckCdataPush(ctxt->input->cur, base); if ((tmp < 0) || (tmp != base)) { tmp = -tmp; ctxt->input->cur += tmp; goto encoding_error; } if ((ctxt->sax != NULL) && (base == 0) && (ctxt->sax->cdataBlock != NULL) && (!ctxt->disableSAX)) { /* * Special case to provide identical behaviour * between pull and push parsers on enpty CDATA * sections */ if ((ctxt->input->cur - ctxt->input->base >= 9) && (!strncmp((const char *)&ctxt->input->cur[-9], "<![CDATA[", 9))) ctxt->sax->cdataBlock(ctxt->userData, BAD_CAST "", 0); } else if ((ctxt->sax != NULL) && (base > 0) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, ctxt->input->cur, base); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, base); } SKIPL(base + 3); ctxt->checkIndex = 0; ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif } break; } case XML_PARSER_MISC: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); ctxt->checkIndex = 0; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); ctxt->instate = XML_PARSER_MISC; ctxt->checkIndex = 0; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == 'D') && (ctxt->input->cur[3] == 'O') && (ctxt->input->cur[4] == 'C') && (ctxt->input->cur[5] == 'T') && (ctxt->input->cur[6] == 'Y') && (ctxt->input->cur[7] == 'P') && (ctxt->input->cur[8] == 'E')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing internal subset\n"); #endif ctxt->inSubset = 1; xmlParseDocTypeDecl(ctxt); if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif } else { /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->externalSubset != NULL)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering PROLOG\n"); #endif } } else if ((cur == '<') && (next == '!') && (avail < 9)) { goto done; } else { ctxt->instate = XML_PARSER_START_TAG; ctxt->progressive = 1; xmlParseGetLasts(ctxt, &lastlt, &lastgt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif } break; case XML_PARSER_PROLOG: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); ctxt->instate = XML_PARSER_PROLOG; } else if ((cur == '<') && (next == '!') && (avail < 4)) { goto done; } else { ctxt->instate = XML_PARSER_START_TAG; if (ctxt->progressive == 0) ctxt->progressive = 1; xmlParseGetLasts(ctxt, &lastlt, &lastgt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif } break; case XML_PARSER_EPILOG: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); ctxt->instate = XML_PARSER_EPILOG; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); ctxt->instate = XML_PARSER_EPILOG; } else if ((cur == '<') && (next == '!') && (avail < 4)) { goto done; } else { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); ctxt->instate = XML_PARSER_EOF; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering EOF\n"); #endif if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } break; case XML_PARSER_DTD: { /* * Sorry but progressive parsing of the internal subset * is not expected to be supported. We first check that * the full content of the internal subset is available and * the parsing is launched only at that point. * Internal subset ends up with "']' S? '>'" in an unescaped * section and not in a ']]>' sequence which are conditional * sections (whoever argued to keep that crap in XML deserve * a place in hell !). */ int base, i; xmlChar *buf; xmlChar quote = 0; base = ctxt->input->cur - ctxt->input->base; if (base < 0) return(0); if (ctxt->checkIndex > base) base = ctxt->checkIndex; buf = ctxt->input->buf->buffer->content; for (;(unsigned int) base < ctxt->input->buf->buffer->use; base++) { if (quote != 0) { if (buf[base] == quote) quote = 0; continue; } if ((quote == 0) && (buf[base] == '<')) { int found = 0; /* special handling of comments */ if (((unsigned int) base + 4 < ctxt->input->buf->buffer->use) && (buf[base + 1] == '!') && (buf[base + 2] == '-') && (buf[base + 3] == '-')) { for (;(unsigned int) base + 3 < ctxt->input->buf->buffer->use; base++) { if ((buf[base] == '-') && (buf[base + 1] == '-') && (buf[base + 2] == '>')) { found = 1; base += 2; break; } } if (!found) { #if 0 fprintf(stderr, "unfinished comment\n"); #endif break; /* for */ } continue; } } if (buf[base] == '"') { quote = '"'; continue; } if (buf[base] == '\'') { quote = '\''; continue; } if (buf[base] == ']') { #if 0 fprintf(stderr, "%c%c%c%c: ", buf[base], buf[base + 1], buf[base + 2], buf[base + 3]); #endif if ((unsigned int) base +1 >= ctxt->input->buf->buffer->use) break; if (buf[base + 1] == ']') { /* conditional crap, skip both ']' ! */ base++; continue; } for (i = 1; (unsigned int) base + i < ctxt->input->buf->buffer->use; i++) { if (buf[base + i] == '>') { #if 0 fprintf(stderr, "found\n"); #endif goto found_end_int_subset; } if (!IS_BLANK_CH(buf[base + i])) { #if 0 fprintf(stderr, "not found\n"); #endif goto not_end_of_int_subset; } } #if 0 fprintf(stderr, "end of stream\n"); #endif break; } not_end_of_int_subset: continue; /* for */ } /* * We didn't found the end of the Internal subset */ #ifdef DEBUG_PUSH if (next == 0) xmlGenericError(xmlGenericErrorContext, "PP: lookup of int subset end filed\n"); #endif goto done; found_end_int_subset: xmlParseInternalSubset(ctxt); ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->externalSubset != NULL)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; ctxt->checkIndex = 0; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering PROLOG\n"); #endif break; } case XML_PARSER_COMMENT: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == COMMENT\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif break; case XML_PARSER_IGNORE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == IGNORE"); ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_PI: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == PI\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif break; case XML_PARSER_ENTITY_DECL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ENTITY_DECL\n"); ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_ENTITY_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ENTITY_VALUE\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_ATTRIBUTE_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ATTRIBUTE_VALUE\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; case XML_PARSER_SYSTEM_LITERAL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == SYSTEM_LITERAL\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; case XML_PARSER_PUBLIC_LITERAL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == PUBLIC_LITERAL\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; } } done: #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: done %d\n", ret); #endif return(ret); encoding_error: { char buffer[150]; snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n", ctxt->input->cur[0], ctxt->input->cur[1], ctxt->input->cur[2], ctxt->input->cur[3]); __xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR, "Input is not proper UTF-8, indicate encoding !\n%s", BAD_CAST buffer, NULL); } return(0); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { int ret = 0; int avail, tlen; xmlChar cur, next; const xmlChar *lastlt, *lastgt; if (ctxt->input == NULL) return(0); #ifdef DEBUG_PUSH switch (ctxt->instate) { case XML_PARSER_EOF: xmlGenericError(xmlGenericErrorContext, "PP: try EOF\n"); break; case XML_PARSER_START: xmlGenericError(xmlGenericErrorContext, "PP: try START\n"); break; case XML_PARSER_MISC: xmlGenericError(xmlGenericErrorContext, "PP: try MISC\n");break; case XML_PARSER_COMMENT: xmlGenericError(xmlGenericErrorContext, "PP: try COMMENT\n");break; case XML_PARSER_PROLOG: xmlGenericError(xmlGenericErrorContext, "PP: try PROLOG\n");break; case XML_PARSER_START_TAG: xmlGenericError(xmlGenericErrorContext, "PP: try START_TAG\n");break; case XML_PARSER_CONTENT: xmlGenericError(xmlGenericErrorContext, "PP: try CONTENT\n");break; case XML_PARSER_CDATA_SECTION: xmlGenericError(xmlGenericErrorContext, "PP: try CDATA_SECTION\n");break; case XML_PARSER_END_TAG: xmlGenericError(xmlGenericErrorContext, "PP: try END_TAG\n");break; case XML_PARSER_ENTITY_DECL: xmlGenericError(xmlGenericErrorContext, "PP: try ENTITY_DECL\n");break; case XML_PARSER_ENTITY_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: try ENTITY_VALUE\n");break; case XML_PARSER_ATTRIBUTE_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: try ATTRIBUTE_VALUE\n");break; case XML_PARSER_DTD: xmlGenericError(xmlGenericErrorContext, "PP: try DTD\n");break; case XML_PARSER_EPILOG: xmlGenericError(xmlGenericErrorContext, "PP: try EPILOG\n");break; case XML_PARSER_PI: xmlGenericError(xmlGenericErrorContext, "PP: try PI\n");break; case XML_PARSER_IGNORE: xmlGenericError(xmlGenericErrorContext, "PP: try IGNORE\n");break; } #endif if ((ctxt->input != NULL) && (ctxt->input->cur - ctxt->input->base > 4096)) { xmlSHRINK(ctxt); ctxt->checkIndex = 0; } xmlParseGetLasts(ctxt, &lastlt, &lastgt); while (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(0); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if (ctxt->input == NULL) break; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else { /* * If we are operating on converted input, try to flush * remainng chars to avoid them stalling in the non-converted * buffer. */ if ((ctxt->input->buf->raw != NULL) && (ctxt->input->buf->raw->use > 0)) { int base = ctxt->input->base - ctxt->input->buf->buffer->content; int current = ctxt->input->cur - ctxt->input->base; xmlParserInputBufferPush(ctxt->input->buf, 0, ""); ctxt->input->base = ctxt->input->buf->buffer->content + base; ctxt->input->cur = ctxt->input->base + current; ctxt->input->end = &ctxt->input->buf->buffer->content[ ctxt->input->buf->buffer->use]; } avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); } if (avail < 1) goto done; switch (ctxt->instate) { case XML_PARSER_EOF: /* * Document parsing is done ! */ goto done; case XML_PARSER_START: if (ctxt->charset == XML_CHAR_ENCODING_NONE) { xmlChar start[4]; xmlCharEncoding enc; /* * Very first chars read from the document flow. */ if (avail < 4) goto done; /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines, * else xmlSwitchEncoding will set to (default) * UTF8. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); xmlSwitchEncoding(ctxt, enc); break; } if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if (cur == 0) { if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); ctxt->instate = XML_PARSER_EOF; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering EOF\n"); #endif if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } if ((cur == '<') && (next == '?')) { /* PI or XML decl */ if (avail < 5) return(ret); if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) return(ret); if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if ((ctxt->input->cur[2] == 'x') && (ctxt->input->cur[3] == 'm') && (ctxt->input->cur[4] == 'l') && (IS_BLANK_CH(ctxt->input->cur[5]))) { ret += 5; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing XML Decl\n"); #endif xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right * here */ ctxt->instate = XML_PARSER_EOF; return(0); } ctxt->standalone = ctxt->input->standalone; if ((ctxt->encoding == NULL) && (ctxt->input->encoding != NULL)) ctxt->encoding = xmlStrdup(ctxt->input->encoding); if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } } else { if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); if (ctxt->version == NULL) { xmlErrMemory(ctxt, NULL); break; } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } break; case XML_PARSER_START_TAG: { const xmlChar *name; const xmlChar *prefix = NULL; const xmlChar *URI = NULL; int nsNr = ctxt->nsNr; if ((avail < 2) && (ctxt->inputNr == 1)) goto done; cur = ctxt->input->cur[0]; if (cur != '<') { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); ctxt->instate = XML_PARSER_EOF; if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } if (!terminate) { if (ctxt->progressive) { /* > can be found unescaped in attribute values */ if ((lastgt == NULL) || (ctxt->input->cur >= lastgt)) goto done; } else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) { goto done; } } if (ctxt->spaceNr == 0) spacePush(ctxt, -1); else if (*ctxt->space == -2) spacePush(ctxt, -1); else spacePush(ctxt, *ctxt->space); #ifdef LIBXML_SAX1_ENABLED if (ctxt->sax2) #endif /* LIBXML_SAX1_ENABLED */ name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen); #ifdef LIBXML_SAX1_ENABLED else name = xmlParseStartTag(ctxt); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) goto done; if (name == NULL) { spacePop(ctxt); ctxt->instate = XML_PARSER_EOF; if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } #ifdef LIBXML_VALID_ENABLED /* * [ VC: Root Element Type ] * The Name in the document type declaration must match * the element type of the root element. */ if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc && ctxt->node && (ctxt->node == ctxt->myDoc->children)) ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc); #endif /* LIBXML_VALID_ENABLED */ /* * Check for an Empty Element. */ if ((RAW == '/') && (NXT(1) == '>')) { SKIP(2); if (ctxt->sax2) { if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI); if (ctxt->nsNr - nsNr > 0) nsPop(ctxt, ctxt->nsNr - nsNr); #ifdef LIBXML_SAX1_ENABLED } else { if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElement(ctxt->userData, name); #endif /* LIBXML_SAX1_ENABLED */ } if (ctxt->instate == XML_PARSER_EOF) goto done; spacePop(ctxt); if (ctxt->nameNr == 0) { ctxt->instate = XML_PARSER_EPILOG; } else { ctxt->instate = XML_PARSER_CONTENT; } break; } if (RAW == '>') { NEXT; } else { xmlFatalErrMsgStr(ctxt, XML_ERR_GT_REQUIRED, "Couldn't find end of Start Tag %s\n", name); nodePop(ctxt); spacePop(ctxt); } if (ctxt->sax2) nameNsPush(ctxt, name, prefix, URI, ctxt->nsNr - nsNr); #ifdef LIBXML_SAX1_ENABLED else namePush(ctxt, name); #endif /* LIBXML_SAX1_ENABLED */ ctxt->instate = XML_PARSER_CONTENT; break; } case XML_PARSER_CONTENT: { const xmlChar *test; unsigned int cons; if ((avail < 2) && (ctxt->inputNr == 1)) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; test = CUR_PTR; cons = ctxt->input->consumed; if ((cur == '<') && (next == '/')) { ctxt->instate = XML_PARSER_END_TAG; break; } else if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; xmlParsePI(ctxt); } else if ((cur == '<') && (next != '!')) { ctxt->instate = XML_PARSER_START_TAG; break; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { int term; if (avail < 4) goto done; ctxt->input->cur += 4; term = xmlParseLookupSequence(ctxt, '-', '-', '>'); ctxt->input->cur -= 4; if ((!terminate) && (term < 0)) goto done; xmlParseComment(ctxt); ctxt->instate = XML_PARSER_CONTENT; } else if ((cur == '<') && (ctxt->input->cur[1] == '!') && (ctxt->input->cur[2] == '[') && (ctxt->input->cur[3] == 'C') && (ctxt->input->cur[4] == 'D') && (ctxt->input->cur[5] == 'A') && (ctxt->input->cur[6] == 'T') && (ctxt->input->cur[7] == 'A') && (ctxt->input->cur[8] == '[')) { SKIP(9); ctxt->instate = XML_PARSER_CDATA_SECTION; break; } else if ((cur == '<') && (next == '!') && (avail < 9)) { goto done; } else if (cur == '&') { if ((!terminate) && (xmlParseLookupSequence(ctxt, ';', 0, 0) < 0)) goto done; xmlParseReference(ctxt); } else { /* TODO Avoid the extra copy, handle directly !!! */ /* * Goal of the following test is: * - minimize calls to the SAX 'character' callback * when they are mergeable * - handle an problem for isBlank when we only parse * a sequence of blank chars and the next one is * not available to check against '<' presence. * - tries to homogenize the differences in SAX * callbacks between the push and pull versions * of the parser. */ if ((ctxt->inputNr == 1) && (avail < XML_PARSER_BIG_BUFFER_SIZE)) { if (!terminate) { if (ctxt->progressive) { if ((lastlt == NULL) || (ctxt->input->cur > lastlt)) goto done; } else if (xmlParseLookupSequence(ctxt, '<', 0, 0) < 0) { goto done; } } } ctxt->checkIndex = 0; xmlParseCharData(ctxt, 0); } /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((cons == ctxt->input->consumed) && (test == CUR_PTR)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "detected an error in element content\n"); ctxt->instate = XML_PARSER_EOF; break; } break; } case XML_PARSER_END_TAG: if (avail < 2) goto done; if (!terminate) { if (ctxt->progressive) { /* > can be found unescaped in attribute values */ if ((lastgt == NULL) || (ctxt->input->cur >= lastgt)) goto done; } else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) { goto done; } } if (ctxt->sax2) { xmlParseEndTag2(ctxt, (void *) ctxt->pushTab[ctxt->nameNr * 3 - 3], (void *) ctxt->pushTab[ctxt->nameNr * 3 - 2], 0, (int) (long) ctxt->pushTab[ctxt->nameNr * 3 - 1], 0); nameNsPop(ctxt); } #ifdef LIBXML_SAX1_ENABLED else xmlParseEndTag1(ctxt, 0); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->instate == XML_PARSER_EOF) { /* Nothing */ } else if (ctxt->nameNr == 0) { ctxt->instate = XML_PARSER_EPILOG; } else { ctxt->instate = XML_PARSER_CONTENT; } break; case XML_PARSER_CDATA_SECTION: { /* * The Push mode need to have the SAX callback for * cdataBlock merge back contiguous callbacks. */ int base; base = xmlParseLookupSequence(ctxt, ']', ']', '>'); if (base < 0) { if (avail >= XML_PARSER_BIG_BUFFER_SIZE + 2) { int tmp; tmp = xmlCheckCdataPush(ctxt->input->cur, XML_PARSER_BIG_BUFFER_SIZE); if (tmp < 0) { tmp = -tmp; ctxt->input->cur += tmp; goto encoding_error; } if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, ctxt->input->cur, tmp); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, tmp); } if (ctxt->instate == XML_PARSER_EOF) goto done; SKIPL(tmp); ctxt->checkIndex = 0; } goto done; } else { int tmp; tmp = xmlCheckCdataPush(ctxt->input->cur, base); if ((tmp < 0) || (tmp != base)) { tmp = -tmp; ctxt->input->cur += tmp; goto encoding_error; } if ((ctxt->sax != NULL) && (base == 0) && (ctxt->sax->cdataBlock != NULL) && (!ctxt->disableSAX)) { /* * Special case to provide identical behaviour * between pull and push parsers on enpty CDATA * sections */ if ((ctxt->input->cur - ctxt->input->base >= 9) && (!strncmp((const char *)&ctxt->input->cur[-9], "<![CDATA[", 9))) ctxt->sax->cdataBlock(ctxt->userData, BAD_CAST "", 0); } else if ((ctxt->sax != NULL) && (base > 0) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, ctxt->input->cur, base); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, base); } if (ctxt->instate == XML_PARSER_EOF) goto done; SKIPL(base + 3); ctxt->checkIndex = 0; ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif } break; } case XML_PARSER_MISC: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->checkIndex = 0; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_MISC; ctxt->checkIndex = 0; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == 'D') && (ctxt->input->cur[3] == 'O') && (ctxt->input->cur[4] == 'C') && (ctxt->input->cur[5] == 'T') && (ctxt->input->cur[6] == 'Y') && (ctxt->input->cur[7] == 'P') && (ctxt->input->cur[8] == 'E')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing internal subset\n"); #endif ctxt->inSubset = 1; xmlParseDocTypeDecl(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif } else { /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->externalSubset != NULL)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering PROLOG\n"); #endif } } else if ((cur == '<') && (next == '!') && (avail < 9)) { goto done; } else { ctxt->instate = XML_PARSER_START_TAG; ctxt->progressive = 1; xmlParseGetLasts(ctxt, &lastlt, &lastgt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif } break; case XML_PARSER_PROLOG: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_PROLOG; } else if ((cur == '<') && (next == '!') && (avail < 4)) { goto done; } else { ctxt->instate = XML_PARSER_START_TAG; if (ctxt->progressive == 0) ctxt->progressive = 1; xmlParseGetLasts(ctxt, &lastlt, &lastgt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif } break; case XML_PARSER_EPILOG: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_EPILOG; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_EPILOG; } else if ((cur == '<') && (next == '!') && (avail < 4)) { goto done; } else { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); ctxt->instate = XML_PARSER_EOF; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering EOF\n"); #endif if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } break; case XML_PARSER_DTD: { /* * Sorry but progressive parsing of the internal subset * is not expected to be supported. We first check that * the full content of the internal subset is available and * the parsing is launched only at that point. * Internal subset ends up with "']' S? '>'" in an unescaped * section and not in a ']]>' sequence which are conditional * sections (whoever argued to keep that crap in XML deserve * a place in hell !). */ int base, i; xmlChar *buf; xmlChar quote = 0; base = ctxt->input->cur - ctxt->input->base; if (base < 0) return(0); if (ctxt->checkIndex > base) base = ctxt->checkIndex; buf = ctxt->input->buf->buffer->content; for (;(unsigned int) base < ctxt->input->buf->buffer->use; base++) { if (quote != 0) { if (buf[base] == quote) quote = 0; continue; } if ((quote == 0) && (buf[base] == '<')) { int found = 0; /* special handling of comments */ if (((unsigned int) base + 4 < ctxt->input->buf->buffer->use) && (buf[base + 1] == '!') && (buf[base + 2] == '-') && (buf[base + 3] == '-')) { for (;(unsigned int) base + 3 < ctxt->input->buf->buffer->use; base++) { if ((buf[base] == '-') && (buf[base + 1] == '-') && (buf[base + 2] == '>')) { found = 1; base += 2; break; } } if (!found) { #if 0 fprintf(stderr, "unfinished comment\n"); #endif break; /* for */ } continue; } } if (buf[base] == '"') { quote = '"'; continue; } if (buf[base] == '\'') { quote = '\''; continue; } if (buf[base] == ']') { #if 0 fprintf(stderr, "%c%c%c%c: ", buf[base], buf[base + 1], buf[base + 2], buf[base + 3]); #endif if ((unsigned int) base +1 >= ctxt->input->buf->buffer->use) break; if (buf[base + 1] == ']') { /* conditional crap, skip both ']' ! */ base++; continue; } for (i = 1; (unsigned int) base + i < ctxt->input->buf->buffer->use; i++) { if (buf[base + i] == '>') { #if 0 fprintf(stderr, "found\n"); #endif goto found_end_int_subset; } if (!IS_BLANK_CH(buf[base + i])) { #if 0 fprintf(stderr, "not found\n"); #endif goto not_end_of_int_subset; } } #if 0 fprintf(stderr, "end of stream\n"); #endif break; } not_end_of_int_subset: continue; /* for */ } /* * We didn't found the end of the Internal subset */ #ifdef DEBUG_PUSH if (next == 0) xmlGenericError(xmlGenericErrorContext, "PP: lookup of int subset end filed\n"); #endif goto done; found_end_int_subset: xmlParseInternalSubset(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->externalSubset != NULL)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); if (ctxt->instate == XML_PARSER_EOF) goto done; ctxt->instate = XML_PARSER_PROLOG; ctxt->checkIndex = 0; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering PROLOG\n"); #endif break; } case XML_PARSER_COMMENT: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == COMMENT\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif break; case XML_PARSER_IGNORE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == IGNORE"); ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_PI: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == PI\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif break; case XML_PARSER_ENTITY_DECL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ENTITY_DECL\n"); ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_ENTITY_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ENTITY_VALUE\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_ATTRIBUTE_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ATTRIBUTE_VALUE\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; case XML_PARSER_SYSTEM_LITERAL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == SYSTEM_LITERAL\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; case XML_PARSER_PUBLIC_LITERAL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == PUBLIC_LITERAL\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; } } done: #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: done %d\n", ret); #endif return(ret); encoding_error: { char buffer[150]; snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n", ctxt->input->cur[0], ctxt->input->cur[1], ctxt->input->cur[2], ctxt->input->cur[3]); __xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR, "Input is not proper UTF-8, indicate encoding !\n%s", BAD_CAST buffer, NULL); } return(0); }
171,307
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int bpf_check(struct bpf_prog **prog, union bpf_attr *attr) { struct bpf_verifier_env *env; struct bpf_verifer_log *log; int ret = -EINVAL; /* no program is valid */ if (ARRAY_SIZE(bpf_verifier_ops) == 0) return -EINVAL; /* 'struct bpf_verifier_env' can be global, but since it's not small, * allocate/free it every time bpf_check() is called */ env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); if (!env) return -ENOMEM; log = &env->log; env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) * (*prog)->len); ret = -ENOMEM; if (!env->insn_aux_data) goto err_free_env; env->prog = *prog; env->ops = bpf_verifier_ops[env->prog->type]; /* grab the mutex to protect few globals used by verifier */ mutex_lock(&bpf_verifier_lock); if (attr->log_level || attr->log_buf || attr->log_size) { /* user requested verbose verifier output * and supplied buffer to store the verification trace */ log->level = attr->log_level; log->ubuf = (char __user *) (unsigned long) attr->log_buf; log->len_total = attr->log_size; ret = -EINVAL; /* log attributes have to be sane */ if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 || !log->level || !log->ubuf) goto err_unlock; } env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) env->strict_alignment = true; if (env->prog->aux->offload) { ret = bpf_prog_offload_verifier_prep(env); if (ret) goto err_unlock; } ret = replace_map_fd_with_map_ptr(env); if (ret < 0) goto skip_full_check; env->explored_states = kcalloc(env->prog->len, sizeof(struct bpf_verifier_state_list *), GFP_USER); ret = -ENOMEM; if (!env->explored_states) goto skip_full_check; ret = check_cfg(env); if (ret < 0) goto skip_full_check; env->allow_ptr_leaks = capable(CAP_SYS_ADMIN); ret = do_check(env); if (env->cur_state) { free_verifier_state(env->cur_state, true); env->cur_state = NULL; } skip_full_check: while (!pop_stack(env, NULL, NULL)); free_states(env); if (ret == 0) /* program is valid, convert *(u32*)(ctx + off) accesses */ ret = convert_ctx_accesses(env); if (ret == 0) ret = fixup_bpf_calls(env); if (log->level && bpf_verifier_log_full(log)) ret = -ENOSPC; if (log->level && !log->ubuf) { ret = -EFAULT; goto err_release_maps; } if (ret == 0 && env->used_map_cnt) { /* if program passed verifier, update used_maps in bpf_prog_info */ env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, sizeof(env->used_maps[0]), GFP_KERNEL); if (!env->prog->aux->used_maps) { ret = -ENOMEM; goto err_release_maps; } memcpy(env->prog->aux->used_maps, env->used_maps, sizeof(env->used_maps[0]) * env->used_map_cnt); env->prog->aux->used_map_cnt = env->used_map_cnt; /* program is valid. Convert pseudo bpf_ld_imm64 into generic * bpf_ld_imm64 instructions */ convert_pseudo_ld_imm64(env); } err_release_maps: if (!env->prog->aux->used_maps) /* if we didn't copy map pointers into bpf_prog_info, release * them now. Otherwise free_bpf_prog_info() will release them. */ release_maps(env); *prog = env->prog; err_unlock: mutex_unlock(&bpf_verifier_lock); vfree(env->insn_aux_data); err_free_env: kfree(env); return ret; } Commit Message: bpf: fix branch pruning logic when the verifier detects that register contains a runtime constant and it's compared with another constant it will prune exploration of the branch that is guaranteed not to be taken at runtime. This is all correct, but malicious program may be constructed in such a way that it always has a constant comparison and the other branch is never taken under any conditions. In this case such path through the program will not be explored by the verifier. It won't be taken at run-time either, but since all instructions are JITed the malicious program may cause JITs to complain about using reserved fields, etc. To fix the issue we have to track the instructions explored by the verifier and sanitize instructions that are dead at run time with NOPs. We cannot reject such dead code, since llvm generates it for valid C code, since it doesn't do as much data flow analysis as the verifier does. Fixes: 17a5267067f3 ("bpf: verifier (add verifier core)") Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-20
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr) { struct bpf_verifier_env *env; struct bpf_verifer_log *log; int ret = -EINVAL; /* no program is valid */ if (ARRAY_SIZE(bpf_verifier_ops) == 0) return -EINVAL; /* 'struct bpf_verifier_env' can be global, but since it's not small, * allocate/free it every time bpf_check() is called */ env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); if (!env) return -ENOMEM; log = &env->log; env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) * (*prog)->len); ret = -ENOMEM; if (!env->insn_aux_data) goto err_free_env; env->prog = *prog; env->ops = bpf_verifier_ops[env->prog->type]; /* grab the mutex to protect few globals used by verifier */ mutex_lock(&bpf_verifier_lock); if (attr->log_level || attr->log_buf || attr->log_size) { /* user requested verbose verifier output * and supplied buffer to store the verification trace */ log->level = attr->log_level; log->ubuf = (char __user *) (unsigned long) attr->log_buf; log->len_total = attr->log_size; ret = -EINVAL; /* log attributes have to be sane */ if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 || !log->level || !log->ubuf) goto err_unlock; } env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) env->strict_alignment = true; if (env->prog->aux->offload) { ret = bpf_prog_offload_verifier_prep(env); if (ret) goto err_unlock; } ret = replace_map_fd_with_map_ptr(env); if (ret < 0) goto skip_full_check; env->explored_states = kcalloc(env->prog->len, sizeof(struct bpf_verifier_state_list *), GFP_USER); ret = -ENOMEM; if (!env->explored_states) goto skip_full_check; ret = check_cfg(env); if (ret < 0) goto skip_full_check; env->allow_ptr_leaks = capable(CAP_SYS_ADMIN); ret = do_check(env); if (env->cur_state) { free_verifier_state(env->cur_state, true); env->cur_state = NULL; } skip_full_check: while (!pop_stack(env, NULL, NULL)); free_states(env); if (ret == 0) sanitize_dead_code(env); if (ret == 0) /* program is valid, convert *(u32*)(ctx + off) accesses */ ret = convert_ctx_accesses(env); if (ret == 0) ret = fixup_bpf_calls(env); if (log->level && bpf_verifier_log_full(log)) ret = -ENOSPC; if (log->level && !log->ubuf) { ret = -EFAULT; goto err_release_maps; } if (ret == 0 && env->used_map_cnt) { /* if program passed verifier, update used_maps in bpf_prog_info */ env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, sizeof(env->used_maps[0]), GFP_KERNEL); if (!env->prog->aux->used_maps) { ret = -ENOMEM; goto err_release_maps; } memcpy(env->prog->aux->used_maps, env->used_maps, sizeof(env->used_maps[0]) * env->used_map_cnt); env->prog->aux->used_map_cnt = env->used_map_cnt; /* program is valid. Convert pseudo bpf_ld_imm64 into generic * bpf_ld_imm64 instructions */ convert_pseudo_ld_imm64(env); } err_release_maps: if (!env->prog->aux->used_maps) /* if we didn't copy map pointers into bpf_prog_info, release * them now. Otherwise free_bpf_prog_info() will release them. */ release_maps(env); *prog = env->prog; err_unlock: mutex_unlock(&bpf_verifier_lock); vfree(env->insn_aux_data); err_free_env: kfree(env); return ret; }
167,638
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SQLRETURN SQLSetDescFieldW( SQLHDESC descriptor_handle, SQLSMALLINT rec_number, SQLSMALLINT field_identifier, SQLPOINTER value, SQLINTEGER buffer_length ) { /* * not quite sure how the descriptor can be * allocated to a statement, all the documentation talks * about state transitions on statement states, but the * descriptor may be allocated with more than one statement * at one time. Which one should I check ? */ DMHDESC descriptor = (DMHDESC) descriptor_handle; SQLRETURN ret; SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ]; int isStrField = 0; /* * check descriptor */ if ( !__validate_desc( descriptor )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: SQL_INVALID_HANDLE" ); #ifdef WITH_HANDLE_REDIRECT { DMHDESC parent_desc; parent_desc = find_parent_handle( descriptor, SQL_HANDLE_DESC ); if ( parent_desc ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Info: found parent handle" ); if ( CHECK_SQLSETDESCFIELDW( parent_desc -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Info: calling redirected driver function" ); return SQLSETDESCFIELDW( parent_desc -> connection, descriptor, rec_number, field_identifier, value, buffer_length ); } } } #endif return SQL_INVALID_HANDLE; } function_entry( descriptor ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tEntry:\ \n\t\t\tDescriptor = %p\ \n\t\t\tRec Number = %d\ \n\t\t\tField Ident = %s\ \n\t\t\tValue = %p\ \n\t\t\tBuffer Length = %d", descriptor, rec_number, __desc_attr_as_string( s1, field_identifier ), value, (int)buffer_length ); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } thread_protect( SQL_HANDLE_DESC, descriptor ); if ( descriptor -> connection -> state < STATE_C4 ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * check status of statements associated with this descriptor */ if( __check_stmt_from_desc( descriptor, STATE_S8 ) || __check_stmt_from_desc( descriptor, STATE_S9 ) || __check_stmt_from_desc( descriptor, STATE_S10 ) || __check_stmt_from_desc( descriptor, STATE_S11 ) || __check_stmt_from_desc( descriptor, STATE_S12 ) || __check_stmt_from_desc( descriptor, STATE_S13 ) || __check_stmt_from_desc( descriptor, STATE_S14 ) || __check_stmt_from_desc( descriptor, STATE_S15 )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( rec_number < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } switch ( field_identifier ) { /* Fixed-length fields: buffer_length is ignored */ case SQL_DESC_ALLOC_TYPE: case SQL_DESC_ARRAY_SIZE: case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_BIND_OFFSET_PTR: case SQL_DESC_BIND_TYPE: case SQL_DESC_COUNT: case SQL_DESC_ROWS_PROCESSED_PTR: case SQL_DESC_AUTO_UNIQUE_VALUE: case SQL_DESC_CASE_SENSITIVE: case SQL_DESC_CONCISE_TYPE: case SQL_DESC_DATA_PTR: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_DISPLAY_SIZE: case SQL_DESC_FIXED_PREC_SCALE: case SQL_DESC_INDICATOR_PTR: case SQL_DESC_LENGTH: case SQL_DESC_NULLABLE: case SQL_DESC_NUM_PREC_RADIX: case SQL_DESC_OCTET_LENGTH: case SQL_DESC_OCTET_LENGTH_PTR: case SQL_DESC_PARAMETER_TYPE: case SQL_DESC_PRECISION: case SQL_DESC_ROWVER: case SQL_DESC_SCALE: case SQL_DESC_SEARCHABLE: case SQL_DESC_TYPE: case SQL_DESC_UNNAMED: case SQL_DESC_UNSIGNED: case SQL_DESC_UPDATABLE: isStrField = 0; break; /* Pointer to data: buffer_length must be valid */ case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: isStrField = 1; break; default: isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER && buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT && buffer_length != SQL_IS_USMALLINT; } if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS) { __post_internal_error( &descriptor -> error, ERROR_HY090, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_COUNT && (SQLINTEGER)value < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_PARAMETER_TYPE && value != SQL_PARAM_INPUT && value != SQL_PARAM_OUTPUT && value != SQL_PARAM_INPUT_OUTPUT && value != SQL_PARAM_INPUT_OUTPUT_STREAM && value != SQL_PARAM_OUTPUT_STREAM ) { __post_internal_error( &descriptor -> error, ERROR_HY105, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( descriptor -> connection -> unicode_driver || CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { if ( !CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: IM001" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } ret = SQLSETDESCFIELDW( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tExit:[%s]", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } } else { SQLCHAR *ascii_str = NULL; if ( !CHECK_SQLSETDESCFIELD( descriptor -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: IM001" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * is it a char arg... */ switch ( field_identifier ) { case SQL_DESC_NAME: /* This is the only R/W SQLCHAR* type */ ascii_str = (SQLCHAR*) unicode_to_ansi_alloc( value, buffer_length, descriptor -> connection, NULL ); value = ascii_str; buffer_length = strlen((char*) ascii_str ); break; default: break; } ret = SQLSETDESCFIELD( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tExit:[%s]", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } if ( ascii_str ) { free( ascii_str ); } } return function_return( SQL_HANDLE_DESC, descriptor, ret ); } Commit Message: New Pre Source CWE ID: CWE-119
SQLRETURN SQLSetDescFieldW( SQLHDESC descriptor_handle, SQLSMALLINT rec_number, SQLSMALLINT field_identifier, SQLPOINTER value, SQLINTEGER buffer_length ) { /* * not quite sure how the descriptor can be * allocated to a statement, all the documentation talks * about state transitions on statement states, but the * descriptor may be allocated with more than one statement * at one time. Which one should I check ? */ DMHDESC descriptor = (DMHDESC) descriptor_handle; SQLRETURN ret; SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ]; int isStrField = 0; /* * check descriptor */ if ( !__validate_desc( descriptor )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: SQL_INVALID_HANDLE" ); #ifdef WITH_HANDLE_REDIRECT { DMHDESC parent_desc; parent_desc = find_parent_handle( descriptor, SQL_HANDLE_DESC ); if ( parent_desc ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Info: found parent handle" ); if ( CHECK_SQLSETDESCFIELDW( parent_desc -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Info: calling redirected driver function" ); return SQLSETDESCFIELDW( parent_desc -> connection, descriptor, rec_number, field_identifier, value, buffer_length ); } } } #endif return SQL_INVALID_HANDLE; } function_entry( descriptor ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tEntry:\ \n\t\t\tDescriptor = %p\ \n\t\t\tRec Number = %d\ \n\t\t\tField Ident = %s\ \n\t\t\tValue = %p\ \n\t\t\tBuffer Length = %d", descriptor, rec_number, __desc_attr_as_string( s1, field_identifier ), value, (int)buffer_length ); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } thread_protect( SQL_HANDLE_DESC, descriptor ); if ( descriptor -> connection -> state < STATE_C4 ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * check status of statements associated with this descriptor */ if( __check_stmt_from_desc( descriptor, STATE_S8 ) || __check_stmt_from_desc( descriptor, STATE_S9 ) || __check_stmt_from_desc( descriptor, STATE_S10 ) || __check_stmt_from_desc( descriptor, STATE_S11 ) || __check_stmt_from_desc( descriptor, STATE_S12 ) || __check_stmt_from_desc( descriptor, STATE_S13 ) || __check_stmt_from_desc( descriptor, STATE_S14 ) || __check_stmt_from_desc( descriptor, STATE_S15 )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( rec_number < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } switch ( field_identifier ) { /* Fixed-length fields: buffer_length is ignored */ case SQL_DESC_ALLOC_TYPE: case SQL_DESC_ARRAY_SIZE: case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_BIND_OFFSET_PTR: case SQL_DESC_BIND_TYPE: case SQL_DESC_COUNT: case SQL_DESC_ROWS_PROCESSED_PTR: case SQL_DESC_AUTO_UNIQUE_VALUE: case SQL_DESC_CASE_SENSITIVE: case SQL_DESC_CONCISE_TYPE: case SQL_DESC_DATA_PTR: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_DISPLAY_SIZE: case SQL_DESC_FIXED_PREC_SCALE: case SQL_DESC_INDICATOR_PTR: case SQL_DESC_LENGTH: case SQL_DESC_NULLABLE: case SQL_DESC_NUM_PREC_RADIX: case SQL_DESC_OCTET_LENGTH: case SQL_DESC_OCTET_LENGTH_PTR: case SQL_DESC_PARAMETER_TYPE: case SQL_DESC_PRECISION: case SQL_DESC_ROWVER: case SQL_DESC_SCALE: case SQL_DESC_SEARCHABLE: case SQL_DESC_TYPE: case SQL_DESC_UNNAMED: case SQL_DESC_UNSIGNED: case SQL_DESC_UPDATABLE: isStrField = 0; break; /* Pointer to data: buffer_length must be valid */ case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: isStrField = 1; break; default: isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER && buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT && buffer_length != SQL_IS_USMALLINT; } if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS) { __post_internal_error( &descriptor -> error, ERROR_HY090, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_COUNT && (intptr_t)value < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_PARAMETER_TYPE && (intptr_t)value != SQL_PARAM_INPUT && (intptr_t)value != SQL_PARAM_OUTPUT && (intptr_t)value != SQL_PARAM_INPUT_OUTPUT && (intptr_t)value != SQL_PARAM_INPUT_OUTPUT_STREAM && (intptr_t)value != SQL_PARAM_OUTPUT_STREAM ) { __post_internal_error( &descriptor -> error, ERROR_HY105, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( descriptor -> connection -> unicode_driver || CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { if ( !CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: IM001" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } ret = SQLSETDESCFIELDW( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tExit:[%s]", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } } else { SQLCHAR *ascii_str = NULL; if ( !CHECK_SQLSETDESCFIELD( descriptor -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: IM001" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * is it a char arg... */ switch ( field_identifier ) { case SQL_DESC_NAME: /* This is the only R/W SQLCHAR* type */ ascii_str = (SQLCHAR*) unicode_to_ansi_alloc( value, buffer_length, descriptor -> connection, NULL ); value = ascii_str; buffer_length = strlen((char*) ascii_str ); break; default: break; } ret = SQLSETDESCFIELD( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tExit:[%s]", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } if ( ascii_str ) { free( ascii_str ); } } return function_return( SQL_HANDLE_DESC, descriptor, ret ); }
169,311
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: MirrorMockJobInterceptor(const base::FilePath& root_http, ReportResponseHeadersOnUI report_on_ui) : root_http_(root_http), report_on_ui_(report_on_ui) {} Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service. The functionality worked, as part of converting DICE, however the test code didn't work since it depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to better match production, which removes the dependency on net/. Also: -make GetFilePathWithReplacements replace strings in the mock headers if they're present -add a global to google_util to ignore ports; that way other tests can be converted without having to modify each callsite to google_util Bug: 881976 Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058 Reviewed-on: https://chromium-review.googlesource.com/c/1328142 Commit-Queue: John Abd-El-Malek <[email protected]> Reviewed-by: Ramin Halavati <[email protected]> Reviewed-by: Maks Orlovich <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#607652} CWE ID:
MirrorMockJobInterceptor(const base::FilePath& root_http,
172,577
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void tun_net_init(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); switch (tun->flags & TUN_TYPE_MASK) { case TUN_TUN_DEV: dev->netdev_ops = &tun_netdev_ops; /* Point-to-Point TUN Device */ dev->hard_header_len = 0; dev->addr_len = 0; dev->mtu = 1500; /* Zero header length */ dev->type = ARPHRD_NONE; dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST; dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */ break; case TUN_TAP_DEV: dev->netdev_ops = &tap_netdev_ops; /* Ethernet TAP Device */ ether_setup(dev); random_ether_addr(dev->dev_addr); dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */ break; } } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
static void tun_net_init(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); switch (tun->flags & TUN_TYPE_MASK) { case TUN_TUN_DEV: dev->netdev_ops = &tun_netdev_ops; /* Point-to-Point TUN Device */ dev->hard_header_len = 0; dev->addr_len = 0; dev->mtu = 1500; /* Zero header length */ dev->type = ARPHRD_NONE; dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST; dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */ break; case TUN_TAP_DEV: dev->netdev_ops = &tap_netdev_ops; /* Ethernet TAP Device */ ether_setup(dev); dev->priv_flags &= ~IFF_TX_SKB_SHARING; random_ether_addr(dev->dev_addr); dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */ break; } }
165,730
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Document::DispatchUnloadEvents() { PluginScriptForbiddenScope forbid_plugin_destructor_scripting; if (parser_) parser_->StopParsing(); if (load_event_progress_ == kLoadEventNotRun) return; if (load_event_progress_ <= kUnloadEventInProgress) { Element* current_focused_element = FocusedElement(); if (auto* input = ToHTMLInputElementOrNull(current_focused_element)) input->EndEditing(); if (load_event_progress_ < kPageHideInProgress) { load_event_progress_ = kPageHideInProgress; if (LocalDOMWindow* window = domWindow()) { const TimeTicks pagehide_event_start = CurrentTimeTicks(); window->DispatchEvent( PageTransitionEvent::Create(EventTypeNames::pagehide, false), this); const TimeTicks pagehide_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, pagehide_histogram, ("DocumentEventTiming.PageHideDuration", 0, 10000000, 50)); pagehide_histogram.Count( (pagehide_event_end - pagehide_event_start).InMicroseconds()); } if (!frame_) return; mojom::PageVisibilityState visibility_state = GetPageVisibilityState(); load_event_progress_ = kUnloadVisibilityChangeInProgress; if (visibility_state != mojom::PageVisibilityState::kHidden) { const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks(); DispatchEvent(Event::CreateBubble(EventTypeNames::visibilitychange)); const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram, ("DocumentEventTiming.PageVibilityHiddenDuration", 0, 10000000, 50)); pagevisibility_histogram.Count((pagevisibility_hidden_event_end - pagevisibility_hidden_event_start) .InMicroseconds()); DispatchEvent( Event::CreateBubble(EventTypeNames::webkitvisibilitychange)); } if (!frame_) return; frame_->Loader().SaveScrollAnchor(); DocumentLoader* document_loader = frame_->Loader().GetProvisionalDocumentLoader(); load_event_progress_ = kUnloadEventInProgress; Event* unload_event(Event::Create(EventTypeNames::unload)); if (document_loader && document_loader->GetTiming().UnloadEventStart().is_null() && document_loader->GetTiming().UnloadEventEnd().is_null()) { DocumentLoadTiming& timing = document_loader->GetTiming(); DCHECK(!timing.NavigationStart().is_null()); const TimeTicks unload_event_start = CurrentTimeTicks(); timing.MarkUnloadEventStart(unload_event_start); frame_->DomWindow()->DispatchEvent(unload_event, this); const TimeTicks unload_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, unload_histogram, ("DocumentEventTiming.UnloadDuration", 0, 10000000, 50)); unload_histogram.Count( (unload_event_end - unload_event_start).InMicroseconds()); timing.MarkUnloadEventEnd(unload_event_end); } else { frame_->DomWindow()->DispatchEvent(unload_event, frame_->GetDocument()); } } load_event_progress_ = kUnloadEventHandled; } if (!frame_) return; bool keep_event_listeners = frame_->Loader().GetProvisionalDocumentLoader() && frame_->ShouldReuseDefaultView( frame_->Loader().GetProvisionalDocumentLoader()->Url()); if (!keep_event_listeners) RemoveAllEventListenersRecursively(); } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285
void Document::DispatchUnloadEvents() { PluginScriptForbiddenScope forbid_plugin_destructor_scripting; if (parser_) parser_->StopParsing(); if (load_event_progress_ == kLoadEventNotRun) return; if (load_event_progress_ <= kUnloadEventInProgress) { Element* current_focused_element = FocusedElement(); if (auto* input = ToHTMLInputElementOrNull(current_focused_element)) input->EndEditing(); if (load_event_progress_ < kPageHideInProgress) { load_event_progress_ = kPageHideInProgress; if (LocalDOMWindow* window = domWindow()) { const TimeTicks pagehide_event_start = CurrentTimeTicks(); window->DispatchEvent( PageTransitionEvent::Create(EventTypeNames::pagehide, false), this); const TimeTicks pagehide_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, pagehide_histogram, ("DocumentEventTiming.PageHideDuration", 0, 10000000, 50)); pagehide_histogram.Count( (pagehide_event_end - pagehide_event_start).InMicroseconds()); } if (!frame_) return; mojom::PageVisibilityState visibility_state = GetPageVisibilityState(); load_event_progress_ = kUnloadVisibilityChangeInProgress; if (visibility_state != mojom::PageVisibilityState::kHidden) { const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks(); DispatchEvent(Event::CreateBubble(EventTypeNames::visibilitychange)); const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram, ("DocumentEventTiming.PageVibilityHiddenDuration", 0, 10000000, 50)); pagevisibility_histogram.Count((pagevisibility_hidden_event_end - pagevisibility_hidden_event_start) .InMicroseconds()); DispatchEvent( Event::CreateBubble(EventTypeNames::webkitvisibilitychange)); } if (!frame_) return; frame_->Loader().SaveScrollAnchor(); DocumentLoader* document_loader = frame_->Loader().GetProvisionalDocumentLoader(); load_event_progress_ = kUnloadEventInProgress; Event* unload_event(Event::Create(EventTypeNames::unload)); if (document_loader && document_loader->GetTiming().UnloadEventStart().is_null() && document_loader->GetTiming().UnloadEventEnd().is_null()) { DocumentLoadTiming& timing = document_loader->GetTiming(); DCHECK(!timing.NavigationStart().is_null()); const TimeTicks unload_event_start = CurrentTimeTicks(); timing.MarkUnloadEventStart(unload_event_start); frame_->DomWindow()->DispatchEvent(unload_event, this); const TimeTicks unload_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, unload_histogram, ("DocumentEventTiming.UnloadDuration", 0, 10000000, 50)); unload_histogram.Count( (unload_event_end - unload_event_start).InMicroseconds()); timing.MarkUnloadEventEnd(unload_event_end); } else { frame_->DomWindow()->DispatchEvent(unload_event, frame_->GetDocument()); } } load_event_progress_ = kUnloadEventHandled; } if (!frame_) return; bool keep_event_listeners = frame_->Loader().GetProvisionalDocumentLoader() && frame_->ShouldReuseDefaultView( frame_->Loader().GetProvisionalDocumentLoader()->Url(), frame_->Loader() .GetProvisionalDocumentLoader() ->GetContentSecurityPolicy()); if (!keep_event_listeners) RemoveAllEventListenersRecursively(); }
173,195
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UsbDeviceImpl::OnPathAccessRequestComplete(const OpenCallback& callback, bool success) { if (success) { blocking_task_runner_->PostTask( FROM_HERE, base::Bind(&UsbDeviceImpl::OpenOnBlockingThread, this, callback)); } else { chromeos::PermissionBrokerClient* client = chromeos::DBusThreadManager::Get()->GetPermissionBrokerClient(); DCHECK(client) << "Could not get permission broker client."; client->OpenPath( device_path_, base::Bind(&UsbDeviceImpl::OnOpenRequestComplete, this, callback)); } } Commit Message: Remove fallback when requesting a single USB interface. This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The permission broker now supports opening devices that are partially claimed through the OpenPath method and RequestPathAccess will always fail for these devices so the fallback path from RequestPathAccess to OpenPath is always taken. BUG=500057 Review URL: https://codereview.chromium.org/1227313003 Cr-Commit-Position: refs/heads/master@{#338354} CWE ID: CWE-399
void UsbDeviceImpl::OnPathAccessRequestComplete(const OpenCallback& callback,
171,701
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __poke_user_compat(struct task_struct *child, addr_t addr, addr_t data) { struct compat_user *dummy32 = NULL; __u32 tmp = (__u32) data; addr_t offset; if (addr < (addr_t) &dummy32->regs.acrs) { struct pt_regs *regs = task_pt_regs(child); /* * psw, gprs, acrs and orig_gpr2 are stored on the stack */ if (addr == (addr_t) &dummy32->regs.psw.mask) { __u32 mask = PSW32_MASK_USER; mask |= is_ri_task(child) ? PSW32_MASK_RI : 0; /* Build a 64 bit psw mask from 31 bit mask. */ if ((tmp & ~mask) != PSW32_USER_BITS) /* Invalid psw mask. */ return -EINVAL; regs->psw.mask = (regs->psw.mask & ~PSW_MASK_USER) | (regs->psw.mask & PSW_MASK_BA) | (__u64)(tmp & mask) << 32; } else if (addr == (addr_t) &dummy32->regs.psw.addr) { /* Build a 64 bit psw address from 31 bit address. */ regs->psw.addr = (__u64) tmp & PSW32_ADDR_INSN; /* Transfer 31 bit amode bit to psw mask. */ regs->psw.mask = (regs->psw.mask & ~PSW_MASK_BA) | (__u64)(tmp & PSW32_ADDR_AMODE); } else { /* gpr 0-15 */ *(__u32*)((addr_t) &regs->psw + addr*2 + 4) = tmp; } } else if (addr < (addr_t) (&dummy32->regs.orig_gpr2)) { /* * access registers are stored in the thread structure */ offset = addr - (addr_t) &dummy32->regs.acrs; *(__u32*)((addr_t) &child->thread.acrs + offset) = tmp; } else if (addr == (addr_t) (&dummy32->regs.orig_gpr2)) { /* * orig_gpr2 is stored on the kernel stack */ *(__u32*)((addr_t) &task_pt_regs(child)->orig_gpr2 + 4) = tmp; } else if (addr < (addr_t) &dummy32->regs.fp_regs) { /* * prevent writess of padding hole between * orig_gpr2 and fp_regs on s390. */ return 0; } else if (addr < (addr_t) (&dummy32->regs.fp_regs + 1)) { /* * floating point regs. are stored in the thread structure */ if (addr == (addr_t) &dummy32->regs.fp_regs.fpc && test_fp_ctl(tmp)) return -EINVAL; offset = addr - (addr_t) &dummy32->regs.fp_regs; *(__u32 *)((addr_t) &child->thread.fp_regs + offset) = tmp; } else if (addr < (addr_t) (&dummy32->regs.per_info + 1)) { /* * Handle access to the per_info structure. */ addr -= (addr_t) &dummy32->regs.per_info; __poke_user_per_compat(child, addr, data); } return 0; } Commit Message: s390/ptrace: fix PSW mask check The PSW mask check of the PTRACE_POKEUSR_AREA command is incorrect. The PSW_MASK_USER define contains the PSW_MASK_ASC bits, the ptrace interface accepts all combinations for the address-space-control bits. To protect the kernel space the PSW mask check in ptrace needs to reject the address-space-control bit combination for home space. Fixes CVE-2014-3534 Cc: [email protected] Signed-off-by: Martin Schwidefsky <[email protected]> CWE ID: CWE-264
static int __poke_user_compat(struct task_struct *child, addr_t addr, addr_t data) { struct compat_user *dummy32 = NULL; __u32 tmp = (__u32) data; addr_t offset; if (addr < (addr_t) &dummy32->regs.acrs) { struct pt_regs *regs = task_pt_regs(child); /* * psw, gprs, acrs and orig_gpr2 are stored on the stack */ if (addr == (addr_t) &dummy32->regs.psw.mask) { __u32 mask = PSW32_MASK_USER; mask |= is_ri_task(child) ? PSW32_MASK_RI : 0; /* Build a 64 bit psw mask from 31 bit mask. */ if ((tmp ^ PSW32_USER_BITS) & ~mask) /* Invalid psw mask. */ return -EINVAL; if ((data & PSW32_MASK_ASC) == PSW32_ASC_HOME) /* Invalid address-space-control bits */ return -EINVAL; regs->psw.mask = (regs->psw.mask & ~PSW_MASK_USER) | (regs->psw.mask & PSW_MASK_BA) | (__u64)(tmp & mask) << 32; } else if (addr == (addr_t) &dummy32->regs.psw.addr) { /* Build a 64 bit psw address from 31 bit address. */ regs->psw.addr = (__u64) tmp & PSW32_ADDR_INSN; /* Transfer 31 bit amode bit to psw mask. */ regs->psw.mask = (regs->psw.mask & ~PSW_MASK_BA) | (__u64)(tmp & PSW32_ADDR_AMODE); } else { /* gpr 0-15 */ *(__u32*)((addr_t) &regs->psw + addr*2 + 4) = tmp; } } else if (addr < (addr_t) (&dummy32->regs.orig_gpr2)) { /* * access registers are stored in the thread structure */ offset = addr - (addr_t) &dummy32->regs.acrs; *(__u32*)((addr_t) &child->thread.acrs + offset) = tmp; } else if (addr == (addr_t) (&dummy32->regs.orig_gpr2)) { /* * orig_gpr2 is stored on the kernel stack */ *(__u32*)((addr_t) &task_pt_regs(child)->orig_gpr2 + 4) = tmp; } else if (addr < (addr_t) &dummy32->regs.fp_regs) { /* * prevent writess of padding hole between * orig_gpr2 and fp_regs on s390. */ return 0; } else if (addr < (addr_t) (&dummy32->regs.fp_regs + 1)) { /* * floating point regs. are stored in the thread structure */ if (addr == (addr_t) &dummy32->regs.fp_regs.fpc && test_fp_ctl(tmp)) return -EINVAL; offset = addr - (addr_t) &dummy32->regs.fp_regs; *(__u32 *)((addr_t) &child->thread.fp_regs + offset) = tmp; } else if (addr < (addr_t) (&dummy32->regs.per_info + 1)) { /* * Handle access to the per_info structure. */ addr -= (addr_t) &dummy32->regs.per_info; __poke_user_per_compat(child, addr, data); } return 0; }
166,363
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int phar_zip_flush(phar_archive_data *phar, char *user_stub, long len, int defaultstub, char **error TSRMLS_DC) /* {{{ */ { char *pos; smart_str main_metadata_str = {0}; static const char newstub[] = "<?php // zip-based phar archive stub file\n__HALT_COMPILER();"; char halt_stub[] = "__HALT_COMPILER();"; char *tmp; php_stream *stubfile, *oldfile; php_serialize_data_t metadata_hash; int free_user_stub, closeoldfile = 0; phar_entry_info entry = {0}; char *temperr = NULL; struct _phar_zip_pass pass; phar_zip_dir_end eocd; php_uint32 cdir_size, cdir_offset; pass.error = &temperr; entry.flags = PHAR_ENT_PERM_DEF_FILE; entry.timestamp = time(NULL); entry.is_modified = 1; entry.is_zip = 1; entry.phar = phar; entry.fp_type = PHAR_MOD; if (phar->is_persistent) { if (error) { spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname); } return EOF; } if (phar->is_data) { goto nostub; } /* set alias */ if (!phar->is_temporary_alias && phar->alias_len) { entry.fp = php_stream_fopen_tmpfile(); if (entry.fp == NULL) { spprintf(error, 0, "phar error: unable to create temporary file"); return EOF; } if (phar->alias_len != (int)php_stream_write(entry.fp, phar->alias, phar->alias_len)) { if (error) { spprintf(error, 0, "unable to set alias in zip-based phar \"%s\"", phar->fname); } return EOF; } entry.uncompressed_filesize = entry.compressed_filesize = phar->alias_len; entry.filename = estrndup(".phar/alias.txt", sizeof(".phar/alias.txt")-1); entry.filename_len = sizeof(".phar/alias.txt")-1; if (SUCCESS != zend_hash_update(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL)) { if (error) { spprintf(error, 0, "unable to set alias in zip-based phar \"%s\"", phar->fname); } return EOF; } } else { zend_hash_del(&phar->manifest, ".phar/alias.txt", sizeof(".phar/alias.txt")-1); } /* register alias */ if (phar->alias_len) { if (FAILURE == phar_get_archive(&phar, phar->fname, phar->fname_len, phar->alias, phar->alias_len, error TSRMLS_CC)) { return EOF; } } /* set stub */ if (user_stub && !defaultstub) { if (len < 0) { /* resource passed in */ if (!(php_stream_from_zval_no_verify(stubfile, (zval **)user_stub))) { if (error) { spprintf(error, 0, "unable to access resource to copy stub to new zip-based phar \"%s\"", phar->fname); } return EOF; } if (len == -1) { len = PHP_STREAM_COPY_ALL; } else { len = -len; } user_stub = 0; if (!(len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)) || !user_stub) { if (error) { spprintf(error, 0, "unable to read resource to copy stub to new zip-based phar \"%s\"", phar->fname); } return EOF; } free_user_stub = 1; } else { free_user_stub = 0; } tmp = estrndup(user_stub, len); if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) { efree(tmp); if (error) { spprintf(error, 0, "illegal stub for zip-based phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } pos = user_stub + (pos - tmp); efree(tmp); len = pos - user_stub + 18; entry.fp = php_stream_fopen_tmpfile(); if (entry.fp == NULL) { spprintf(error, 0, "phar error: unable to create temporary file"); return EOF; } entry.uncompressed_filesize = len + 5; if ((size_t)len != php_stream_write(entry.fp, user_stub, len) || 5 != php_stream_write(entry.fp, " ?>\r\n", 5)) { if (error) { spprintf(error, 0, "unable to create stub from string in new zip-based phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } php_stream_close(entry.fp); return EOF; } entry.filename = estrndup(".phar/stub.php", sizeof(".phar/stub.php")-1); entry.filename_len = sizeof(".phar/stub.php")-1; if (SUCCESS != zend_hash_update(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL)) { if (free_user_stub) { efree(user_stub); } if (error) { spprintf(error, 0, "unable to set stub in zip-based phar \"%s\"", phar->fname); } return EOF; } if (free_user_stub) { efree(user_stub); } } else { /* Either this is a brand new phar (add the stub), or the default stub is required (overwrite the stub) */ entry.fp = php_stream_fopen_tmpfile(); if (entry.fp == NULL) { spprintf(error, 0, "phar error: unable to create temporary file"); return EOF; } if (sizeof(newstub)-1 != php_stream_write(entry.fp, newstub, sizeof(newstub)-1)) { php_stream_close(entry.fp); if (error) { spprintf(error, 0, "unable to %s stub in%szip-based phar \"%s\", failed", user_stub ? "overwrite" : "create", user_stub ? " " : " new ", phar->fname); } return EOF; } entry.uncompressed_filesize = entry.compressed_filesize = sizeof(newstub) - 1; entry.filename = estrndup(".phar/stub.php", sizeof(".phar/stub.php")-1); entry.filename_len = sizeof(".phar/stub.php")-1; if (!defaultstub) { if (!zend_hash_exists(&phar->manifest, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { if (SUCCESS != zend_hash_add(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL)) { php_stream_close(entry.fp); efree(entry.filename); if (error) { spprintf(error, 0, "unable to create stub in zip-based phar \"%s\"", phar->fname); } return EOF; } } else { php_stream_close(entry.fp); efree(entry.filename); } } else { if (SUCCESS != zend_hash_update(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL)) { php_stream_close(entry.fp); efree(entry.filename); if (error) { spprintf(error, 0, "unable to overwrite stub in zip-based phar \"%s\"", phar->fname); } return EOF; } } } nostub: if (phar->fp && !phar->is_brandnew) { oldfile = phar->fp; closeoldfile = 0; php_stream_rewind(oldfile); } else { oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL); closeoldfile = oldfile != NULL; } /* save modified files to the zip */ pass.old = oldfile; pass.filefp = php_stream_fopen_tmpfile(); if (!pass.filefp) { fperror: if (closeoldfile) { php_stream_close(oldfile); } if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to open temporary file", phar->fname); } return EOF; } pass.centralfp = php_stream_fopen_tmpfile(); if (!pass.centralfp) { goto fperror; } pass.free_fp = pass.free_ufp = 1; memset(&eocd, 0, sizeof(eocd)); strncpy(eocd.signature, "PK\5\6", 4); if (!phar->is_data && !phar->sig_flags) { phar->sig_flags = PHAR_SIG_SHA1; } if (phar->sig_flags) { PHAR_SET_16(eocd.counthere, zend_hash_num_elements(&phar->manifest) + 1); PHAR_SET_16(eocd.count, zend_hash_num_elements(&phar->manifest) + 1); } else { PHAR_SET_16(eocd.counthere, zend_hash_num_elements(&phar->manifest)); PHAR_SET_16(eocd.count, zend_hash_num_elements(&phar->manifest)); } zend_hash_apply_with_argument(&phar->manifest, phar_zip_changed_apply, (void *) &pass TSRMLS_CC); if (phar->metadata) { /* set phar metadata */ PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } if (temperr) { if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: %s", phar->fname, temperr); } efree(temperr); temperror: php_stream_close(pass.centralfp); nocentralerror: if (phar->metadata) { smart_str_free(&main_metadata_str); } php_stream_close(pass.filefp); if (closeoldfile) { php_stream_close(oldfile); } return EOF; } if (FAILURE == phar_zip_applysignature(phar, &pass, &main_metadata_str TSRMLS_CC)) { goto temperror; } /* save zip */ cdir_size = php_stream_tell(pass.centralfp); cdir_offset = php_stream_tell(pass.filefp); PHAR_SET_32(eocd.cdir_size, cdir_size); PHAR_SET_32(eocd.cdir_offset, cdir_offset); php_stream_seek(pass.centralfp, 0, SEEK_SET); { size_t clen; int ret = phar_stream_copy_to_stream(pass.centralfp, pass.filefp, PHP_STREAM_COPY_ALL, &clen); if (SUCCESS != ret || clen != cdir_size) { if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write central-directory", phar->fname); } goto temperror; } } php_stream_close(pass.centralfp); if (phar->metadata) { /* set phar metadata */ PHAR_SET_16(eocd.comment_len, main_metadata_str.len); if (sizeof(eocd) != php_stream_write(pass.filefp, (char *)&eocd, sizeof(eocd))) { if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write end of central-directory", phar->fname); } goto nocentralerror; } if (main_metadata_str.len != php_stream_write(pass.filefp, main_metadata_str.c, main_metadata_str.len)) { if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write metadata to zip comment", phar->fname); } goto nocentralerror; } smart_str_free(&main_metadata_str); } else { if (sizeof(eocd) != php_stream_write(pass.filefp, (char *)&eocd, sizeof(eocd))) { if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write end of central-directory", phar->fname); } goto nocentralerror; } } if (phar->fp && pass.free_fp) { php_stream_close(phar->fp); } if (phar->ufp) { if (pass.free_ufp) { php_stream_close(phar->ufp); } phar->ufp = NULL; } /* re-open */ phar->is_brandnew = 0; if (phar->donotflush) { /* deferred flush */ phar->fp = pass.filefp; } else { phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL); if (!phar->fp) { if (closeoldfile) { php_stream_close(oldfile); } phar->fp = pass.filefp; if (error) { spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname); } return EOF; } php_stream_rewind(pass.filefp); phar_stream_copy_to_stream(pass.filefp, phar->fp, PHP_STREAM_COPY_ALL, NULL); /* we could also reopen the file in "rb" mode but there is no need for that */ php_stream_close(pass.filefp); } if (closeoldfile) { php_stream_close(oldfile); } return EOF; } /* }}} */ Commit Message: CWE ID: CWE-119
int phar_zip_flush(phar_archive_data *phar, char *user_stub, long len, int defaultstub, char **error TSRMLS_DC) /* {{{ */ { char *pos; smart_str main_metadata_str = {0}; static const char newstub[] = "<?php // zip-based phar archive stub file\n__HALT_COMPILER();"; char halt_stub[] = "__HALT_COMPILER();"; char *tmp; php_stream *stubfile, *oldfile; php_serialize_data_t metadata_hash; int free_user_stub, closeoldfile = 0; phar_entry_info entry = {0}; char *temperr = NULL; struct _phar_zip_pass pass; phar_zip_dir_end eocd; php_uint32 cdir_size, cdir_offset; pass.error = &temperr; entry.flags = PHAR_ENT_PERM_DEF_FILE; entry.timestamp = time(NULL); entry.is_modified = 1; entry.is_zip = 1; entry.phar = phar; entry.fp_type = PHAR_MOD; if (phar->is_persistent) { if (error) { spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname); } return EOF; } if (phar->is_data) { goto nostub; } /* set alias */ if (!phar->is_temporary_alias && phar->alias_len) { entry.fp = php_stream_fopen_tmpfile(); if (entry.fp == NULL) { spprintf(error, 0, "phar error: unable to create temporary file"); return EOF; } if (phar->alias_len != (int)php_stream_write(entry.fp, phar->alias, phar->alias_len)) { if (error) { spprintf(error, 0, "unable to set alias in zip-based phar \"%s\"", phar->fname); } return EOF; } entry.uncompressed_filesize = entry.compressed_filesize = phar->alias_len; entry.filename = estrndup(".phar/alias.txt", sizeof(".phar/alias.txt")-1); entry.filename_len = sizeof(".phar/alias.txt")-1; if (SUCCESS != zend_hash_update(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL)) { if (error) { spprintf(error, 0, "unable to set alias in zip-based phar \"%s\"", phar->fname); } return EOF; } } else { zend_hash_del(&phar->manifest, ".phar/alias.txt", sizeof(".phar/alias.txt")-1); } /* register alias */ if (phar->alias_len) { if (FAILURE == phar_get_archive(&phar, phar->fname, phar->fname_len, phar->alias, phar->alias_len, error TSRMLS_CC)) { return EOF; } } /* set stub */ if (user_stub && !defaultstub) { if (len < 0) { /* resource passed in */ if (!(php_stream_from_zval_no_verify(stubfile, (zval **)user_stub))) { if (error) { spprintf(error, 0, "unable to access resource to copy stub to new zip-based phar \"%s\"", phar->fname); } return EOF; } if (len == -1) { len = PHP_STREAM_COPY_ALL; } else { len = -len; } user_stub = 0; if (!(len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)) || !user_stub) { if (error) { spprintf(error, 0, "unable to read resource to copy stub to new zip-based phar \"%s\"", phar->fname); } return EOF; } free_user_stub = 1; } else { free_user_stub = 0; } tmp = estrndup(user_stub, len); if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) { efree(tmp); if (error) { spprintf(error, 0, "illegal stub for zip-based phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } pos = user_stub + (pos - tmp); efree(tmp); len = pos - user_stub + 18; entry.fp = php_stream_fopen_tmpfile(); if (entry.fp == NULL) { spprintf(error, 0, "phar error: unable to create temporary file"); return EOF; } entry.uncompressed_filesize = len + 5; if ((size_t)len != php_stream_write(entry.fp, user_stub, len) || 5 != php_stream_write(entry.fp, " ?>\r\n", 5)) { if (error) { spprintf(error, 0, "unable to create stub from string in new zip-based phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } php_stream_close(entry.fp); return EOF; } entry.filename = estrndup(".phar/stub.php", sizeof(".phar/stub.php")-1); entry.filename_len = sizeof(".phar/stub.php")-1; if (SUCCESS != zend_hash_update(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL)) { if (free_user_stub) { efree(user_stub); } if (error) { spprintf(error, 0, "unable to set stub in zip-based phar \"%s\"", phar->fname); } return EOF; } if (free_user_stub) { efree(user_stub); } } else { /* Either this is a brand new phar (add the stub), or the default stub is required (overwrite the stub) */ entry.fp = php_stream_fopen_tmpfile(); if (entry.fp == NULL) { spprintf(error, 0, "phar error: unable to create temporary file"); return EOF; } if (sizeof(newstub)-1 != php_stream_write(entry.fp, newstub, sizeof(newstub)-1)) { php_stream_close(entry.fp); if (error) { spprintf(error, 0, "unable to %s stub in%szip-based phar \"%s\", failed", user_stub ? "overwrite" : "create", user_stub ? " " : " new ", phar->fname); } return EOF; } entry.uncompressed_filesize = entry.compressed_filesize = sizeof(newstub) - 1; entry.filename = estrndup(".phar/stub.php", sizeof(".phar/stub.php")-1); entry.filename_len = sizeof(".phar/stub.php")-1; if (!defaultstub) { if (!zend_hash_exists(&phar->manifest, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { if (SUCCESS != zend_hash_add(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL)) { php_stream_close(entry.fp); efree(entry.filename); if (error) { spprintf(error, 0, "unable to create stub in zip-based phar \"%s\"", phar->fname); } return EOF; } } else { php_stream_close(entry.fp); efree(entry.filename); } } else { if (SUCCESS != zend_hash_update(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL)) { php_stream_close(entry.fp); efree(entry.filename); if (error) { spprintf(error, 0, "unable to overwrite stub in zip-based phar \"%s\"", phar->fname); } return EOF; } } } nostub: if (phar->fp && !phar->is_brandnew) { oldfile = phar->fp; closeoldfile = 0; php_stream_rewind(oldfile); } else { oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL); closeoldfile = oldfile != NULL; } /* save modified files to the zip */ pass.old = oldfile; pass.filefp = php_stream_fopen_tmpfile(); if (!pass.filefp) { fperror: if (closeoldfile) { php_stream_close(oldfile); } if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to open temporary file", phar->fname); } return EOF; } pass.centralfp = php_stream_fopen_tmpfile(); if (!pass.centralfp) { goto fperror; } pass.free_fp = pass.free_ufp = 1; memset(&eocd, 0, sizeof(eocd)); strncpy(eocd.signature, "PK\5\6", 4); if (!phar->is_data && !phar->sig_flags) { phar->sig_flags = PHAR_SIG_SHA1; } if (phar->sig_flags) { PHAR_SET_16(eocd.counthere, zend_hash_num_elements(&phar->manifest) + 1); PHAR_SET_16(eocd.count, zend_hash_num_elements(&phar->manifest) + 1); } else { PHAR_SET_16(eocd.counthere, zend_hash_num_elements(&phar->manifest)); PHAR_SET_16(eocd.count, zend_hash_num_elements(&phar->manifest)); } zend_hash_apply_with_argument(&phar->manifest, phar_zip_changed_apply, (void *) &pass TSRMLS_CC); if (phar->metadata) { /* set phar metadata */ PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } if (temperr) { if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: %s", phar->fname, temperr); } efree(temperr); temperror: php_stream_close(pass.centralfp); nocentralerror: if (phar->metadata) { smart_str_free(&main_metadata_str); } php_stream_close(pass.filefp); if (closeoldfile) { php_stream_close(oldfile); } return EOF; } if (FAILURE == phar_zip_applysignature(phar, &pass, &main_metadata_str TSRMLS_CC)) { goto temperror; } /* save zip */ cdir_size = php_stream_tell(pass.centralfp); cdir_offset = php_stream_tell(pass.filefp); PHAR_SET_32(eocd.cdir_size, cdir_size); PHAR_SET_32(eocd.cdir_offset, cdir_offset); php_stream_seek(pass.centralfp, 0, SEEK_SET); { size_t clen; int ret = phar_stream_copy_to_stream(pass.centralfp, pass.filefp, PHP_STREAM_COPY_ALL, &clen); if (SUCCESS != ret || clen != cdir_size) { if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write central-directory", phar->fname); } goto temperror; } } php_stream_close(pass.centralfp); if (phar->metadata) { /* set phar metadata */ PHAR_SET_16(eocd.comment_len, main_metadata_str.len); if (sizeof(eocd) != php_stream_write(pass.filefp, (char *)&eocd, sizeof(eocd))) { if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write end of central-directory", phar->fname); } goto nocentralerror; } if (main_metadata_str.len != php_stream_write(pass.filefp, main_metadata_str.c, main_metadata_str.len)) { if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write metadata to zip comment", phar->fname); } goto nocentralerror; } smart_str_free(&main_metadata_str); } else { if (sizeof(eocd) != php_stream_write(pass.filefp, (char *)&eocd, sizeof(eocd))) { if (error) { spprintf(error, 4096, "phar zip flush of \"%s\" failed: unable to write end of central-directory", phar->fname); } goto nocentralerror; } } if (phar->fp && pass.free_fp) { php_stream_close(phar->fp); } if (phar->ufp) { if (pass.free_ufp) { php_stream_close(phar->ufp); } phar->ufp = NULL; } /* re-open */ phar->is_brandnew = 0; if (phar->donotflush) { /* deferred flush */ phar->fp = pass.filefp; } else { phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL); if (!phar->fp) { if (closeoldfile) { php_stream_close(oldfile); } phar->fp = pass.filefp; if (error) { spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname); } return EOF; } php_stream_rewind(pass.filefp); phar_stream_copy_to_stream(pass.filefp, phar->fp, PHP_STREAM_COPY_ALL, NULL); /* we could also reopen the file in "rb" mode but there is no need for that */ php_stream_close(pass.filefp); } if (closeoldfile) { php_stream_close(oldfile); } return EOF; } /* }}} */
165,164
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/549 CWE ID: CWE-770
static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); }
167,979
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void testInspectorManualAttachDetach(CustomInspectorTest* test, gconstpointer) { test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); test->resizeView(200, 200); test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); test->showAndWaitUntilFinished(false); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(webkit_web_inspector_get_web_view(test->m_inspector))); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); Vector<InspectorTest::InspectorEvents>& events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Attach); test->m_events.clear(); test->detachAndWaitUntilWindowOpened(); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); test->m_events.clear(); test->closeAndWaitUntilClosed(); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::Closed); test->m_events.clear(); } Commit Message: [GTK] Inspector should set a default attached height before being attached https://bugs.webkit.org/show_bug.cgi?id=90767 Reviewed by Xan Lopez. We are currently using the minimum attached height in WebKitWebViewBase as the default height for the inspector when attached. It would be easier for WebKitWebViewBase and embedders implementing attach() if the inspector already had an attached height set when it's being attached. * UIProcess/API/gtk/WebKitWebViewBase.cpp: (webkitWebViewBaseContainerAdd): Don't initialize inspectorViewHeight. (webkitWebViewBaseSetInspectorViewHeight): Allow to set the inspector view height before having an inpector view, but only queue a resize when the view already has an inspector view. * UIProcess/API/gtk/tests/TestInspector.cpp: (testInspectorDefault): (testInspectorManualAttachDetach): * UIProcess/gtk/WebInspectorProxyGtk.cpp: (WebKit::WebInspectorProxy::platformAttach): Set the default attached height before attach the inspector view. git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void testInspectorManualAttachDetach(CustomInspectorTest* test, gconstpointer) { test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); test->resizeView(200, 200); test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); test->showAndWaitUntilFinished(false); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(webkit_web_inspector_get_web_view(test->m_inspector))); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); Vector<InspectorTest::InspectorEvents>& events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), >=, InspectorTest::gMinimumAttachedInspectorHeight); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Attach); test->m_events.clear(); test->detachAndWaitUntilWindowOpened(); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); test->m_events.clear(); test->closeAndWaitUntilClosed(); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::Closed); test->m_events.clear(); }
171,056
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PlatformSensor::GetLatestReading(SensorReading* result) { if (!shared_buffer_reader_) { const auto* buffer = static_cast<const device::SensorReadingSharedBuffer*>( shared_buffer_mapping_.get()); shared_buffer_reader_ = std::make_unique<SensorReadingSharedBufferReader>(buffer); } return shared_buffer_reader_->GetReading(result); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732
bool PlatformSensor::GetLatestReading(SensorReading* result) { if (!shared_buffer_reader_) { shared_buffer_reader_ = std::make_unique<SensorReadingSharedBufferReader>(reading_buffer_); } return shared_buffer_reader_->GetReading(result); }
172,821
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaControlTimelineElement::defaultEventHandler(Event* event) { if (event->isMouseEvent() && toMouseEvent(event)->button() != static_cast<short>(WebPointerProperties::Button::Left)) return; if (!isConnected() || !document().isActive()) return; if (event->type() == EventTypeNames::mousedown) { Platform::current()->recordAction( UserMetricsAction("Media.Controls.ScrubbingBegin")); mediaControls().beginScrubbing(); } if (event->type() == EventTypeNames::mouseup) { Platform::current()->recordAction( UserMetricsAction("Media.Controls.ScrubbingEnd")); mediaControls().endScrubbing(); } MediaControlInputElement::defaultEventHandler(event); if (event->type() == EventTypeNames::mouseover || event->type() == EventTypeNames::mouseout || event->type() == EventTypeNames::mousemove) return; double time = value().toDouble(); if (event->type() == EventTypeNames::input) { if (mediaElement().seekable()->contain(time)) mediaElement().setCurrentTime(time); } LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject())); if (!slider.isNull() && slider.inDragMode()) mediaControls().updateCurrentTimeDisplay(); } Commit Message: Fixed volume slider element event handling MediaControlVolumeSliderElement::defaultEventHandler has making redundant calls to setVolume() & setMuted() on mouse activity. E.g. if a mouse click changed the slider position, the above calls were made 4 times, once for each of these events: mousedown, input, mouseup, DOMActive, click. This crack got exposed when PointerEvents are enabled by default on M55, adding pointermove, pointerdown & pointerup to the list. This CL fixes the code to trigger the calls to setVolume() & setMuted() only when the slider position is changed. Also added pointer events to certain lists of mouse events in the code. BUG=677900 Review-Url: https://codereview.chromium.org/2622273003 Cr-Commit-Position: refs/heads/master@{#446032} CWE ID: CWE-119
void MediaControlTimelineElement::defaultEventHandler(Event* event) { if (event->isMouseEvent() && toMouseEvent(event)->button() != static_cast<short>(WebPointerProperties::Button::Left)) return; if (!isConnected() || !document().isActive()) return; if (event->type() == EventTypeNames::mousedown) { Platform::current()->recordAction( UserMetricsAction("Media.Controls.ScrubbingBegin")); mediaControls().beginScrubbing(); } if (event->type() == EventTypeNames::mouseup) { Platform::current()->recordAction( UserMetricsAction("Media.Controls.ScrubbingEnd")); mediaControls().endScrubbing(); } MediaControlInputElement::defaultEventHandler(event); if (event->type() != EventTypeNames::input) return; double time = value().toDouble(); // FIXME: This will need to take the timeline offset into consideration // once that concept is supported, see https://crbug.com/312699 if (mediaElement().seekable()->contain(time)) mediaElement().setCurrentTime(time); LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject())); if (!slider.isNull() && slider.inDragMode()) mediaControls().updateCurrentTimeDisplay(); }
171,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftVideoDecoderOMXComponent::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { const int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, mComponentRole, OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamVideoPortFormat: { OMX_VIDEO_PARAM_PORTFORMATTYPE *formatParams = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > kMaxPortIndex) { return OMX_ErrorBadPortIndex; } if (formatParams->nIndex != 0) { return OMX_ErrorNoMore; } if (formatParams->nPortIndex == kInputPortIndex) { if (formatParams->eCompressionFormat != mCodingType || formatParams->eColorFormat != OMX_COLOR_FormatUnused) { return OMX_ErrorUnsupportedSetting; } } else { if (formatParams->eCompressionFormat != OMX_VIDEO_CodingUnused || formatParams->eColorFormat != OMX_COLOR_FormatYUV420Planar) { return OMX_ErrorUnsupportedSetting; } } return OMX_ErrorNone; } case kPrepareForAdaptivePlaybackIndex: { const PrepareForAdaptivePlaybackParams* adaptivePlaybackParams = (const PrepareForAdaptivePlaybackParams *)params; mIsAdaptive = adaptivePlaybackParams->bEnable; if (mIsAdaptive) { mAdaptiveMaxWidth = adaptivePlaybackParams->nMaxFrameWidth; mAdaptiveMaxHeight = adaptivePlaybackParams->nMaxFrameHeight; mWidth = mAdaptiveMaxWidth; mHeight = mAdaptiveMaxHeight; } else { mAdaptiveMaxWidth = 0; mAdaptiveMaxHeight = 0; } updatePortDefinitions(true /* updateCrop */, true /* updateInputSize */); return OMX_ErrorNone; } case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *newParams = (OMX_PARAM_PORTDEFINITIONTYPE *)params; OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &newParams->format.video; OMX_PARAM_PORTDEFINITIONTYPE *def = &editPortInfo(newParams->nPortIndex)->mDef; uint32_t oldWidth = def->format.video.nFrameWidth; uint32_t oldHeight = def->format.video.nFrameHeight; uint32_t newWidth = video_def->nFrameWidth; uint32_t newHeight = video_def->nFrameHeight; if (newWidth != oldWidth || newHeight != oldHeight) { bool outputPort = (newParams->nPortIndex == kOutputPortIndex); if (outputPort) { mWidth = newWidth; mHeight = newHeight; updatePortDefinitions(true /* updateCrop */, true /* updateInputSize */); newParams->nBufferSize = def->nBufferSize; } else { def->format.video.nFrameWidth = newWidth; def->format.video.nFrameHeight = newHeight; } } return SimpleSoftOMXComponent::internalSetParameter(index, params); } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftVideoDecoderOMXComponent::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { const int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, mComponentRole, OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamVideoPortFormat: { OMX_VIDEO_PARAM_PORTFORMATTYPE *formatParams = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > kMaxPortIndex) { return OMX_ErrorBadPortIndex; } if (formatParams->nIndex != 0) { return OMX_ErrorNoMore; } if (formatParams->nPortIndex == kInputPortIndex) { if (formatParams->eCompressionFormat != mCodingType || formatParams->eColorFormat != OMX_COLOR_FormatUnused) { return OMX_ErrorUnsupportedSetting; } } else { if (formatParams->eCompressionFormat != OMX_VIDEO_CodingUnused || formatParams->eColorFormat != OMX_COLOR_FormatYUV420Planar) { return OMX_ErrorUnsupportedSetting; } } return OMX_ErrorNone; } case kPrepareForAdaptivePlaybackIndex: { const PrepareForAdaptivePlaybackParams* adaptivePlaybackParams = (const PrepareForAdaptivePlaybackParams *)params; if (!isValidOMXParam(adaptivePlaybackParams)) { return OMX_ErrorBadParameter; } mIsAdaptive = adaptivePlaybackParams->bEnable; if (mIsAdaptive) { mAdaptiveMaxWidth = adaptivePlaybackParams->nMaxFrameWidth; mAdaptiveMaxHeight = adaptivePlaybackParams->nMaxFrameHeight; mWidth = mAdaptiveMaxWidth; mHeight = mAdaptiveMaxHeight; } else { mAdaptiveMaxWidth = 0; mAdaptiveMaxHeight = 0; } updatePortDefinitions(true /* updateCrop */, true /* updateInputSize */); return OMX_ErrorNone; } case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *newParams = (OMX_PARAM_PORTDEFINITIONTYPE *)params; if (!isValidOMXParam(newParams)) { return OMX_ErrorBadParameter; } OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &newParams->format.video; OMX_PARAM_PORTDEFINITIONTYPE *def = &editPortInfo(newParams->nPortIndex)->mDef; uint32_t oldWidth = def->format.video.nFrameWidth; uint32_t oldHeight = def->format.video.nFrameHeight; uint32_t newWidth = video_def->nFrameWidth; uint32_t newHeight = video_def->nFrameHeight; if (newWidth != oldWidth || newHeight != oldHeight) { bool outputPort = (newParams->nPortIndex == kOutputPortIndex); if (outputPort) { mWidth = newWidth; mHeight = newHeight; updatePortDefinitions(true /* updateCrop */, true /* updateInputSize */); newParams->nBufferSize = def->nBufferSize; } else { def->format.video.nFrameWidth = newWidth; def->format.video.nFrameHeight = newHeight; } } return SimpleSoftOMXComponent::internalSetParameter(index, params); } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,226
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DelegatedFrameHost::CopyFromCompositingSurface( const gfx::Rect& src_subrect, const gfx::Size& dst_size, const base::Callback<void(bool, const SkBitmap&)>& callback, const SkColorType color_type) { bool format_support = ((color_type == kRGB_565_SkColorType) || (color_type == kN32_SkColorType)); DCHECK(format_support); if (!CanCopyToBitmap()) { callback.Run(false, SkBitmap()); return; } const gfx::Size& dst_size_in_pixel = client_->ConvertViewSizeToPixel(dst_size); scoped_ptr<cc::CopyOutputRequest> request = cc::CopyOutputRequest::CreateRequest(base::Bind( &DelegatedFrameHost::CopyFromCompositingSurfaceHasResult, dst_size_in_pixel, color_type, callback)); gfx::Rect src_subrect_in_pixel = ConvertRectToPixel(client_->CurrentDeviceScaleFactor(), src_subrect); request->set_area(src_subrect_in_pixel); client_->RequestCopyOfOutput(request.Pass()); } Commit Message: repairs CopyFromCompositingSurface in HighDPI This CL removes the DIP=>Pixel transform in DelegatedFrameHost::CopyFromCompositingSurface(), because said transformation seems to be happening later in the copy logic and is currently being applied twice. BUG=397708 Review URL: https://codereview.chromium.org/421293002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@286414 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void DelegatedFrameHost::CopyFromCompositingSurface( const gfx::Rect& src_subrect, const gfx::Size& output_size, const base::Callback<void(bool, const SkBitmap&)>& callback, const SkColorType color_type) { bool format_support = ((color_type == kRGB_565_SkColorType) || (color_type == kN32_SkColorType)); DCHECK(format_support); if (!CanCopyToBitmap()) { callback.Run(false, SkBitmap()); return; } scoped_ptr<cc::CopyOutputRequest> request = cc::CopyOutputRequest::CreateRequest(base::Bind( &DelegatedFrameHost::CopyFromCompositingSurfaceHasResult, output_size, color_type, callback)); request->set_area(src_subrect); client_->RequestCopyOfOutput(request.Pass()); }
171,193
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::OutputPicture( const scoped_refptr<VP9Picture>& pic) { scoped_refptr<VaapiDecodeSurface> dec_surface = VP9PictureToVaapiDecodeSurface(pic); dec_surface->set_visible_rect(pic->visible_rect); vaapi_dec_->SurfaceReady(dec_surface); return true; } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362
bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::OutputPicture( const scoped_refptr<VP9Picture>& pic) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); scoped_refptr<VaapiDecodeSurface> dec_surface = VP9PictureToVaapiDecodeSurface(pic); dec_surface->set_visible_rect(pic->visible_rect); vaapi_dec_->SurfaceReady(dec_surface); return true; }
172,806
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DetachWebContentsTest(DiscardReason reason) { LifecycleUnit* first_lifecycle_unit = nullptr; LifecycleUnit* second_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &first_lifecycle_unit, &second_lifecycle_unit); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); std::unique_ptr<content::WebContents> owned_contents = tab_strip_model_->DetachWebContentsAt(0); ExpectCanDiscardFalseTrivialAllReasons(first_lifecycle_unit); NoUnloadListenerTabStripModelDelegate other_tab_strip_model_delegate; TabStripModel other_tab_strip_model(&other_tab_strip_model_delegate, profile()); other_tab_strip_model.AddObserver(source_); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)); other_tab_strip_model.AppendWebContents(CreateTestWebContents(), /*foreground=*/true); other_tab_strip_model.AppendWebContents(std::move(owned_contents), false); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); EXPECT_EQ(LifecycleUnitState::ACTIVE, first_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); first_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, first_lifecycle_unit); CloseTabsAndExpectNotifications(&other_tab_strip_model, {first_lifecycle_unit}); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void DetachWebContentsTest(DiscardReason reason) { LifecycleUnit* first_lifecycle_unit = nullptr; LifecycleUnit* second_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &first_lifecycle_unit, &second_lifecycle_unit); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); std::unique_ptr<content::WebContents> owned_contents = tab_strip_model_->DetachWebContentsAt(0); ExpectCanDiscardFalseTrivialAllReasons(first_lifecycle_unit); NoUnloadListenerTabStripModelDelegate other_tab_strip_model_delegate; TabStripModel other_tab_strip_model(&other_tab_strip_model_delegate, profile()); other_tab_strip_model.AddObserver(source_); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(::testing::_)); other_tab_strip_model.AppendWebContents(CreateTestWebContents(), /*foreground=*/true); other_tab_strip_model.AppendWebContents(std::move(owned_contents), false); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); EXPECT_EQ(LifecycleUnitState::ACTIVE, first_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true)); first_lifecycle_unit->Discard(reason); ::testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, first_lifecycle_unit); CloseTabsAndExpectNotifications(&other_tab_strip_model, {first_lifecycle_unit}); }
172,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostImpl::AcknowledgeBufferPresent( int32 route_id, int gpu_host_id, bool presented, uint32 sync_point) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id); if (ui_shim) ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id, presented, sync_point)); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostImpl::AcknowledgeBufferPresent( int32 route_id, int gpu_host_id, uint64 surface_handle, uint32 sync_point) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id); if (ui_shim) ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id, surface_handle, sync_point)); }
171,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int date_from_ISO8601 (const char *text, time_t * value) { struct tm tm; * Begin Time Functions * ***********************/ static int date_from_ISO8601 (const char *text, time_t * value) { struct tm tm; int n; int i; char buf[18]; if (strchr (text, '-')) { char *p = (char *) text, *p2 = buf; } if (*p != '-') { *p2 = *p; p2++; } p++; } } Commit Message: CWE ID: CWE-119
static int date_from_ISO8601 (const char *text, time_t * value) { struct tm tm; * Begin Time Functions * ***********************/ static time_t mkgmtime(struct tm *tm) { static const int mdays[12] = {0,31,59,90,120,151,181,212,243,273,304,334}; return ((((((tm->tm_year - 70) * 365) + mdays[tm->tm_mon] + tm->tm_mday-1 + (tm->tm_year-68-1+(tm->tm_mon>=2))/4) * 24) + tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_sec; } static int date_from_ISO8601 (const char *text, time_t * value) { struct tm tm; int n; int i; char buf[30]; if (strchr (text, '-')) { char *p = (char *) text, *p2 = buf; } if (*p != '-') { *p2 = *p; p2++; if (p2-buf >= sizeof(buf)) { return -1; } } p++; } }
164,889
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_parse_decode_slice(UWORD8 u1_is_idr_slice, UWORD8 u1_nal_ref_idc, dec_struct_t *ps_dec /* Decoder parameters */ ) { dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm; dec_pic_params_t *ps_pps; dec_seq_params_t *ps_seq; dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; pocstruct_t s_tmp_poc; WORD32 i_delta_poc[2]; WORD32 i4_poc = 0; UWORD16 u2_first_mb_in_slice, u2_frame_num; UWORD8 u1_field_pic_flag, u1_redundant_pic_cnt = 0, u1_slice_type; UWORD32 u4_idr_pic_id = 0; UWORD8 u1_bottom_field_flag, u1_pic_order_cnt_type; UWORD8 u1_nal_unit_type; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; WORD8 i1_is_end_of_poc; WORD32 ret, end_of_frame; WORD32 prev_slice_err, num_mb_skipped; UWORD8 u1_mbaff; pocstruct_t *ps_cur_poc; UWORD32 u4_temp; WORD32 i_temp; UWORD32 u4_call_end_of_pic = 0; /* read FirstMbInSlice and slice type*/ ps_dec->ps_dpb_cmds->u1_dpb_commands_read_slc = 0; u2_first_mb_in_slice = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u2_first_mb_in_slice > (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)) { return ERROR_CORRUPTED_SLICE; } /*we currently don not support ASO*/ if(((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag) <= ps_dec->u2_cur_mb_addr) && (ps_dec->u2_cur_mb_addr != 0) && (ps_dec->u4_first_slice_in_pic != 0)) { return ERROR_CORRUPTED_SLICE; } COPYTHECONTEXT("SH: first_mb_in_slice",u2_first_mb_in_slice); u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > 9) return ERROR_INV_SLC_TYPE_T; u1_slice_type = u4_temp; COPYTHECONTEXT("SH: slice_type",(u1_slice_type)); ps_dec->u1_sl_typ_5_9 = 0; /* Find Out the Slice Type is 5 to 9 or not then Set the Flag */ /* u1_sl_typ_5_9 = 1 .Which tells that all the slices in the Pic*/ /* will be of same type of current */ if(u1_slice_type > 4) { u1_slice_type -= 5; ps_dec->u1_sl_typ_5_9 = 1; } { UWORD32 skip; if((ps_dec->i4_app_skip_mode == IVD_SKIP_PB) || (ps_dec->i4_dec_skip_mode == IVD_SKIP_PB)) { UWORD32 u4_bit_stream_offset = 0; if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) { skip = 0; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; } else if((I_SLICE == u1_slice_type) && (1 >= ps_dec->ps_cur_sps->u1_num_ref_frames)) { skip = 0; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; } else { skip = 1; } /* If one frame worth of data is already skipped, do not skip the next one */ if((0 == u2_first_mb_in_slice) && (1 == ps_dec->u4_prev_nal_skipped)) { skip = 0; } if(skip) { ps_dec->u4_prev_nal_skipped = 1; ps_dec->i4_dec_skip_mode = IVD_SKIP_PB; return 0; } else { /* If the previous NAL was skipped, then do not process that buffer in this call. Return to app and process it in the next call. This is necessary to handle cases where I/IDR is not complete in the current buffer and application intends to fill the remaining part of the bitstream later. This ensures we process only frame worth of data in every call */ if(1 == ps_dec->u4_prev_nal_skipped) { ps_dec->u4_return_to_app = 1; return 0; } } } } u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp & MASK_ERR_PIC_SET_ID) return ERROR_INV_SPS_PPS_T; /* discard slice if pic param is invalid */ COPYTHECONTEXT("SH: pic_parameter_set_id", u4_temp); ps_pps = &ps_dec->ps_pps[u4_temp]; if(FALSE == ps_pps->u1_is_valid) { return ERROR_INV_SPS_PPS_T; } ps_seq = ps_pps->ps_sps; if(!ps_seq) return ERROR_INV_SPS_PPS_T; if(FALSE == ps_seq->u1_is_valid) return ERROR_INV_SPS_PPS_T; /* Get the frame num */ u2_frame_num = ih264d_get_bits_h264(ps_bitstrm, ps_seq->u1_bits_in_frm_num); COPYTHECONTEXT("SH: frame_num", u2_frame_num); /* Get the field related flags */ if(!ps_seq->u1_frame_mbs_only_flag) { u1_field_pic_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: field_pic_flag", u1_field_pic_flag); u1_bottom_field_flag = 0; if(u1_field_pic_flag) { ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan_fld; u1_bottom_field_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: bottom_field_flag", u1_bottom_field_flag); } else { ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; } } else { u1_field_pic_flag = 0; u1_bottom_field_flag = 0; ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; } u1_nal_unit_type = SLICE_NAL; if(u1_is_idr_slice) { if(0 == u1_field_pic_flag) { ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY; } u1_nal_unit_type = IDR_SLICE_NAL; u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_idr_pic_id > 65535) return ERROR_INV_SPS_PPS_T; COPYTHECONTEXT("SH: ", u4_idr_pic_id); } /* read delta pic order count information*/ i_delta_poc[0] = i_delta_poc[1] = 0; s_tmp_poc.i4_pic_order_cnt_lsb = 0; s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; u1_pic_order_cnt_type = ps_seq->u1_pic_order_cnt_type; if(u1_pic_order_cnt_type == 0) { i_temp = ih264d_get_bits_h264( ps_bitstrm, ps_seq->u1_log2_max_pic_order_cnt_lsb_minus); if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb) return ERROR_INV_SPS_PPS_T; s_tmp_poc.i4_pic_order_cnt_lsb = i_temp; COPYTHECONTEXT("SH: pic_order_cnt_lsb", s_tmp_poc.i4_pic_order_cnt_lsb); if((ps_pps->u1_pic_order_present_flag == 1) && (!u1_field_pic_flag)) { s_tmp_poc.i4_delta_pic_order_cnt_bottom = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt_bottom", s_tmp_poc.i4_delta_pic_order_cnt_bottom); } } s_tmp_poc.i4_delta_pic_order_cnt[0] = 0; s_tmp_poc.i4_delta_pic_order_cnt[1] = 0; if(u1_pic_order_cnt_type == 1 && (!ps_seq->u1_delta_pic_order_always_zero_flag)) { s_tmp_poc.i4_delta_pic_order_cnt[0] = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt[0]", s_tmp_poc.i4_delta_pic_order_cnt[0]); if(ps_pps->u1_pic_order_present_flag && !u1_field_pic_flag) { s_tmp_poc.i4_delta_pic_order_cnt[1] = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt[1]", s_tmp_poc.i4_delta_pic_order_cnt[1]); } } if(ps_pps->u1_redundant_pic_cnt_present_flag) { u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_REDUNDANT_PIC_CNT) return ERROR_INV_SPS_PPS_T; u1_redundant_pic_cnt = u4_temp; COPYTHECONTEXT("SH: redundant_pic_cnt", u1_redundant_pic_cnt); } /*--------------------------------------------------------------------*/ /* Check if the slice is part of new picture */ /*--------------------------------------------------------------------*/ i1_is_end_of_poc = 0; if(!ps_dec->u1_first_slice_in_stream) { i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc, &s_tmp_poc, &ps_dec->s_cur_pic_poc, ps_cur_slice, u1_pic_order_cnt_type, u1_nal_unit_type, u4_idr_pic_id, u1_field_pic_flag, u1_bottom_field_flag); /* since we support only Full frame decode, every new process should * process a new pic */ if((ps_dec->u4_first_slice_in_pic == 2) && (i1_is_end_of_poc == 0)) { /* if it is the first slice is process call ,it should be a new frame. If it is not * reject current pic and dont add it to dpb */ ps_dec->ps_dec_err_status->u1_err_flag |= REJECT_CUR_PIC; i1_is_end_of_poc = 1; } else { /* reset REJECT_CUR_PIC */ ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC; } } /*--------------------------------------------------------------------*/ /* Check for error in slice and parse the missing/corrupted MB's */ /* as skip-MB's in an inserted P-slice */ /*--------------------------------------------------------------------*/ u1_mbaff = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag); prev_slice_err = 0; if(i1_is_end_of_poc || ps_dec->u1_first_slice_in_stream) { if(u2_frame_num != ps_dec->u2_prv_frame_num && ps_dec->u1_top_bottom_decoded != 0 && ps_dec->u1_top_bottom_decoded != (TOP_FIELD_ONLY | BOT_FIELD_ONLY)) { ps_dec->u1_dangling_field = 1; if(ps_dec->u4_first_slice_in_pic) { prev_slice_err = 1; } else { prev_slice_err = 2; } if(ps_dec->u1_top_bottom_decoded ==TOP_FIELD_ONLY) ps_cur_slice->u1_bottom_field_flag = 1; else ps_cur_slice->u1_bottom_field_flag = 0; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; ps_cur_poc = &ps_dec->s_cur_pic_poc; u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL; } else if(ps_dec->u4_first_slice_in_pic == 2) { if(u2_first_mb_in_slice > 0) { prev_slice_err = 1; num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; ps_cur_poc = &s_tmp_poc; ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb; ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; } } else { if(ps_dec->u4_first_slice_in_pic) { /* if valid slice header is not decoded do start of pic processing * since in the current process call, frame num is not updated in the slice structure yet * ih264d_is_end_of_pic is checked with valid frame num of previous process call, * although i1_is_end_of_poc is set there could be more slices in the frame, * so conceal only till cur slice */ prev_slice_err = 1; num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; } else { /* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame * completely */ prev_slice_err = 2; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; } ps_cur_poc = &s_tmp_poc; } } else { if((u2_first_mb_in_slice << u1_mbaff) > ps_dec->u2_total_mbs_coded) { prev_slice_err = 2; num_mb_skipped = (u2_first_mb_in_slice << u1_mbaff) - ps_dec->u2_total_mbs_coded; ps_cur_poc = &s_tmp_poc; } else if((u2_first_mb_in_slice << u1_mbaff) < ps_dec->u2_total_mbs_coded) { return ERROR_CORRUPTED_SLICE; } } if(prev_slice_err) { ret = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, u1_is_idr_slice, u2_frame_num, ps_cur_poc, prev_slice_err); if(ps_dec->u1_dangling_field == 1) { ps_dec->u1_second_field = 1 - ps_dec->u1_second_field; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_dec->u2_prv_frame_num = u2_frame_num; ps_dec->u1_first_slice_in_stream = 0; return ERROR_DANGLING_FIELD_IN_PIC; } if(prev_slice_err == 2) { ps_dec->u1_first_slice_in_stream = 0; return ERROR_INCOMPLETE_FRAME; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { /* return if all MBs in frame are parsed*/ ps_dec->u1_first_slice_in_stream = 0; return ERROR_IN_LAST_SLICE_OF_PIC; } if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return ERROR_NEW_FRAME_EXPECTED; } if(ret != OK) return ret; i1_is_end_of_poc = 0; } if (ps_dec->u4_first_slice_in_pic == 0) ps_dec->ps_parse_cur_slice++; ps_dec->u1_slice_header_done = 0; /*--------------------------------------------------------------------*/ /* If the slice is part of new picture, do End of Pic processing. */ /*--------------------------------------------------------------------*/ if(!ps_dec->u1_first_slice_in_stream) { UWORD8 uc_mbs_exceed = 0; if(ps_dec->u2_total_mbs_coded == (ps_dec->ps_cur_sps->u2_max_mb_addr + 1)) { /*u2_total_mbs_coded is forced to u2_max_mb_addr+ 1 at the end of decode ,so ,if it is first slice in pic dont consider u2_total_mbs_coded to detect new picture */ if(ps_dec->u4_first_slice_in_pic == 0) uc_mbs_exceed = 1; } if(i1_is_end_of_poc || uc_mbs_exceed) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num); if(ret != OK) return ret; #if WIN32 H264_DEC_DEBUG_PRINT(" ------ PIC SKIPPED ------\n"); #endif return RET_LAST_SKIP; } else { ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num); if(ret != OK) return ret; } } } if(u1_field_pic_flag) { ps_dec->u2_prv_frame_num = u2_frame_num; } if(ps_cur_slice->u1_mmco_equalto5) { WORD32 i4_temp_poc; WORD32 i4_top_field_order_poc, i4_bot_field_order_poc; if(!ps_cur_slice->u1_field_pic_flag) // or a complementary field pair { i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; i4_temp_poc = MIN(i4_top_field_order_poc, i4_bot_field_order_poc); } else if(!ps_cur_slice->u1_bottom_field_flag) i4_temp_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; else i4_temp_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; ps_dec->ps_cur_pic->i4_top_field_order_cnt = i4_temp_poc - ps_dec->ps_cur_pic->i4_top_field_order_cnt; ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = i4_temp_poc - ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; ps_dec->ps_cur_pic->i4_poc = i4_temp_poc; ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; } if(ps_dec->u4_first_slice_in_pic == 2) { ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num, &ps_dec->s_prev_pic_poc, &s_tmp_poc, ps_cur_slice, ps_pps, u1_nal_ref_idc, u1_bottom_field_flag, u1_field_pic_flag, &i4_poc); if(ret != OK) return ret; /* Display seq no calculations */ if(i4_poc >= ps_dec->i4_max_poc) ps_dec->i4_max_poc = i4_poc; /* IDR Picture or POC wrap around */ if(i4_poc == 0) { ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq + ps_dec->i4_max_poc + ps_dec->u1_max_dec_frame_buffering + 1; ps_dec->i4_max_poc = 0; } } /*--------------------------------------------------------------------*/ /* Copy the values read from the bitstream to the slice header and then*/ /* If the slice is first slice in picture, then do Start of Picture */ /* processing. */ /*--------------------------------------------------------------------*/ ps_cur_slice->i4_delta_pic_order_cnt[0] = i_delta_poc[0]; ps_cur_slice->i4_delta_pic_order_cnt[1] = i_delta_poc[1]; ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; ps_cur_slice->u2_first_mb_in_slice = u2_first_mb_in_slice; ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_cur_slice->u1_slice_type = u1_slice_type; ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb; ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; if(ps_seq->u1_frame_mbs_only_flag) ps_cur_slice->u1_direct_8x8_inference_flag = ps_seq->u1_direct_8x8_inference_flag; else ps_cur_slice->u1_direct_8x8_inference_flag = 1; if(u1_slice_type == B_SLICE) { ps_cur_slice->u1_direct_spatial_mv_pred_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SH: direct_spatial_mv_pred_flag", ps_cur_slice->u1_direct_spatial_mv_pred_flag); if(ps_cur_slice->u1_direct_spatial_mv_pred_flag) ps_cur_slice->pf_decodeDirect = ih264d_decode_spatial_direct; else ps_cur_slice->pf_decodeDirect = ih264d_decode_temporal_direct; if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) ps_dec->pf_mvpred = ih264d_mvpred_nonmbaffB; } else { if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; } if(ps_dec->u4_first_slice_in_pic == 2) { if(u2_first_mb_in_slice == 0) { ret = ih264d_start_of_pic(ps_dec, i4_poc, &s_tmp_poc, u2_frame_num, ps_pps); if(ret != OK) return ret; } ps_dec->u4_output_present = 0; { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); /* If error code is non-zero then there is no buffer available for display, hence avoid format conversion */ if(0 != ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; } else ps_dec->u4_output_present = 1; } if(ps_dec->u1_separate_parse == 1) { if(ps_dec->u4_dec_thread_created == 0) { ithread_create(ps_dec->pv_dec_thread_handle, NULL, (void *)ih264d_decode_picture_thread, (void *)ps_dec); ps_dec->u4_dec_thread_created = 1; } if((ps_dec->u4_num_cores == 3) && ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) && (ps_dec->u4_bs_deblk_thread_created == 0)) { ps_dec->u4_start_recon_deblk = 0; ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, (void *)ih264d_recon_deblk_thread, (void *)ps_dec); ps_dec->u4_bs_deblk_thread_created = 1; } } } /* INITIALIZATION of fn ptrs for MC and formMbPartInfo functions */ { UWORD8 uc_nofield_nombaff; uc_nofield_nombaff = ((ps_dec->ps_cur_slice->u1_field_pic_flag == 0) && (ps_dec->ps_cur_slice->u1_mbaff_frame_flag == 0) && (u1_slice_type != B_SLICE) && (ps_dec->ps_cur_pps->u1_wted_pred_flag == 0)); /* Initialise MC and formMbPartInfo fn ptrs one time based on profile_idc */ if(uc_nofield_nombaff) { ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; } else { ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_mp; ps_dec->p_motion_compensate = ih264d_motion_compensate_mp; } } /* * Decide whether to decode the current picture or not */ { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if(ps_err->u4_frm_sei_sync == u2_frame_num) { ps_err->u1_err_flag = ACCEPT_ALL_PICS; ps_err->u4_frm_sei_sync = SYNC_FRM_DEFAULT; } ps_err->u4_cur_frm = u2_frame_num; } /* Decision for decoding if the picture is to be skipped */ { WORD32 i4_skip_b_pic, i4_skip_p_pic; i4_skip_b_pic = (ps_dec->u4_skip_frm_mask & B_SLC_BIT) && (B_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); i4_skip_p_pic = (ps_dec->u4_skip_frm_mask & P_SLC_BIT) && (P_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); /**************************************************************/ /* Skip the B picture if skip mask is set for B picture and */ /* Current B picture is a non reference B picture or there is */ /* no user for reference B picture */ /**************************************************************/ if(i4_skip_b_pic) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; /* Don't decode the picture in SKIP-B mode if that picture is B */ /* and also it is not to be used as a reference picture */ ps_dec->u1_last_pic_not_decoded = 1; return OK; } /**************************************************************/ /* Skip the P picture if skip mask is set for P picture and */ /* Current P picture is a non reference P picture or there is */ /* no user for reference P picture */ /**************************************************************/ if(i4_skip_p_pic) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; /* Don't decode the picture in SKIP-P mode if that picture is P */ /* and also it is not to be used as a reference picture */ ps_dec->u1_last_pic_not_decoded = 1; return OK; } } { UWORD16 u2_mb_x, u2_mb_y; ps_dec->i4_submb_ofst = ((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag) * SUB_BLK_SIZE) - SUB_BLK_SIZE; if(u2_first_mb_in_slice) { UWORD8 u1_mb_aff; UWORD8 u1_field_pic; UWORD16 u2_frm_wd_in_mbs; u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs; u1_mb_aff = ps_cur_slice->u1_mbaff_frame_flag; u1_field_pic = ps_cur_slice->u1_field_pic_flag; { UWORD32 x_offset; UWORD32 y_offset; UWORD32 u4_frame_stride; tfr_ctxt_t *ps_trns_addr; // = &ps_dec->s_tran_addrecon_parse; if(ps_dec->u1_separate_parse) { ps_trns_addr = &ps_dec->s_tran_addrecon_parse; } else { ps_trns_addr = &ps_dec->s_tran_addrecon; } u2_mb_x = MOD(u2_first_mb_in_slice, u2_frm_wd_in_mbs); u2_mb_y = DIV(u2_first_mb_in_slice, u2_frm_wd_in_mbs); u2_mb_y <<= u1_mb_aff; if((u2_mb_x > u2_frm_wd_in_mbs - 1) || (u2_mb_y > ps_dec->u2_frm_ht_in_mbs - 1)) { return ERROR_CORRUPTED_SLICE; } u4_frame_stride = ps_dec->u2_frm_wd_y << u1_field_pic; x_offset = u2_mb_x << 4; y_offset = (u2_mb_y * u4_frame_stride) << 4; ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1 + x_offset + y_offset; u4_frame_stride = ps_dec->u2_frm_wd_uv << u1_field_pic; x_offset >>= 1; y_offset = (u2_mb_y * u4_frame_stride) << 3; x_offset *= YUV420SP_FACTOR; ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2 + x_offset + y_offset; ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3 + x_offset + y_offset; ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; if(ps_dec->u1_separate_parse == 1) { ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + (u2_first_mb_in_slice << u1_mb_aff); } else { ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + (u2_first_mb_in_slice << u1_mb_aff); } ps_dec->u2_cur_mb_addr = (u2_first_mb_in_slice << u1_mb_aff); ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv + ((u2_first_mb_in_slice << u1_mb_aff) << 4); } } else { tfr_ctxt_t *ps_trns_addr; if(ps_dec->u1_separate_parse) { ps_trns_addr = &ps_dec->s_tran_addrecon_parse; } else { ps_trns_addr = &ps_dec->s_tran_addrecon; } u2_mb_x = 0xffff; u2_mb_y = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic; ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv; ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1; ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2; ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3; ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; } ps_dec->ps_part = ps_dec->ps_parse_part_params; ps_dec->u2_mbx = (MOD(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); ps_dec->u2_mby = (DIV(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); ps_dec->u2_mby <<= ps_cur_slice->u1_mbaff_frame_flag; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; } /* RBSP stop bit is used for CABAC decoding*/ ps_bitstrm->u4_max_ofst += ps_dec->ps_cur_pps->u1_entropy_coding_mode; ps_dec->u1_B = (u1_slice_type == B_SLICE); ps_dec->u4_next_mb_skip = 0; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->ps_cur_slice->u2_first_mb_in_slice; ps_dec->ps_parse_cur_slice->slice_type = ps_dec->ps_cur_slice->u1_slice_type; ps_dec->u4_start_recon_deblk = 1; { WORD32 num_entries; WORD32 size; UWORD8 *pu1_buf; num_entries = MAX_FRAMES; if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) && (0 == ps_dec->i4_display_delay)) { num_entries = 1; } num_entries = ((2 * num_entries) + 1); if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc) { num_entries *= 2; } size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; pu1_buf += size * ps_dec->u2_cur_slice_num; ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = ( void *)pu1_buf; } if(ps_dec->u1_separate_parse) { ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; } else { ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; } if(u1_slice_type == I_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= I_SLC_BIT; ret = ih264d_parse_islice(ps_dec, u2_first_mb_in_slice); if(ps_dec->i4_pic_type != B_SLICE && ps_dec->i4_pic_type != P_SLICE) ps_dec->i4_pic_type = I_SLICE; } else if(u1_slice_type == P_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; ret = ih264d_parse_pslice(ps_dec, u2_first_mb_in_slice); ps_dec->u1_pr_sl_type = u1_slice_type; if(ps_dec->i4_pic_type != B_SLICE) ps_dec->i4_pic_type = P_SLICE; } else if(u1_slice_type == B_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; ret = ih264d_parse_bslice(ps_dec, u2_first_mb_in_slice); ps_dec->u1_pr_sl_type = u1_slice_type; ps_dec->i4_pic_type = B_SLICE; } else return ERROR_INV_SLC_TYPE_T; if(ps_dec->u1_slice_header_done) { /* set to zero to indicate a valid slice has been decoded */ /* first slice header successfully decoded */ ps_dec->u4_first_slice_in_pic = 0; ps_dec->u1_first_slice_in_stream = 0; } if(ret != OK) return ret; ps_dec->u2_cur_slice_num++; /* storing last Mb X and MbY of the slice */ ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; /* End of Picture detection */ if(ps_dec->u2_total_mbs_coded >= (ps_seq->u2_max_mb_addr + 1)) { ps_dec->u1_pic_decode_done = 1; } { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if((ps_err->u1_err_flag & REJECT_PB_PICS) && (ps_err->u1_cur_pic_type == PIC_TYPE_I)) { ps_err->u1_err_flag = ACCEPT_ALL_PICS; } } PRINT_BIN_BIT_RATIO(ps_dec) return ret; } Commit Message: Decoder: Fix slice number increment for error clips Bug: 28673410 CWE ID: CWE-119
WORD32 ih264d_parse_decode_slice(UWORD8 u1_is_idr_slice, UWORD8 u1_nal_ref_idc, dec_struct_t *ps_dec /* Decoder parameters */ ) { dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm; dec_pic_params_t *ps_pps; dec_seq_params_t *ps_seq; dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; pocstruct_t s_tmp_poc; WORD32 i_delta_poc[2]; WORD32 i4_poc = 0; UWORD16 u2_first_mb_in_slice, u2_frame_num; UWORD8 u1_field_pic_flag, u1_redundant_pic_cnt = 0, u1_slice_type; UWORD32 u4_idr_pic_id = 0; UWORD8 u1_bottom_field_flag, u1_pic_order_cnt_type; UWORD8 u1_nal_unit_type; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; WORD8 i1_is_end_of_poc; WORD32 ret, end_of_frame; WORD32 prev_slice_err, num_mb_skipped; UWORD8 u1_mbaff; pocstruct_t *ps_cur_poc; UWORD32 u4_temp; WORD32 i_temp; UWORD32 u4_call_end_of_pic = 0; /* read FirstMbInSlice and slice type*/ ps_dec->ps_dpb_cmds->u1_dpb_commands_read_slc = 0; u2_first_mb_in_slice = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u2_first_mb_in_slice > (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)) { return ERROR_CORRUPTED_SLICE; } /*we currently don not support ASO*/ if(((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag) <= ps_dec->u2_cur_mb_addr) && (ps_dec->u2_cur_mb_addr != 0) && (ps_dec->u4_first_slice_in_pic != 0)) { return ERROR_CORRUPTED_SLICE; } COPYTHECONTEXT("SH: first_mb_in_slice",u2_first_mb_in_slice); u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > 9) return ERROR_INV_SLC_TYPE_T; u1_slice_type = u4_temp; COPYTHECONTEXT("SH: slice_type",(u1_slice_type)); ps_dec->u1_sl_typ_5_9 = 0; /* Find Out the Slice Type is 5 to 9 or not then Set the Flag */ /* u1_sl_typ_5_9 = 1 .Which tells that all the slices in the Pic*/ /* will be of same type of current */ if(u1_slice_type > 4) { u1_slice_type -= 5; ps_dec->u1_sl_typ_5_9 = 1; } { UWORD32 skip; if((ps_dec->i4_app_skip_mode == IVD_SKIP_PB) || (ps_dec->i4_dec_skip_mode == IVD_SKIP_PB)) { UWORD32 u4_bit_stream_offset = 0; if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) { skip = 0; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; } else if((I_SLICE == u1_slice_type) && (1 >= ps_dec->ps_cur_sps->u1_num_ref_frames)) { skip = 0; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; } else { skip = 1; } /* If one frame worth of data is already skipped, do not skip the next one */ if((0 == u2_first_mb_in_slice) && (1 == ps_dec->u4_prev_nal_skipped)) { skip = 0; } if(skip) { ps_dec->u4_prev_nal_skipped = 1; ps_dec->i4_dec_skip_mode = IVD_SKIP_PB; return 0; } else { /* If the previous NAL was skipped, then do not process that buffer in this call. Return to app and process it in the next call. This is necessary to handle cases where I/IDR is not complete in the current buffer and application intends to fill the remaining part of the bitstream later. This ensures we process only frame worth of data in every call */ if(1 == ps_dec->u4_prev_nal_skipped) { ps_dec->u4_return_to_app = 1; return 0; } } } } u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp & MASK_ERR_PIC_SET_ID) return ERROR_INV_SPS_PPS_T; /* discard slice if pic param is invalid */ COPYTHECONTEXT("SH: pic_parameter_set_id", u4_temp); ps_pps = &ps_dec->ps_pps[u4_temp]; if(FALSE == ps_pps->u1_is_valid) { return ERROR_INV_SPS_PPS_T; } ps_seq = ps_pps->ps_sps; if(!ps_seq) return ERROR_INV_SPS_PPS_T; if(FALSE == ps_seq->u1_is_valid) return ERROR_INV_SPS_PPS_T; /* Get the frame num */ u2_frame_num = ih264d_get_bits_h264(ps_bitstrm, ps_seq->u1_bits_in_frm_num); COPYTHECONTEXT("SH: frame_num", u2_frame_num); /* Get the field related flags */ if(!ps_seq->u1_frame_mbs_only_flag) { u1_field_pic_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: field_pic_flag", u1_field_pic_flag); u1_bottom_field_flag = 0; if(u1_field_pic_flag) { ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan_fld; u1_bottom_field_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: bottom_field_flag", u1_bottom_field_flag); } else { ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; } } else { u1_field_pic_flag = 0; u1_bottom_field_flag = 0; ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; } u1_nal_unit_type = SLICE_NAL; if(u1_is_idr_slice) { if(0 == u1_field_pic_flag) { ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY; } u1_nal_unit_type = IDR_SLICE_NAL; u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_idr_pic_id > 65535) return ERROR_INV_SPS_PPS_T; COPYTHECONTEXT("SH: ", u4_idr_pic_id); } /* read delta pic order count information*/ i_delta_poc[0] = i_delta_poc[1] = 0; s_tmp_poc.i4_pic_order_cnt_lsb = 0; s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; u1_pic_order_cnt_type = ps_seq->u1_pic_order_cnt_type; if(u1_pic_order_cnt_type == 0) { i_temp = ih264d_get_bits_h264( ps_bitstrm, ps_seq->u1_log2_max_pic_order_cnt_lsb_minus); if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb) return ERROR_INV_SPS_PPS_T; s_tmp_poc.i4_pic_order_cnt_lsb = i_temp; COPYTHECONTEXT("SH: pic_order_cnt_lsb", s_tmp_poc.i4_pic_order_cnt_lsb); if((ps_pps->u1_pic_order_present_flag == 1) && (!u1_field_pic_flag)) { s_tmp_poc.i4_delta_pic_order_cnt_bottom = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt_bottom", s_tmp_poc.i4_delta_pic_order_cnt_bottom); } } s_tmp_poc.i4_delta_pic_order_cnt[0] = 0; s_tmp_poc.i4_delta_pic_order_cnt[1] = 0; if(u1_pic_order_cnt_type == 1 && (!ps_seq->u1_delta_pic_order_always_zero_flag)) { s_tmp_poc.i4_delta_pic_order_cnt[0] = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt[0]", s_tmp_poc.i4_delta_pic_order_cnt[0]); if(ps_pps->u1_pic_order_present_flag && !u1_field_pic_flag) { s_tmp_poc.i4_delta_pic_order_cnt[1] = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt[1]", s_tmp_poc.i4_delta_pic_order_cnt[1]); } } if(ps_pps->u1_redundant_pic_cnt_present_flag) { u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_REDUNDANT_PIC_CNT) return ERROR_INV_SPS_PPS_T; u1_redundant_pic_cnt = u4_temp; COPYTHECONTEXT("SH: redundant_pic_cnt", u1_redundant_pic_cnt); } /*--------------------------------------------------------------------*/ /* Check if the slice is part of new picture */ /*--------------------------------------------------------------------*/ i1_is_end_of_poc = 0; if(!ps_dec->u1_first_slice_in_stream) { i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc, &s_tmp_poc, &ps_dec->s_cur_pic_poc, ps_cur_slice, u1_pic_order_cnt_type, u1_nal_unit_type, u4_idr_pic_id, u1_field_pic_flag, u1_bottom_field_flag); /* since we support only Full frame decode, every new process should * process a new pic */ if((ps_dec->u4_first_slice_in_pic == 2) && (i1_is_end_of_poc == 0)) { /* if it is the first slice is process call ,it should be a new frame. If it is not * reject current pic and dont add it to dpb */ ps_dec->ps_dec_err_status->u1_err_flag |= REJECT_CUR_PIC; i1_is_end_of_poc = 1; } else { /* reset REJECT_CUR_PIC */ ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC; } } /*--------------------------------------------------------------------*/ /* Check for error in slice and parse the missing/corrupted MB's */ /* as skip-MB's in an inserted P-slice */ /*--------------------------------------------------------------------*/ u1_mbaff = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag); prev_slice_err = 0; if(i1_is_end_of_poc || ps_dec->u1_first_slice_in_stream) { if(u2_frame_num != ps_dec->u2_prv_frame_num && ps_dec->u1_top_bottom_decoded != 0 && ps_dec->u1_top_bottom_decoded != (TOP_FIELD_ONLY | BOT_FIELD_ONLY)) { ps_dec->u1_dangling_field = 1; if(ps_dec->u4_first_slice_in_pic) { prev_slice_err = 1; } else { prev_slice_err = 2; } if(ps_dec->u1_top_bottom_decoded ==TOP_FIELD_ONLY) ps_cur_slice->u1_bottom_field_flag = 1; else ps_cur_slice->u1_bottom_field_flag = 0; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; ps_cur_poc = &ps_dec->s_cur_pic_poc; u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL; } else if(ps_dec->u4_first_slice_in_pic == 2) { if(u2_first_mb_in_slice > 0) { prev_slice_err = 1; num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; ps_cur_poc = &s_tmp_poc; ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb; ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; } } else { if(ps_dec->u4_first_slice_in_pic) { /* if valid slice header is not decoded do start of pic processing * since in the current process call, frame num is not updated in the slice structure yet * ih264d_is_end_of_pic is checked with valid frame num of previous process call, * although i1_is_end_of_poc is set there could be more slices in the frame, * so conceal only till cur slice */ prev_slice_err = 1; num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; } else { /* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame * completely */ prev_slice_err = 2; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; } ps_cur_poc = &s_tmp_poc; } } else { if((u2_first_mb_in_slice << u1_mbaff) > ps_dec->u2_total_mbs_coded) { prev_slice_err = 2; num_mb_skipped = (u2_first_mb_in_slice << u1_mbaff) - ps_dec->u2_total_mbs_coded; ps_cur_poc = &s_tmp_poc; } else if((u2_first_mb_in_slice << u1_mbaff) < ps_dec->u2_total_mbs_coded) { return ERROR_CORRUPTED_SLICE; } } if(prev_slice_err) { ret = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, u1_is_idr_slice, u2_frame_num, ps_cur_poc, prev_slice_err); if(ps_dec->u1_dangling_field == 1) { ps_dec->u1_second_field = 1 - ps_dec->u1_second_field; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_dec->u2_prv_frame_num = u2_frame_num; ps_dec->u1_first_slice_in_stream = 0; return ERROR_DANGLING_FIELD_IN_PIC; } if(prev_slice_err == 2) { ps_dec->u1_first_slice_in_stream = 0; return ERROR_INCOMPLETE_FRAME; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { /* return if all MBs in frame are parsed*/ ps_dec->u1_first_slice_in_stream = 0; return ERROR_IN_LAST_SLICE_OF_PIC; } if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return ERROR_NEW_FRAME_EXPECTED; } if(ret != OK) return ret; i1_is_end_of_poc = 0; } if (ps_dec->u4_first_slice_in_pic == 0) { ps_dec->ps_parse_cur_slice++; ps_dec->u2_cur_slice_num++; } ps_dec->u1_slice_header_done = 0; /*--------------------------------------------------------------------*/ /* If the slice is part of new picture, do End of Pic processing. */ /*--------------------------------------------------------------------*/ if(!ps_dec->u1_first_slice_in_stream) { UWORD8 uc_mbs_exceed = 0; if(ps_dec->u2_total_mbs_coded == (ps_dec->ps_cur_sps->u2_max_mb_addr + 1)) { /*u2_total_mbs_coded is forced to u2_max_mb_addr+ 1 at the end of decode ,so ,if it is first slice in pic dont consider u2_total_mbs_coded to detect new picture */ if(ps_dec->u4_first_slice_in_pic == 0) uc_mbs_exceed = 1; } if(i1_is_end_of_poc || uc_mbs_exceed) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num); if(ret != OK) return ret; #if WIN32 H264_DEC_DEBUG_PRINT(" ------ PIC SKIPPED ------\n"); #endif return RET_LAST_SKIP; } else { ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num); if(ret != OK) return ret; } } } if(u1_field_pic_flag) { ps_dec->u2_prv_frame_num = u2_frame_num; } if(ps_cur_slice->u1_mmco_equalto5) { WORD32 i4_temp_poc; WORD32 i4_top_field_order_poc, i4_bot_field_order_poc; if(!ps_cur_slice->u1_field_pic_flag) // or a complementary field pair { i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; i4_temp_poc = MIN(i4_top_field_order_poc, i4_bot_field_order_poc); } else if(!ps_cur_slice->u1_bottom_field_flag) i4_temp_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; else i4_temp_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; ps_dec->ps_cur_pic->i4_top_field_order_cnt = i4_temp_poc - ps_dec->ps_cur_pic->i4_top_field_order_cnt; ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = i4_temp_poc - ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; ps_dec->ps_cur_pic->i4_poc = i4_temp_poc; ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; } if(ps_dec->u4_first_slice_in_pic == 2) { ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num, &ps_dec->s_prev_pic_poc, &s_tmp_poc, ps_cur_slice, ps_pps, u1_nal_ref_idc, u1_bottom_field_flag, u1_field_pic_flag, &i4_poc); if(ret != OK) return ret; /* Display seq no calculations */ if(i4_poc >= ps_dec->i4_max_poc) ps_dec->i4_max_poc = i4_poc; /* IDR Picture or POC wrap around */ if(i4_poc == 0) { ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq + ps_dec->i4_max_poc + ps_dec->u1_max_dec_frame_buffering + 1; ps_dec->i4_max_poc = 0; } } /*--------------------------------------------------------------------*/ /* Copy the values read from the bitstream to the slice header and then*/ /* If the slice is first slice in picture, then do Start of Picture */ /* processing. */ /*--------------------------------------------------------------------*/ ps_cur_slice->i4_delta_pic_order_cnt[0] = i_delta_poc[0]; ps_cur_slice->i4_delta_pic_order_cnt[1] = i_delta_poc[1]; ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; ps_cur_slice->u2_first_mb_in_slice = u2_first_mb_in_slice; ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_cur_slice->u1_slice_type = u1_slice_type; ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb; ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; if(ps_seq->u1_frame_mbs_only_flag) ps_cur_slice->u1_direct_8x8_inference_flag = ps_seq->u1_direct_8x8_inference_flag; else ps_cur_slice->u1_direct_8x8_inference_flag = 1; if(u1_slice_type == B_SLICE) { ps_cur_slice->u1_direct_spatial_mv_pred_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SH: direct_spatial_mv_pred_flag", ps_cur_slice->u1_direct_spatial_mv_pred_flag); if(ps_cur_slice->u1_direct_spatial_mv_pred_flag) ps_cur_slice->pf_decodeDirect = ih264d_decode_spatial_direct; else ps_cur_slice->pf_decodeDirect = ih264d_decode_temporal_direct; if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) ps_dec->pf_mvpred = ih264d_mvpred_nonmbaffB; } else { if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; } if(ps_dec->u4_first_slice_in_pic == 2) { if(u2_first_mb_in_slice == 0) { ret = ih264d_start_of_pic(ps_dec, i4_poc, &s_tmp_poc, u2_frame_num, ps_pps); if(ret != OK) return ret; } ps_dec->u4_output_present = 0; { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); /* If error code is non-zero then there is no buffer available for display, hence avoid format conversion */ if(0 != ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; } else ps_dec->u4_output_present = 1; } if(ps_dec->u1_separate_parse == 1) { if(ps_dec->u4_dec_thread_created == 0) { ithread_create(ps_dec->pv_dec_thread_handle, NULL, (void *)ih264d_decode_picture_thread, (void *)ps_dec); ps_dec->u4_dec_thread_created = 1; } if((ps_dec->u4_num_cores == 3) && ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) && (ps_dec->u4_bs_deblk_thread_created == 0)) { ps_dec->u4_start_recon_deblk = 0; ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, (void *)ih264d_recon_deblk_thread, (void *)ps_dec); ps_dec->u4_bs_deblk_thread_created = 1; } } } /* INITIALIZATION of fn ptrs for MC and formMbPartInfo functions */ { UWORD8 uc_nofield_nombaff; uc_nofield_nombaff = ((ps_dec->ps_cur_slice->u1_field_pic_flag == 0) && (ps_dec->ps_cur_slice->u1_mbaff_frame_flag == 0) && (u1_slice_type != B_SLICE) && (ps_dec->ps_cur_pps->u1_wted_pred_flag == 0)); /* Initialise MC and formMbPartInfo fn ptrs one time based on profile_idc */ if(uc_nofield_nombaff) { ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; } else { ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_mp; ps_dec->p_motion_compensate = ih264d_motion_compensate_mp; } } /* * Decide whether to decode the current picture or not */ { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if(ps_err->u4_frm_sei_sync == u2_frame_num) { ps_err->u1_err_flag = ACCEPT_ALL_PICS; ps_err->u4_frm_sei_sync = SYNC_FRM_DEFAULT; } ps_err->u4_cur_frm = u2_frame_num; } /* Decision for decoding if the picture is to be skipped */ { WORD32 i4_skip_b_pic, i4_skip_p_pic; i4_skip_b_pic = (ps_dec->u4_skip_frm_mask & B_SLC_BIT) && (B_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); i4_skip_p_pic = (ps_dec->u4_skip_frm_mask & P_SLC_BIT) && (P_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); /**************************************************************/ /* Skip the B picture if skip mask is set for B picture and */ /* Current B picture is a non reference B picture or there is */ /* no user for reference B picture */ /**************************************************************/ if(i4_skip_b_pic) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; /* Don't decode the picture in SKIP-B mode if that picture is B */ /* and also it is not to be used as a reference picture */ ps_dec->u1_last_pic_not_decoded = 1; return OK; } /**************************************************************/ /* Skip the P picture if skip mask is set for P picture and */ /* Current P picture is a non reference P picture or there is */ /* no user for reference P picture */ /**************************************************************/ if(i4_skip_p_pic) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; /* Don't decode the picture in SKIP-P mode if that picture is P */ /* and also it is not to be used as a reference picture */ ps_dec->u1_last_pic_not_decoded = 1; return OK; } } { UWORD16 u2_mb_x, u2_mb_y; ps_dec->i4_submb_ofst = ((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag) * SUB_BLK_SIZE) - SUB_BLK_SIZE; if(u2_first_mb_in_slice) { UWORD8 u1_mb_aff; UWORD8 u1_field_pic; UWORD16 u2_frm_wd_in_mbs; u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs; u1_mb_aff = ps_cur_slice->u1_mbaff_frame_flag; u1_field_pic = ps_cur_slice->u1_field_pic_flag; { UWORD32 x_offset; UWORD32 y_offset; UWORD32 u4_frame_stride; tfr_ctxt_t *ps_trns_addr; // = &ps_dec->s_tran_addrecon_parse; if(ps_dec->u1_separate_parse) { ps_trns_addr = &ps_dec->s_tran_addrecon_parse; } else { ps_trns_addr = &ps_dec->s_tran_addrecon; } u2_mb_x = MOD(u2_first_mb_in_slice, u2_frm_wd_in_mbs); u2_mb_y = DIV(u2_first_mb_in_slice, u2_frm_wd_in_mbs); u2_mb_y <<= u1_mb_aff; if((u2_mb_x > u2_frm_wd_in_mbs - 1) || (u2_mb_y > ps_dec->u2_frm_ht_in_mbs - 1)) { return ERROR_CORRUPTED_SLICE; } u4_frame_stride = ps_dec->u2_frm_wd_y << u1_field_pic; x_offset = u2_mb_x << 4; y_offset = (u2_mb_y * u4_frame_stride) << 4; ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1 + x_offset + y_offset; u4_frame_stride = ps_dec->u2_frm_wd_uv << u1_field_pic; x_offset >>= 1; y_offset = (u2_mb_y * u4_frame_stride) << 3; x_offset *= YUV420SP_FACTOR; ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2 + x_offset + y_offset; ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3 + x_offset + y_offset; ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; if(ps_dec->u1_separate_parse == 1) { ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + (u2_first_mb_in_slice << u1_mb_aff); } else { ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + (u2_first_mb_in_slice << u1_mb_aff); } ps_dec->u2_cur_mb_addr = (u2_first_mb_in_slice << u1_mb_aff); ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv + ((u2_first_mb_in_slice << u1_mb_aff) << 4); } } else { tfr_ctxt_t *ps_trns_addr; if(ps_dec->u1_separate_parse) { ps_trns_addr = &ps_dec->s_tran_addrecon_parse; } else { ps_trns_addr = &ps_dec->s_tran_addrecon; } u2_mb_x = 0xffff; u2_mb_y = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic; ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv; ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1; ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2; ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3; ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; } ps_dec->ps_part = ps_dec->ps_parse_part_params; ps_dec->u2_mbx = (MOD(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); ps_dec->u2_mby = (DIV(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); ps_dec->u2_mby <<= ps_cur_slice->u1_mbaff_frame_flag; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; } /* RBSP stop bit is used for CABAC decoding*/ ps_bitstrm->u4_max_ofst += ps_dec->ps_cur_pps->u1_entropy_coding_mode; ps_dec->u1_B = (u1_slice_type == B_SLICE); ps_dec->u4_next_mb_skip = 0; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->ps_cur_slice->u2_first_mb_in_slice; ps_dec->ps_parse_cur_slice->slice_type = ps_dec->ps_cur_slice->u1_slice_type; ps_dec->u4_start_recon_deblk = 1; { WORD32 num_entries; WORD32 size; UWORD8 *pu1_buf; num_entries = MAX_FRAMES; if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) && (0 == ps_dec->i4_display_delay)) { num_entries = 1; } num_entries = ((2 * num_entries) + 1); if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc) { num_entries *= 2; } size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; pu1_buf += size * ps_dec->u2_cur_slice_num; ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = ( void *)pu1_buf; } if(ps_dec->u1_separate_parse) { ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; } else { ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; } if(u1_slice_type == I_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= I_SLC_BIT; ret = ih264d_parse_islice(ps_dec, u2_first_mb_in_slice); if(ps_dec->i4_pic_type != B_SLICE && ps_dec->i4_pic_type != P_SLICE) ps_dec->i4_pic_type = I_SLICE; } else if(u1_slice_type == P_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; ret = ih264d_parse_pslice(ps_dec, u2_first_mb_in_slice); ps_dec->u1_pr_sl_type = u1_slice_type; if(ps_dec->i4_pic_type != B_SLICE) ps_dec->i4_pic_type = P_SLICE; } else if(u1_slice_type == B_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; ret = ih264d_parse_bslice(ps_dec, u2_first_mb_in_slice); ps_dec->u1_pr_sl_type = u1_slice_type; ps_dec->i4_pic_type = B_SLICE; } else return ERROR_INV_SLC_TYPE_T; if(ps_dec->u1_slice_header_done) { /* set to zero to indicate a valid slice has been decoded */ /* first slice header successfully decoded */ ps_dec->u4_first_slice_in_pic = 0; ps_dec->u1_first_slice_in_stream = 0; } if(ret != OK) return ret; /* storing last Mb X and MbY of the slice */ ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; /* End of Picture detection */ if(ps_dec->u2_total_mbs_coded >= (ps_seq->u2_max_mb_addr + 1)) { ps_dec->u1_pic_decode_done = 1; } { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if((ps_err->u1_err_flag & REJECT_PB_PICS) && (ps_err->u1_cur_pic_type == PIC_TYPE_I)) { ps_err->u1_err_flag = ACCEPT_ALL_PICS; } } PRINT_BIN_BIT_RATIO(ps_dec) return ret; }
173,544
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DownloadRequestLimiter::TabDownloadState::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame()) return; if (status_ == ALLOW_ONE_DOWNLOAD || (status_ == PROMPT_BEFORE_DOWNLOAD && !navigation_handle->IsRendererInitiated())) { NotifyCallbacks(false); host_->Remove(this, web_contents()); } } Commit Message: Don't reset TabDownloadState on history back/forward Currently performing forward/backward on a tab will reset the TabDownloadState. Which allows javascript code to do trigger multiple downloads. This CL disables that behavior by not resetting the TabDownloadState on forward/back. It is still possible to reset the TabDownloadState through user gesture or using browser initiated download. BUG=848535 Change-Id: I7f9bf6e8fb759b4dcddf5ac0c214e8c6c9f48863 Reviewed-on: https://chromium-review.googlesource.com/1108959 Commit-Queue: Min Qin <[email protected]> Reviewed-by: Xing Liu <[email protected]> Cr-Commit-Position: refs/heads/master@{#574437} CWE ID:
void DownloadRequestLimiter::TabDownloadState::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame()) return; if (status_ == ALLOW_ONE_DOWNLOAD || (status_ == PROMPT_BEFORE_DOWNLOAD && !navigation_handle->IsRendererInitiated() && !IsNavigationRestricted(navigation_handle))) { NotifyCallbacks(false); host_->Remove(this, web_contents()); } }
173,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void processInputBuffer(client *c) { server.current_client = c; /* Keep processing while there is something in the input buffer */ while(sdslen(c->querybuf)) { /* Return if clients are paused. */ if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break; /* Immediately abort if the client is in the middle of something. */ if (c->flags & CLIENT_BLOCKED) break; /* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is * written to the client. Make sure to not let the reply grow after * this flag has been set (i.e. don't process more commands). */ if (c->flags & CLIENT_CLOSE_AFTER_REPLY) break; /* Determine request type when unknown. */ if (!c->reqtype) { if (c->querybuf[0] == '*') { c->reqtype = PROTO_REQ_MULTIBULK; } else { c->reqtype = PROTO_REQ_INLINE; } } if (c->reqtype == PROTO_REQ_INLINE) { if (processInlineBuffer(c) != C_OK) break; } else if (c->reqtype == PROTO_REQ_MULTIBULK) { if (processMultibulkBuffer(c) != C_OK) break; } else { serverPanic("Unknown request type"); } /* Multibulk processing could see a <= 0 length. */ if (c->argc == 0) { resetClient(c); } else { /* Only reset the client when the command was executed. */ if (processCommand(c) == C_OK) resetClient(c); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) break; } } server.current_client = NULL; } Commit Message: Security: Cross Protocol Scripting protection. This is an attempt at mitigating problems due to cross protocol scripting, an attack targeting services using line oriented protocols like Redis that can accept HTTP requests as valid protocol, by discarding the invalid parts and accepting the payloads sent, for example, via a POST request. For this to be effective, when we detect POST and Host: and terminate the connection asynchronously, the networking code was modified in order to never process further input. It was later verified that in a pipelined request containing a POST command, the successive commands are not executed. CWE ID: CWE-254
void processInputBuffer(client *c) { server.current_client = c; /* Keep processing while there is something in the input buffer */ while(sdslen(c->querybuf)) { /* Return if clients are paused. */ if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break; /* Immediately abort if the client is in the middle of something. */ if (c->flags & CLIENT_BLOCKED) break; /* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is * written to the client. Make sure to not let the reply grow after * this flag has been set (i.e. don't process more commands). * * The same applies for clients we want to terminate ASAP. */ if (c->flags & (CLIENT_CLOSE_AFTER_REPLY|CLIENT_CLOSE_ASAP)) break; /* Determine request type when unknown. */ if (!c->reqtype) { if (c->querybuf[0] == '*') { c->reqtype = PROTO_REQ_MULTIBULK; } else { c->reqtype = PROTO_REQ_INLINE; } } if (c->reqtype == PROTO_REQ_INLINE) { if (processInlineBuffer(c) != C_OK) break; } else if (c->reqtype == PROTO_REQ_MULTIBULK) { if (processMultibulkBuffer(c) != C_OK) break; } else { serverPanic("Unknown request type"); } /* Multibulk processing could see a <= 0 length. */ if (c->argc == 0) { resetClient(c); } else { /* Only reset the client when the command was executed. */ if (processCommand(c) == C_OK) resetClient(c); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) break; } } server.current_client = NULL; }
168,453
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int pcd_detect(void) { char id[18]; int k, unit; struct pcd_unit *cd; printk("%s: %s version %s, major %d, nice %d\n", name, name, PCD_VERSION, major, nice); par_drv = pi_register_driver(name); if (!par_drv) { pr_err("failed to register %s driver\n", name); return -1; } k = 0; if (pcd_drive_count == 0) { /* nothing spec'd - so autoprobe for 1 */ cd = pcd; if (pi_init(cd->pi, 1, -1, -1, -1, -1, -1, pcd_buffer, PI_PCD, verbose, cd->name)) { if (!pcd_probe(cd, -1, id) && cd->disk) { cd->present = 1; k++; } else pi_release(cd->pi); } } else { for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { int *conf = *drives[unit]; if (!conf[D_PRT]) continue; if (!pi_init(cd->pi, 0, conf[D_PRT], conf[D_MOD], conf[D_UNI], conf[D_PRO], conf[D_DLY], pcd_buffer, PI_PCD, verbose, cd->name)) continue; if (!pcd_probe(cd, conf[D_SLV], id) && cd->disk) { cd->present = 1; k++; } else pi_release(cd->pi); } } if (k) return 0; printk("%s: No CD-ROM drive found\n", name); for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { blk_cleanup_queue(cd->disk->queue); cd->disk->queue = NULL; blk_mq_free_tag_set(&cd->tag_set); put_disk(cd->disk); } pi_unregister_driver(par_drv); return -1; } Commit Message: paride/pcd: Fix potential NULL pointer dereference and mem leak Syzkaller report this: pcd: pcd version 1.07, major 46, nice 0 pcd0: Autoprobe failed pcd: No CD-ROM drive found kasan: CONFIG_KASAN_INLINE enabled kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN PTI CPU: 1 PID: 4525 Comm: syz-executor.0 Not tainted 5.1.0-rc3+ #8 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 RIP: 0010:pcd_init+0x95c/0x1000 [pcd] Code: c4 ab f7 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 56 a3 da f7 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 39 a3 da f7 49 8b bc 24 80 05 00 00 e8 cc b2 RSP: 0018:ffff8881e84df880 EFLAGS: 00010202 RAX: 00000000000000b0 RBX: ffffffffc155a088 RCX: ffffffffc1508935 RDX: 0000000000040000 RSI: ffffc900014f0000 RDI: 0000000000000580 RBP: dffffc0000000000 R08: ffffed103ee658b8 R09: ffffed103ee658b8 R10: 0000000000000001 R11: ffffed103ee658b7 R12: 0000000000000000 R13: ffffffffc155a778 R14: ffffffffc155a4a8 R15: 0000000000000003 FS: 00007fe71bee3700(0000) GS:ffff8881f7300000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 000055a7334441a8 CR3: 00000001e9674003 CR4: 00000000007606e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400 PKRU: 55555554 Call Trace: ? 0xffffffffc1508000 ? 0xffffffffc1508000 do_one_initcall+0xbc/0x47d init/main.c:901 do_init_module+0x1b5/0x547 kernel/module.c:3456 load_module+0x6405/0x8c10 kernel/module.c:3804 __do_sys_finit_module+0x162/0x190 kernel/module.c:3898 do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007fe71bee2c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003 RBP: 00007fe71bee2c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007fe71bee36bc R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004 Modules linked in: pcd(+) paride solos_pci atm ts_fsm rtc_mt6397 mac80211 nhc_mobility nhc_udp nhc_ipv6 nhc_hop nhc_dest nhc_fragment nhc_routing 6lowpan rtc_cros_ec memconsole intel_xhci_usb_role_switch roles rtc_wm8350 usbcore industrialio_triggered_buffer kfifo_buf industrialio asc7621 dm_era dm_persistent_data dm_bufio dm_mod tpm gnss_ubx gnss_serial serdev gnss max2165 cpufreq_dt hid_penmount hid menf21bmc_wdt rc_core n_tracesink ide_gd_mod cdns_csi2tx v4l2_fwnode videodev media pinctrl_lewisburg pinctrl_intel iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun joydev mousedev ppdev kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel aes_x86_64 crypto_simd ide_pci_generic piix input_leds cryptd glue_helper psmouse ide_core intel_agp serio_raw intel_gtt ata_generic i2c_piix4 agpgart pata_acpi parport_pc parport floppy rtc_cmos sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: bmc150_magn] Dumping ftrace buffer: (ftrace buffer empty) ---[ end trace d873691c3cd69f56 ]--- If alloc_disk fails in pcd_init_units, cd->disk will be NULL, however in pcd_detect and pcd_exit, it's not check this before free.It may result a NULL pointer dereference. Also when register_blkdev failed, blk_cleanup_queue() and blk_mq_free_tag_set() should be called to free resources. Reported-by: Hulk Robot <[email protected]> Fixes: 81b74ac68c28 ("paride/pcd: cleanup queues when detection fails") Signed-off-by: YueHaibing <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-476
static int pcd_detect(void) { char id[18]; int k, unit; struct pcd_unit *cd; printk("%s: %s version %s, major %d, nice %d\n", name, name, PCD_VERSION, major, nice); par_drv = pi_register_driver(name); if (!par_drv) { pr_err("failed to register %s driver\n", name); return -1; } k = 0; if (pcd_drive_count == 0) { /* nothing spec'd - so autoprobe for 1 */ cd = pcd; if (pi_init(cd->pi, 1, -1, -1, -1, -1, -1, pcd_buffer, PI_PCD, verbose, cd->name)) { if (!pcd_probe(cd, -1, id) && cd->disk) { cd->present = 1; k++; } else pi_release(cd->pi); } } else { for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { int *conf = *drives[unit]; if (!conf[D_PRT]) continue; if (!pi_init(cd->pi, 0, conf[D_PRT], conf[D_MOD], conf[D_UNI], conf[D_PRO], conf[D_DLY], pcd_buffer, PI_PCD, verbose, cd->name)) continue; if (!pcd_probe(cd, conf[D_SLV], id) && cd->disk) { cd->present = 1; k++; } else pi_release(cd->pi); } } if (k) return 0; printk("%s: No CD-ROM drive found\n", name); for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { if (!cd->disk) continue; blk_cleanup_queue(cd->disk->queue); cd->disk->queue = NULL; blk_mq_free_tag_set(&cd->tag_set); put_disk(cd->disk); } pi_unregister_driver(par_drv); return -1; }
169,517