project
stringclasses 633
values | commit_id
stringlengths 7
81
| target
int64 0
1
| func
stringlengths 5
484k
| cwe
stringclasses 131
values | big_vul_idx
float64 0
189k
⌀ | idx
int64 0
522k
| hash
stringlengths 34
39
| size
float64 1
24k
⌀ | message
stringlengths 0
11.5k
⌀ | dataset
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|
Chrome
|
f8f6ed59949be4451ee2f5443d8a313f102fde60
| 1 |
void DoCanonicalizeRef(const CHAR* spec,
const Component& ref,
CanonOutput* output,
Component* out_ref) {
if (ref.len < 0) {
*out_ref = Component();
return;
}
output->push_back('#');
out_ref->begin = output->length();
int end = ref.end();
for (int i = ref.begin; i < end; i++) {
if (spec[i] == 0) {
continue;
} else if (static_cast<UCHAR>(spec[i]) < 0x20) {
AppendEscapedChar(static_cast<unsigned char>(spec[i]), output);
} else if (static_cast<UCHAR>(spec[i]) < 0x80) {
output->push_back(static_cast<char>(spec[i]));
} else {
unsigned code_point;
ReadUTFChar(spec, &i, end, &code_point);
AppendUTF8Value(code_point, output);
}
}
out_ref->len = output->length() - out_ref->begin;
}
|
CWE-79
| 186,880 | 7,581 |
267438556305741570638101418192920944148
| null | null | null |
Chrome
|
fe3c71592ccc6fd6f3909215e326ffc8fe0c35ce
| 1 |
IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"ӏ > l; [кĸκ] > k; п > n; [ƅь] > b; в > b; м > m; н > h; "
"т > t; [шщ] > w; ട > s;"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
|
CWE-20
| 186,887 | 7,587 |
195566591690515387288108138542323492745
| null | null | null |
Chrome
|
a96567f02a0881561c964e5c11afe9c1af17a5f7
| 1 |
QuicErrorCode QuicStreamSequencerBuffer::OnStreamData(
QuicStreamOffset starting_offset,
QuicStringPiece data,
QuicTime timestamp,
size_t* const bytes_buffered,
std::string* error_details) {
CHECK_EQ(destruction_indicator_, 123456) << "This object has been destructed";
*bytes_buffered = 0;
QuicStreamOffset offset = starting_offset;
size_t size = data.size();
if (size == 0) {
*error_details = "Received empty stream frame without FIN.";
return QUIC_EMPTY_STREAM_FRAME_NO_FIN;
}
std::list<Gap>::iterator current_gap = gaps_.begin();
while (current_gap != gaps_.end() && current_gap->end_offset <= offset) {
++current_gap;
}
DCHECK(current_gap != gaps_.end());
if (offset < current_gap->begin_offset &&
offset + size <= current_gap->begin_offset) {
QUIC_DVLOG(1) << "Duplicated data at offset: " << offset
<< " length: " << size;
return QUIC_NO_ERROR;
}
if (offset < current_gap->begin_offset &&
offset + size > current_gap->begin_offset) {
string prefix(data.data(), data.length() < 128 ? data.length() : 128);
*error_details =
QuicStrCat("Beginning of received data overlaps with buffered data.\n",
"New frame range [", offset, ", ", offset + size,
") with first 128 bytes: ", prefix, "\n",
"Currently received frames: ", GapsDebugString(), "\n",
"Current gaps: ", ReceivedFramesDebugString());
return QUIC_OVERLAPPING_STREAM_DATA;
}
if (offset + size > current_gap->end_offset) {
string prefix(data.data(), data.length() < 128 ? data.length() : 128);
*error_details = QuicStrCat(
"End of received data overlaps with buffered data.\nNew frame range [",
offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n",
"Currently received frames: ", ReceivedFramesDebugString(), "\n",
"Current gaps: ", GapsDebugString());
return QUIC_OVERLAPPING_STREAM_DATA;
}
if (offset + size > total_bytes_read_ + max_buffer_capacity_bytes_) {
*error_details = "Received data beyond available range.";
return QUIC_INTERNAL_ERROR;
}
if (current_gap->begin_offset != starting_offset &&
current_gap->end_offset != starting_offset + data.length() &&
gaps_.size() >= kMaxNumGapsAllowed) {
*error_details = "Too many gaps created for this stream.";
return QUIC_TOO_MANY_FRAME_GAPS;
}
size_t total_written = 0;
size_t source_remaining = size;
const char* source = data.data();
while (source_remaining > 0) {
const size_t write_block_num = GetBlockIndex(offset);
const size_t write_block_offset = GetInBlockOffset(offset);
DCHECK_GT(blocks_count_, write_block_num);
size_t block_capacity = GetBlockCapacity(write_block_num);
size_t bytes_avail = block_capacity - write_block_offset;
if (offset + bytes_avail > total_bytes_read_ + max_buffer_capacity_bytes_) {
bytes_avail = total_bytes_read_ + max_buffer_capacity_bytes_ - offset;
}
if (blocks_ == nullptr) {
blocks_.reset(new BufferBlock*[blocks_count_]());
for (size_t i = 0; i < blocks_count_; ++i) {
blocks_[i] = nullptr;
}
}
if (write_block_num >= blocks_count_) {
*error_details = QuicStrCat(
"QuicStreamSequencerBuffer error: OnStreamData() exceed array bounds."
"write offset = ",
offset, " write_block_num = ", write_block_num,
" blocks_count_ = ", blocks_count_);
return QUIC_STREAM_SEQUENCER_INVALID_STATE;
}
if (blocks_ == nullptr) {
*error_details =
"QuicStreamSequencerBuffer error: OnStreamData() blocks_ is null";
return QUIC_STREAM_SEQUENCER_INVALID_STATE;
}
if (blocks_[write_block_num] == nullptr) {
blocks_[write_block_num] = new BufferBlock();
}
const size_t bytes_to_copy =
std::min<size_t>(bytes_avail, source_remaining);
char* dest = blocks_[write_block_num]->buffer + write_block_offset;
QUIC_DVLOG(1) << "Write at offset: " << offset
<< " length: " << bytes_to_copy;
if (dest == nullptr || source == nullptr) {
*error_details = QuicStrCat(
"QuicStreamSequencerBuffer error: OnStreamData()"
" dest == nullptr: ",
(dest == nullptr), " source == nullptr: ", (source == nullptr),
" Writing at offset ", offset, " Gaps: ", GapsDebugString(),
" Remaining frames: ", ReceivedFramesDebugString(),
" total_bytes_read_ = ", total_bytes_read_);
return QUIC_STREAM_SEQUENCER_INVALID_STATE;
}
memcpy(dest, source, bytes_to_copy);
source += bytes_to_copy;
source_remaining -= bytes_to_copy;
offset += bytes_to_copy;
total_written += bytes_to_copy;
}
DCHECK_GT(total_written, 0u);
*bytes_buffered = total_written;
UpdateGapList(current_gap, starting_offset, total_written);
frame_arrival_time_map_.insert(
std::make_pair(starting_offset, FrameInfo(size, timestamp)));
num_bytes_buffered_ += total_written;
return QUIC_NO_ERROR;
}
|
CWE-787
| 186,900 | 7,597 |
195459414426763194190187991709770472827
| null | null | null |
Chrome
|
11bd4bc92f3fe704631e3e6ad1dd1a4351641f7c
| 1 |
BlobStorageContext::BlobFlattener::BlobFlattener(
const BlobDataBuilder& input_builder,
BlobEntry* output_blob,
BlobStorageRegistry* registry) {
const std::string& uuid = input_builder.uuid_;
std::set<std::string> dependent_blob_uuids;
size_t num_files_with_unknown_size = 0;
size_t num_building_dependent_blobs = 0;
bool found_memory_transport = false;
bool found_file_transport = false;
base::CheckedNumeric<uint64_t> checked_total_size = 0;
base::CheckedNumeric<uint64_t> checked_total_memory_size = 0;
base::CheckedNumeric<uint64_t> checked_transport_quota_needed = 0;
base::CheckedNumeric<uint64_t> checked_copy_quota_needed = 0;
for (scoped_refptr<BlobDataItem> input_item : input_builder.items_) {
const DataElement& input_element = input_item->data_element();
DataElement::Type type = input_element.type();
uint64_t length = input_element.length();
RecordBlobItemSizeStats(input_element);
if (IsBytes(type)) {
DCHECK_NE(0 + DataElement::kUnknownSize, input_element.length());
found_memory_transport = true;
if (found_file_transport) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
contains_unpopulated_transport_items |=
(type == DataElement::TYPE_BYTES_DESCRIPTION);
checked_transport_quota_needed += length;
checked_total_size += length;
scoped_refptr<ShareableBlobDataItem> item = new ShareableBlobDataItem(
std::move(input_item), ShareableBlobDataItem::QUOTA_NEEDED);
pending_transport_items.push_back(item);
transport_items.push_back(item.get());
output_blob->AppendSharedBlobItem(std::move(item));
continue;
}
if (type == DataElement::TYPE_BLOB) {
BlobEntry* ref_entry = registry->GetEntry(input_element.blob_uuid());
if (!ref_entry || input_element.blob_uuid() == uuid) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (BlobStatusIsError(ref_entry->status())) {
status = BlobStatus::ERR_REFERENCED_BLOB_BROKEN;
return;
}
if (ref_entry->total_size() == DataElement::kUnknownSize) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (dependent_blob_uuids.find(input_element.blob_uuid()) ==
dependent_blob_uuids.end()) {
dependent_blobs.push_back(
std::make_pair(input_element.blob_uuid(), ref_entry));
dependent_blob_uuids.insert(input_element.blob_uuid());
if (BlobStatusIsPending(ref_entry->status())) {
num_building_dependent_blobs++;
}
}
length = length == DataElement::kUnknownSize ? ref_entry->total_size()
: input_element.length();
checked_total_size += length;
if (input_element.offset() == 0 && length == ref_entry->total_size()) {
for (const auto& shareable_item : ref_entry->items()) {
output_blob->AppendSharedBlobItem(shareable_item);
}
continue;
}
if (input_element.offset() + length > ref_entry->total_size()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
BlobSlice slice(*ref_entry, input_element.offset(), length);
if (!slice.copying_memory_size.IsValid() ||
!slice.total_memory_size.IsValid()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
checked_total_memory_size += slice.total_memory_size;
if (slice.first_source_item) {
copies.push_back(ItemCopyEntry(slice.first_source_item,
slice.first_item_slice_offset,
slice.dest_items.front()));
pending_copy_items.push_back(slice.dest_items.front());
}
if (slice.last_source_item) {
copies.push_back(
ItemCopyEntry(slice.last_source_item, 0, slice.dest_items.back()));
pending_copy_items.push_back(slice.dest_items.back());
}
checked_copy_quota_needed += slice.copying_memory_size;
for (auto& shareable_item : slice.dest_items) {
output_blob->AppendSharedBlobItem(std::move(shareable_item));
}
continue;
}
scoped_refptr<ShareableBlobDataItem> item;
if (BlobDataBuilder::IsFutureFileItem(input_element)) {
found_file_transport = true;
if (found_memory_transport) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
contains_unpopulated_transport_items = true;
item = new ShareableBlobDataItem(std::move(input_item),
ShareableBlobDataItem::QUOTA_NEEDED);
pending_transport_items.push_back(item);
transport_items.push_back(item.get());
checked_transport_quota_needed += length;
} else {
item = new ShareableBlobDataItem(
std::move(input_item),
ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA);
}
if (length == DataElement::kUnknownSize)
num_files_with_unknown_size++;
checked_total_size += length;
output_blob->AppendSharedBlobItem(std::move(item));
}
if (num_files_with_unknown_size > 1 && input_builder.items_.size() > 1) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (!checked_total_size.IsValid() || !checked_total_memory_size.IsValid() ||
!checked_transport_quota_needed.IsValid() ||
!checked_copy_quota_needed.IsValid()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
total_size = checked_total_size.ValueOrDie();
total_memory_size = checked_total_memory_size.ValueOrDie();
transport_quota_needed = checked_transport_quota_needed.ValueOrDie();
copy_quota_needed = checked_copy_quota_needed.ValueOrDie();
transport_quota_type = found_file_transport ? TransportQuotaType::FILE
: TransportQuotaType::MEMORY;
if (transport_quota_needed) {
status = BlobStatus::PENDING_QUOTA;
} else {
status = BlobStatus::PENDING_INTERNALS;
}
}
|
CWE-119
| 186,904 | 7,600 |
159071568910807303434133927958514713737
| null | null | null |
Chrome
|
16c719e0e275d2ee5d5c69e4962b744bcaf0fe40
| 1 |
int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) {
if (HasTextBeingDragged())
return ui::DragDropTypes::DRAG_NONE;
if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) {
GURL url;
base::string16 title;
if (data.GetURLAndTitle(
ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) {
base::string16 text(
StripJavascriptSchemas(base::UTF8ToUTF16(url.spec())));
if (model()->CanPasteAndGo(text)) {
model()->PasteAndGo(text);
return ui::DragDropTypes::DRAG_COPY;
}
}
} else if (data.HasString()) {
base::string16 text;
if (data.GetString(&text)) {
base::string16 collapsed_text(base::CollapseWhitespace(text, true));
if (model()->CanPasteAndGo(collapsed_text))
model()->PasteAndGo(collapsed_text);
return ui::DragDropTypes::DRAG_COPY;
}
}
return ui::DragDropTypes::DRAG_NONE;
}
|
CWE-79
| 186,914 | 7,609 |
116048407286939855404619577586856383346
| null | null | null |
Chrome
|
7a6484fa7b7f86ea06749bfc9d10bb67b145140b
| 1 |
void QuicClientPromisedInfo::OnPromiseHeaders(const SpdyHeaderBlock& headers) {
SpdyHeaderBlock::const_iterator it = headers.find(kHttp2MethodHeader);
DCHECK(it != headers.end());
if (!(it->second == "GET" || it->second == "HEAD")) {
QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid method "
<< it->second;
Reset(QUIC_INVALID_PROMISE_METHOD);
return;
}
if (!SpdyUtils::UrlIsValid(headers)) {
QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid URL "
<< url_;
Reset(QUIC_INVALID_PROMISE_URL);
return;
}
if (!session_->IsAuthorized(SpdyUtils::GetHostNameFromHeaderBlock(headers))) {
Reset(QUIC_UNAUTHORIZED_PROMISE_URL);
return;
}
request_headers_.reset(new SpdyHeaderBlock(headers.Clone()));
}
|
CWE-119
| 186,917 | 7,612 |
210233707268975960798029880846581145241
| null | null | null |
Chrome
|
783c28d59c4c748ef9b787d4717882c90c5b227b
| 1 |
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();
}
}
|
CWE-416
| 186,920 | 7,615 |
39757271478211368210416725460825532346
| null | null | null |
Chrome
|
7d803fd8bbb8a2f3b626851a5ce58244efa0798a
| 1 |
DOMWindow* CreateWindow(const String& url_string,
const AtomicString& frame_name,
const String& window_features_string,
LocalDOMWindow& calling_window,
LocalFrame& first_frame,
LocalFrame& opener_frame,
ExceptionState& exception_state) {
LocalFrame* active_frame = calling_window.GetFrame();
DCHECK(active_frame);
KURL completed_url = url_string.IsEmpty()
? KURL(kParsedURLString, g_empty_string)
: first_frame.GetDocument()->CompleteURL(url_string);
if (!completed_url.IsEmpty() && !completed_url.IsValid()) {
UseCounter::Count(active_frame, WebFeature::kWindowOpenWithInvalidURL);
exception_state.ThrowDOMException(
kSyntaxError, "Unable to open a window with invalid URL '" +
completed_url.GetString() + "'.\n");
return nullptr;
}
WebWindowFeatures window_features =
GetWindowFeaturesFromString(window_features_string);
FrameLoadRequest frame_request(calling_window.document(),
ResourceRequest(completed_url), frame_name);
frame_request.SetShouldSetOpener(window_features.noopener ? kNeverSetOpener
: kMaybeSetOpener);
frame_request.GetResourceRequest().SetFrameType(
WebURLRequest::kFrameTypeAuxiliary);
frame_request.GetResourceRequest().SetRequestorOrigin(
SecurityOrigin::Create(active_frame->GetDocument()->Url()));
frame_request.GetResourceRequest().SetHTTPReferrer(
SecurityPolicy::GenerateReferrer(
active_frame->GetDocument()->GetReferrerPolicy(), completed_url,
active_frame->GetDocument()->OutgoingReferrer()));
bool has_user_gesture = UserGestureIndicator::ProcessingUserGesture();
bool created;
Frame* new_frame = CreateWindowHelper(
opener_frame, *active_frame, opener_frame, frame_request, window_features,
kNavigationPolicyIgnore, created);
if (!new_frame)
return nullptr;
if (new_frame->DomWindow()->IsInsecureScriptAccess(calling_window,
completed_url))
return window_features.noopener ? nullptr : new_frame->DomWindow();
if (created) {
FrameLoadRequest request(calling_window.document(),
ResourceRequest(completed_url));
request.GetResourceRequest().SetHasUserGesture(has_user_gesture);
new_frame->Navigate(request);
} else if (!url_string.IsEmpty()) {
new_frame->Navigate(*calling_window.document(), completed_url, false,
has_user_gesture ? UserGestureStatus::kActive
: UserGestureStatus::kNone);
}
return window_features.noopener ? nullptr : new_frame->DomWindow();
}
| 186,930 | 7,623 |
4747582580787629456898536848814114316
| null | null | null |
|
Chrome
|
5788690fb1395dc672ff9b3385dbfb1180ed710a
| 1 |
void DelegatedFrameHost::ClearDelegatedFrame() {
EvictDelegatedFrame();
}
|
CWE-20
| 186,931 | 7,624 |
28748284513977894071746374597875861134
| null | null | null |
Chrome
|
1f6acd54ee3765d5c1a6f14fc31ddd4a74145314
| 1 |
bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([^\p{scx=arab}][\u064b-\u0655\u0670]|)"
R"([^\p{scx=hebr}]\u05b4)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
|
CWE-20
| 186,932 | 7,625 |
104852595640074462607346558783157441089
| null | null | null |
Chrome
|
a8ef19900d003ff7078fe4fcec8f63496b18f0dc
| 1 |
WebContents* DevToolsWindow::OpenURLFromTab(
WebContents* source,
const content::OpenURLParams& params) {
DCHECK(source == main_web_contents_);
if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) {
WebContents* inspected_web_contents = GetInspectedWebContents();
return inspected_web_contents ?
inspected_web_contents->OpenURL(params) : NULL;
}
bindings_->Reload();
return main_web_contents_;
}
|
CWE-668
| 186,937 | 7,630 |
223302603119110223754967750027064404578
| null | null | null |
Chrome
|
504e0c45030f76bffda93f0857e7595216d6e7a4
| 1 |
std::set<std::string> GetDistinctHosts(const URLPatternSet& host_patterns,
bool include_rcd,
bool exclude_file_scheme) {
typedef base::StringPairs HostVector;
HostVector hosts_best_rcd;
for (const URLPattern& pattern : host_patterns) {
if (exclude_file_scheme && pattern.scheme() == url::kFileScheme)
continue;
std::string host = pattern.host();
if (pattern.match_subdomains())
host = "*." + host;
std::string rcd;
size_t reg_len =
net::registry_controlled_domains::PermissiveGetHostRegistryLength(
host, net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
if (reg_len && reg_len != std::string::npos) {
if (include_rcd) // else leave rcd empty
rcd = host.substr(host.size() - reg_len);
host = host.substr(0, host.size() - reg_len);
}
HostVector::iterator it = hosts_best_rcd.begin();
for (; it != hosts_best_rcd.end(); ++it) {
if (it->first == host)
break;
}
if (it != hosts_best_rcd.end()) {
if (include_rcd && RcdBetterThan(rcd, it->second))
it->second = rcd;
} else { // Previously unseen host, append it.
hosts_best_rcd.push_back(std::make_pair(host, rcd));
}
}
std::set<std::string> distinct_hosts;
for (const auto& host_rcd : hosts_best_rcd)
distinct_hosts.insert(host_rcd.first + host_rcd.second);
return distinct_hosts;
}
|
CWE-20
| 186,938 | 7,631 |
127460476047306412399344920878489310118
| null | null | null |
Chrome
|
761d65ebcac0cdb730fd27b87e207201ac38e3b4
| 1 |
void ServiceWorkerPaymentInstrument::OnPaymentAppInvoked(
mojom::PaymentHandlerResponsePtr response) {
DCHECK(delegate_);
if (delegate_ != nullptr) {
delegate_->OnInstrumentDetailsReady(response->method_name,
response->stringified_details);
delegate_ = nullptr;
}
}
|
CWE-416
| 186,942 | 7,633 |
124123857466942327305934839118596059224
| null | null | null |
Chrome
|
eaf2e8bce3855d362e53034bd83f0e3aff8714e4
| 1 |
void IndexedDBDatabase::ForceClose() {
scoped_refptr<IndexedDBDatabase> protect(this);
while (!pending_requests_.empty()) {
std::unique_ptr<ConnectionRequest> request =
std::move(pending_requests_.front());
pending_requests_.pop();
request->AbortForForceClose();
}
auto it = connections_.begin();
while (it != connections_.end()) {
IndexedDBConnection* connection = *it++;
connection->ForceClose();
}
DCHECK(connections_.empty());
DCHECK(!active_request_);
}
| 186,994 | 7,678 |
322875196528899547630385748142028946879
| null | null | null |
|
Chrome
|
ee86799b2b90cd65e31a42e65fef44c58691285d
| 1 |
htmlCheckEncodingDirect(htmlParserCtxtPtr ctxt, const xmlChar *encoding) {
if ((ctxt == NULL) || (encoding == NULL) ||
(ctxt->options & HTML_PARSE_IGNORE_ENC))
return;
/* do not change encoding */
if (ctxt->input->encoding != NULL)
return;
if (encoding != NULL) {
xmlCharEncoding enc;
xmlCharEncodingHandlerPtr handler;
while ((*encoding == ' ') || (*encoding == '\t')) encoding++;
if (ctxt->input->encoding != NULL)
xmlFree((xmlChar *) ctxt->input->encoding);
ctxt->input->encoding = xmlStrdup(encoding);
enc = xmlParseCharEncoding((const char *) encoding);
/*
* registered set of known encodings
*/
if (enc != XML_CHAR_ENCODING_ERROR) {
if (((enc == XML_CHAR_ENCODING_UTF16LE) ||
(enc == XML_CHAR_ENCODING_UTF16BE) ||
(enc == XML_CHAR_ENCODING_UCS4LE) ||
(enc == XML_CHAR_ENCODING_UCS4BE)) &&
(ctxt->input->buf != NULL) &&
(ctxt->input->buf->encoder == NULL)) {
htmlParseErr(ctxt, XML_ERR_INVALID_ENCODING,
"htmlCheckEncoding: wrong encoding meta\n",
NULL, NULL);
} else {
xmlSwitchEncoding(ctxt, enc);
}
ctxt->charset = XML_CHAR_ENCODING_UTF8;
} else {
/*
* fallback for unknown encodings
*/
handler = xmlFindCharEncodingHandler((const char *) encoding);
if (handler != NULL) {
xmlSwitchToEncoding(ctxt, handler);
ctxt->charset = XML_CHAR_ENCODING_UTF8;
} else {
htmlParseErr(ctxt, XML_ERR_UNSUPPORTED_ENCODING,
"htmlCheckEncoding: unknown encoding %s\n",
encoding, NULL);
}
}
if ((ctxt->input->buf != NULL) &&
(ctxt->input->buf->encoder != NULL) &&
(ctxt->input->buf->raw != NULL) &&
(ctxt->input->buf->buffer != NULL)) {
int nbchars;
int processed;
/*
* convert as much as possible to the parser reading buffer.
*/
processed = ctxt->input->cur - ctxt->input->base;
xmlBufShrink(ctxt->input->buf->buffer, processed);
nbchars = xmlCharEncInput(ctxt->input->buf, 1);
if (nbchars < 0) {
htmlParseErr(ctxt, XML_ERR_INVALID_ENCODING,
"htmlCheckEncoding: encoder error\n",
NULL, NULL);
}
xmlBufResetInput(ctxt->input->buf->buffer, ctxt->input);
}
}
}
| 186,995 | 7,679 |
4561038195331777726498136714954938764
| null | null | null |
|
Chrome
|
37a0e90a956194a066dd31edd5b5ac5045701d31
| 1 |
ChildProcessTerminationInfo ChildProcessLauncherHelper::GetTerminationInfo(
const ChildProcessLauncherHelper::Process& process,
bool known_dead) {
ChildProcessTerminationInfo info;
if (!java_peer_avaiable_on_client_thread_)
return info;
Java_ChildProcessLauncherHelperImpl_getTerminationInfo(
AttachCurrentThread(), java_peer_, reinterpret_cast<intptr_t>(&info));
base::android::ApplicationState app_state =
base::android::ApplicationStatusListener::GetState();
bool app_foreground =
app_state == base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES ||
app_state == base::android::APPLICATION_STATE_HAS_PAUSED_ACTIVITIES;
if (app_foreground &&
(info.binding_state == base::android::ChildBindingState::MODERATE ||
info.binding_state == base::android::ChildBindingState::STRONG)) {
info.status = base::TERMINATION_STATUS_OOM_PROTECTED;
} else {
info.status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
}
return info;
}
|
CWE-664
| 186,996 | 7,680 |
333289139968551203439529930274063233703
| null | null | null |
Chrome
|
b38064dbb21aaf32151073dcb7d594b240c68f73
| 1 |
OperationID FileSystemOperationRunner::BeginOperation(
std::unique_ptr<FileSystemOperation> operation) {
OperationID id = next_operation_id_++;
operations_.emplace(id, std::move(operation));
return id;
}
|
CWE-190
| 187,010 | 7,690 |
307301560034915445955748674281488723039
| null | null | null |
Chrome
|
12348a12a8b108baedee2ddbda99948029d363ed
| 1 |
UseCounterPageLoadMetricsObserver::GetAllowedUkmFeatures() {
static base::NoDestructor<UseCounterPageLoadMetricsObserver::UkmFeatureList>
opt_in_features(std::initializer_list<WebFeature>({
WebFeature::kNavigatorVibrate,
WebFeature::kNavigatorVibrateSubFrame,
WebFeature::kTouchEventPreventedNoTouchAction,
WebFeature::kTouchEventPreventedForcedDocumentPassiveNoTouchAction,
WebFeature::kDataUriHasOctothorpe,
WebFeature::kApplicationCacheManifestSelectInsecureOrigin,
WebFeature::kApplicationCacheManifestSelectSecureOrigin,
WebFeature::kMixedContentAudio,
WebFeature::kMixedContentImage,
WebFeature::kMixedContentVideo,
WebFeature::kMixedContentPlugin,
WebFeature::kOpenerNavigationWithoutGesture,
WebFeature::kUsbRequestDevice,
WebFeature::kXMLHttpRequestSynchronous,
WebFeature::kPaymentHandler,
WebFeature::kPaymentRequestShowWithoutGesture,
WebFeature::kHTMLImports,
WebFeature::kHTMLImportsHasStyleSheets,
WebFeature::kElementCreateShadowRoot,
WebFeature::kDocumentRegisterElement,
WebFeature::kCredentialManagerCreatePublicKeyCredential,
WebFeature::kCredentialManagerGetPublicKeyCredential,
WebFeature::kCredentialManagerMakePublicKeyCredentialSuccess,
WebFeature::kCredentialManagerGetPublicKeyCredentialSuccess,
WebFeature::kV8AudioContext_Constructor,
WebFeature::kElementAttachShadow,
WebFeature::kElementAttachShadowOpen,
WebFeature::kElementAttachShadowClosed,
WebFeature::kCustomElementRegistryDefine,
WebFeature::kTextToSpeech_Speak,
WebFeature::kTextToSpeech_SpeakDisallowedByAutoplay,
WebFeature::kCSSEnvironmentVariable,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetTop,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetLeft,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetRight,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetBottom,
WebFeature::kMediaControlsDisplayCutoutGesture,
WebFeature::kPolymerV1Detected,
WebFeature::kPolymerV2Detected,
WebFeature::kFullscreenSecureOrigin,
WebFeature::kFullscreenInsecureOrigin,
WebFeature::kPrefixedVideoEnterFullscreen,
WebFeature::kPrefixedVideoExitFullscreen,
WebFeature::kPrefixedVideoEnterFullScreen,
WebFeature::kPrefixedVideoExitFullScreen,
WebFeature::kDocumentLevelPassiveDefaultEventListenerPreventedWheel,
WebFeature::kDocumentDomainBlockedCrossOriginAccess,
WebFeature::kDocumentDomainEnabledCrossOriginAccess,
WebFeature::kSuppressHistoryEntryWithoutUserGesture,
WebFeature::kCursorImageGT32x32,
WebFeature::kCursorImageLE32x32,
WebFeature::kHistoryPushState,
WebFeature::kHistoryReplaceState,
WebFeature::kCursorImageGT64x64,
WebFeature::kAdClick,
WebFeature::kUpdateWithoutShippingOptionOnShippingAddressChange,
WebFeature::kUpdateWithoutShippingOptionOnShippingOptionChange,
WebFeature::kSignedExchangeInnerResponseInMainFrame,
WebFeature::kSignedExchangeInnerResponseInSubFrame,
WebFeature::kWebShareShare,
WebFeature::kHTMLAnchorElementDownloadInSandboxWithUserGesture,
WebFeature::kHTMLAnchorElementDownloadInSandboxWithoutUserGesture,
WebFeature::kNavigationDownloadInSandboxWithUserGesture,
WebFeature::kNavigationDownloadInSandboxWithoutUserGesture,
WebFeature::kDownloadInAdFrameWithUserGesture,
WebFeature::kDownloadInAdFrameWithoutUserGesture,
WebFeature::kOpenWebDatabase,
WebFeature::kV8MediaCapabilities_DecodingInfo_Method,
}));
return *opt_in_features;
}
|
CWE-20
| 187,044 | 7,718 |
57277998242963052725697948803861988420
| null | null | null |
Chrome
|
0e3b0c22a5c596bdc24a391b3f02952c1c3e4f1b
| 1 |
void Location::SetLocation(const String& url,
LocalDOMWindow* current_window,
LocalDOMWindow* entered_window,
ExceptionState* exception_state,
SetLocationPolicy set_location_policy) {
if (!IsAttached())
return;
if (!current_window->GetFrame())
return;
Document* entered_document = entered_window->document();
if (!entered_document)
return;
KURL completed_url = entered_document->CompleteURL(url);
if (completed_url.IsNull())
return;
if (!current_window->GetFrame()->CanNavigate(*dom_window_->GetFrame(),
completed_url)) {
if (exception_state) {
exception_state->ThrowSecurityError(
"The current window does not have permission to navigate the target "
"frame to '" +
url + "'.");
}
return;
}
if (exception_state && !completed_url.IsValid()) {
exception_state->ThrowDOMException(DOMExceptionCode::kSyntaxError,
"'" + url + "' is not a valid URL.");
return;
}
if (dom_window_->IsInsecureScriptAccess(*current_window, completed_url))
return;
V8DOMActivityLogger* activity_logger =
V8DOMActivityLogger::CurrentActivityLoggerIfIsolatedWorld();
if (activity_logger) {
Vector<String> argv;
argv.push_back("LocalDOMWindow");
argv.push_back("url");
argv.push_back(entered_document->Url());
argv.push_back(completed_url);
activity_logger->LogEvent("blinkSetAttribute", argv.size(), argv.data());
}
WebFrameLoadType frame_load_type = WebFrameLoadType::kStandard;
if (set_location_policy == SetLocationPolicy::kReplaceThisFrame)
frame_load_type = WebFrameLoadType::kReplaceCurrentItem;
dom_window_->GetFrame()->ScheduleNavigation(*current_window->document(),
completed_url, frame_load_type,
UserGestureStatus::kNone);
}
|
CWE-20
| 187,045 | 7,719 |
167749381289571003674001566860372202208
| null | null | null |
Chrome
|
08965161257ab9aeef9a3548c1cd1a44525dc562
| 1 |
std::wstring GetSwitchValueFromCommandLine(const std::wstring& command_line,
const std::wstring& switch_name) {
assert(!command_line.empty());
assert(!switch_name.empty());
std::vector<std::wstring> as_array = TokenizeCommandLineToArray(command_line);
std::wstring switch_with_equal = L"--" + switch_name + L"=";
for (size_t i = 1; i < as_array.size(); ++i) {
const std::wstring& arg = as_array[i];
if (arg.compare(0, switch_with_equal.size(), switch_with_equal) == 0)
return arg.substr(switch_with_equal.size());
}
return std::wstring();
}
|
CWE-77
| 187,046 | 7,720 |
171910779797819594028763339567654682884
| null | null | null |
Chrome
|
ba9748e78ec7e9c0d594e7edf7b2c07ea2a90449
| 1 |
DOMArrayBuffer* FileReaderLoader::ArrayBufferResult() {
DCHECK_EQ(read_type_, kReadAsArrayBuffer);
if (array_buffer_result_)
return array_buffer_result_;
if (!raw_data_ || error_code_ != FileErrorCode::kOK)
return nullptr;
DOMArrayBuffer* result = DOMArrayBuffer::Create(raw_data_->ToArrayBuffer());
if (finished_loading_) {
array_buffer_result_ = result;
AdjustReportedMemoryUsageToV8(
-1 * static_cast<int64_t>(raw_data_->ByteLength()));
raw_data_.reset();
}
return result;
}
|
CWE-416
| 187,047 | 7,721 |
122522782558913257646836191491659055903
| null | null | null |
Chrome
|
fd2335678e96c34d14f4b20f0d9613dfbd1ccdb4
| 1 |
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;
}
|
CWE-310
| 187,048 | 7,722 |
56192871356368726192904480706768007859
| null | null | null |
Chrome
|
032c3339bfb454c65ce38e7eafe49a54bac83073
| 1 |
bool SVGElement::HasSVGParent() const {
return ParentOrShadowHostElement() &&
ParentOrShadowHostElement()->IsSVGElement();
}
|
CWE-704
| 187,049 | 7,723 |
228383481357535142699833327675748675928
| null | null | null |
Chrome
|
f045c704568e9cf6279b3cbccbec6d86c35f8a13
| 1 |
void FileSystemManagerImpl::CreateWriter(const GURL& file_path,
CreateWriterCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
FileSystemURL url(context_->CrackURL(file_path));
base::Optional<base::File::Error> opt_error = ValidateFileSystemURL(url);
if (opt_error) {
std::move(callback).Run(opt_error.value(), nullptr);
return;
}
if (!security_policy_->CanWriteFileSystemFile(process_id_, url)) {
std::move(callback).Run(base::File::FILE_ERROR_SECURITY, nullptr);
return;
}
blink::mojom::FileWriterPtr writer;
mojo::MakeStrongBinding(std::make_unique<storage::FileWriterImpl>(
url, context_->CreateFileSystemOperationRunner(),
blob_storage_context_->context()->AsWeakPtr()),
MakeRequest(&writer));
std::move(callback).Run(base::File::FILE_OK, std::move(writer));
}
|
CWE-189
| 187,061 | 7,734 |
220704916600868172933697275127391660900
| null | null | null |
Chrome
|
2f01a0cb03732fdb982dd42786d95736322d2241
| 1 |
bool SetExtendedFileAttribute(const char* path,
const char* name,
const char* value,
size_t value_size,
int flags) {
//// On Chrome OS, there is no component that can validate these extended
//// attributes so there is no need to set them.
base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK);
int result = setxattr(path, name, value, value_size, flags);
if (result) {
DPLOG(ERROR) << "Could not set extended attribute " << name << " on file "
<< path;
return false;
}
return true;
}
|
CWE-200
| 187,101 | 7,770 |
277230499082888650870623075308095519757
| null | null | null |
Chrome
|
18c5c5dcef9cfccff64f0c23f920ef22822271a9
| 1 |
void ChromeContentBrowserClient::OpenURL(
content::BrowserContext* browser_context,
const content::OpenURLParams& params,
const base::Callback<void(content::WebContents*)>& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
#if defined(OS_ANDROID)
ServiceTabLauncher::GetInstance()->LaunchTab(browser_context, params,
callback);
#else
NavigateParams nav_params(Profile::FromBrowserContext(browser_context),
params.url, params.transition);
nav_params.FillNavigateParamsFromOpenURLParams(params);
nav_params.user_gesture = params.user_gesture;
Navigate(&nav_params);
callback.Run(nav_params.navigated_or_inserted_contents);
#endif
}
|
CWE-264
| 187,104 | 7,773 |
16021253388225897781441435985372707271
| null | null | null |
Chrome
|
01b42e2bc2aac531b17596729ae4e5c223ae7124
| 1 |
bool Performance::PassesTimingAllowCheck(
const ResourceResponse& response,
const SecurityOrigin& initiator_security_origin,
const AtomicString& original_timing_allow_origin,
ExecutionContext* context) {
scoped_refptr<const SecurityOrigin> resource_origin =
SecurityOrigin::Create(response.Url());
if (resource_origin->IsSameSchemeHostPort(&initiator_security_origin))
return true;
const AtomicString& timing_allow_origin_string =
original_timing_allow_origin.IsEmpty()
? response.HttpHeaderField(HTTPNames::Timing_Allow_Origin)
: original_timing_allow_origin;
if (timing_allow_origin_string.IsEmpty() ||
EqualIgnoringASCIICase(timing_allow_origin_string, "null"))
return false;
if (timing_allow_origin_string == "*") {
UseCounter::Count(context, WebFeature::kStarInTimingAllowOrigin);
return true;
}
const String& security_origin = initiator_security_origin.ToString();
Vector<String> timing_allow_origins;
timing_allow_origin_string.GetString().Split(',', timing_allow_origins);
if (timing_allow_origins.size() > 1) {
UseCounter::Count(context, WebFeature::kMultipleOriginsInTimingAllowOrigin);
} else if (timing_allow_origins.size() == 1 &&
timing_allow_origin_string != "*") {
UseCounter::Count(context, WebFeature::kSingleOriginInTimingAllowOrigin);
}
for (const String& allow_origin : timing_allow_origins) {
const String allow_origin_stripped = allow_origin.StripWhiteSpace();
if (allow_origin_stripped == security_origin ||
allow_origin_stripped == "*") {
return true;
}
}
return false;
}
|
CWE-200
| 187,127 | 7,792 |
294339990149396937792434128088311611936
| null | null | null |
Chrome
|
b43de74aa37a65c608308a122098204ab9c2702f
| 1 |
void WebGLRenderingContextBase::TexImageHelperImageData(
TexImageFunctionID function_id,
GLenum target,
GLint level,
GLint internalformat,
GLint border,
GLenum format,
GLenum type,
GLsizei depth,
GLint xoffset,
GLint yoffset,
GLint zoffset,
ImageData* pixels,
const IntRect& source_image_rect,
GLint unpack_image_height) {
const char* func_name = GetTexImageFunctionName(function_id);
if (isContextLost())
return;
DCHECK(pixels);
if (pixels->data()->BufferBase()->IsNeutered()) {
SynthesizeGLError(GL_INVALID_VALUE, func_name,
"The source data has been neutered.");
return;
}
if (!ValidateTexImageBinding(func_name, function_id, target))
return;
TexImageFunctionType function_type;
if (function_id == kTexImage2D || function_id == kTexImage3D)
function_type = kTexImage;
else
function_type = kTexSubImage;
if (!ValidateTexFunc(func_name, function_type, kSourceImageData, target,
level, internalformat, pixels->width(), pixels->height(),
depth, border, format, type, xoffset, yoffset, zoffset))
return;
bool selecting_sub_rectangle = false;
if (!ValidateTexImageSubRectangle(
func_name, function_id, pixels, source_image_rect, depth,
unpack_image_height, &selecting_sub_rectangle)) {
return;
}
IntRect adjusted_source_image_rect = source_image_rect;
if (unpack_flip_y_) {
adjusted_source_image_rect.SetY(pixels->height() -
adjusted_source_image_rect.MaxY());
}
Vector<uint8_t> data;
bool need_conversion = true;
if (!unpack_flip_y_ && !unpack_premultiply_alpha_ && format == GL_RGBA &&
type == GL_UNSIGNED_BYTE && !selecting_sub_rectangle && depth == 1) {
need_conversion = false;
} else {
if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) {
type = GL_FLOAT;
}
if (!WebGLImageConversion::ExtractImageData(
pixels->data()->Data(),
WebGLImageConversion::DataFormat::kDataFormatRGBA8, pixels->Size(),
adjusted_source_image_rect, depth, unpack_image_height, format,
type, unpack_flip_y_, unpack_premultiply_alpha_, data)) {
SynthesizeGLError(GL_INVALID_VALUE, func_name, "bad image data");
return;
}
}
ScopedUnpackParametersResetRestore temporary_reset_unpack(this);
const uint8_t* bytes = need_conversion ? data.data() : pixels->data()->Data();
if (function_id == kTexImage2D) {
DCHECK_EQ(unpack_image_height, 0);
TexImage2DBase(
target, level, internalformat, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), border, format, type, bytes);
} else if (function_id == kTexSubImage2D) {
DCHECK_EQ(unpack_image_height, 0);
ContextGL()->TexSubImage2D(
target, level, xoffset, yoffset, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), format, type, bytes);
} else {
GLint upload_height = adjusted_source_image_rect.Height();
if (unpack_image_height) {
upload_height = unpack_image_height;
}
if (function_id == kTexImage3D) {
ContextGL()->TexImage3D(target, level, internalformat,
adjusted_source_image_rect.Width(), upload_height,
depth, border, format, type, bytes);
} else {
DCHECK_EQ(function_id, kTexSubImage3D);
ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset,
adjusted_source_image_rect.Width(),
upload_height, depth, format, type, bytes);
}
}
}
| 187,135 | 7,798 |
288027456984957527088021906426940281508
| null | null | null |
|
Chrome
|
4391ff2884fe15b8d609bd6d3af61aacf8ad52a1
| 1 |
void NavigationControllerImpl::Reload(ReloadType reload_type,
bool check_for_repost) {
DCHECK_NE(ReloadType::NONE, reload_type);
if (transient_entry_index_ != -1) {
NavigationEntryImpl* transient_entry = GetTransientEntry();
if (!transient_entry)
return;
LoadURL(transient_entry->GetURL(),
Referrer(),
ui::PAGE_TRANSITION_RELOAD,
transient_entry->extra_headers());
return;
}
NavigationEntryImpl* entry = nullptr;
int current_index = -1;
if (IsInitialNavigation() && pending_entry_) {
entry = pending_entry_;
current_index = pending_entry_index_;
} else {
DiscardNonCommittedEntriesInternal();
current_index = GetCurrentEntryIndex();
if (current_index != -1) {
entry = GetEntryAtIndex(current_index);
}
}
if (!entry)
return;
if (last_committed_reload_type_ != ReloadType::NONE) {
DCHECK(!last_committed_reload_time_.is_null());
base::Time now =
time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
DCHECK_GT(now, last_committed_reload_time_);
if (!last_committed_reload_time_.is_null() &&
now > last_committed_reload_time_) {
base::TimeDelta delta = now - last_committed_reload_time_;
UMA_HISTOGRAM_MEDIUM_TIMES("Navigation.Reload.ReloadToReloadDuration",
delta);
if (last_committed_reload_type_ == ReloadType::NORMAL) {
UMA_HISTOGRAM_MEDIUM_TIMES(
"Navigation.Reload.ReloadMainResourceToReloadDuration", delta);
}
}
}
entry->set_reload_type(reload_type);
if (g_check_for_repost && check_for_repost &&
entry->GetHasPostData()) {
delegate_->NotifyBeforeFormRepostWarningShow();
pending_reload_ = reload_type;
delegate_->ActivateAndShowRepostFormWarningDialog();
} else {
if (!IsInitialNavigation())
DiscardNonCommittedEntriesInternal();
SiteInstanceImpl* site_instance = entry->site_instance();
bool is_for_guests_only = site_instance && site_instance->HasProcess() &&
site_instance->GetProcess()->IsForGuestsOnly();
if (!is_for_guests_only && site_instance &&
site_instance->HasWrongProcessForURL(entry->GetURL())) {
NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry(
CreateNavigationEntry(entry->GetURL(), entry->GetReferrer(),
entry->GetTransitionType(), false,
entry->extra_headers(), browser_context_,
nullptr /* blob_url_loader_factory */)
.release());
reload_type = ReloadType::NONE;
nav_entry->set_should_replace_entry(true);
pending_entry_ = nav_entry;
DCHECK_EQ(-1, pending_entry_index_);
} else {
pending_entry_ = entry;
pending_entry_index_ = current_index;
pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
}
NavigateToPendingEntry(reload_type, nullptr /* navigation_ui_data */);
}
}
| 187,139 | 7,801 |
283272276034660245075166536565197421729
| null | null | null |
|
Chrome
|
f8bc31acf099873ebc623e92908477f2e99c17f6
| 1 |
IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭԏ] > t;"
"[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;"
"[єҽҿၔ] > e; ґ > r; [ғӻ] > f; [ҫင] > c;"
"ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;"
"[зӡ] > 3"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 187,140 | 7,802 |
311081322959935484061557991970985269225
| null | null | null |
|
Chrome
|
8ac035c31d42cedcc2a772d7765622dc9f406240
| 1 |
IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщฟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;"
"[зҙӡ] > 3"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 187,142 | 7,803 |
72414987944763466618057351112913117826
| null | null | null |
|
Chrome
|
303d78445257d1eec726c4ebadb3517cb16c8c09
| 1 |
ExtensionInstallDialogView::ExtensionInstallDialogView(
Profile* profile,
content::PageNavigator* navigator,
const ExtensionInstallPrompt::DoneCallback& done_callback,
std::unique_ptr<ExtensionInstallPrompt::Prompt> prompt)
: profile_(profile),
navigator_(navigator),
done_callback_(done_callback),
prompt_(std::move(prompt)),
container_(NULL),
scroll_view_(NULL),
handled_result_(false) {
InitView();
}
|
CWE-20
| 187,143 | 7,804 |
15427734945482777536410234481930575123
| null | null | null |
Chrome
|
c5c6320f80159dc41dffc3cfbf0298925c7dcf1b
| 1 |
ExtensionFunction::ResponseAction BluetoothSocketSendFunction::Run() {
DCHECK_CURRENTLY_ON(work_thread_id());
auto params = bluetooth_socket::Send::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params.get());
io_buffer_size_ = params->data.size();
io_buffer_ = new net::WrappedIOBuffer(params->data.data());
BluetoothApiSocket* socket = GetSocket(params->socket_id);
if (!socket)
return RespondNow(Error(kSocketNotFoundError));
socket->Send(io_buffer_,
io_buffer_size_,
base::Bind(&BluetoothSocketSendFunction::OnSuccess, this),
base::Bind(&BluetoothSocketSendFunction::OnError, this));
return did_respond() ? AlreadyResponded() : RespondLater();
}
|
CWE-416
| 187,144 | 7,805 |
71558336532325004275089306724468629221
| null | null | null |
Chrome
|
fbeba958bb83c05ec8cc54e285a4a9ca10d1b311
| 1 |
ConfirmInfoBar::ConfirmInfoBar(std::unique_ptr<ConfirmInfoBarDelegate> delegate)
: InfoBarView(std::move(delegate)) {
auto* delegate_ptr = GetDelegate();
label_ = CreateLabel(delegate_ptr->GetMessageText());
AddChildView(label_);
const auto buttons = delegate_ptr->GetButtons();
if (buttons & ConfirmInfoBarDelegate::BUTTON_OK) {
ok_button_ = CreateButton(ConfirmInfoBarDelegate::BUTTON_OK);
ok_button_->SetProminent(true);
if (delegate_ptr->OKButtonTriggersUACPrompt()) {
elevation_icon_setter_.reset(new ElevationIconSetter(
ok_button_,
base::BindOnce(&ConfirmInfoBar::Layout, base::Unretained(this))));
}
}
if (buttons & ConfirmInfoBarDelegate::BUTTON_CANCEL) {
cancel_button_ = CreateButton(ConfirmInfoBarDelegate::BUTTON_CANCEL);
if (buttons == ConfirmInfoBarDelegate::BUTTON_CANCEL)
cancel_button_->SetProminent(true);
}
link_ = CreateLink(delegate_ptr->GetLinkText(), this);
AddChildView(link_);
}
|
CWE-254
| 187,149 | 7,810 |
181759325539671609085216673583402225887
| null | null | null |
Chrome
|
a62f913109fc1566230f5963bbf69ee65274ebc8
| 1 |
void FetchManager::Loader::Start() {
if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) &&
!execution_context_->GetContentSecurityPolicy()->AllowConnectToSource(
fetch_request_data_->Url())) {
PerformNetworkError(
"Refused to connect to '" + fetch_request_data_->Url().ElidedString() +
"' because it violates the document's Content Security Policy.");
return;
}
if ((SecurityOrigin::Create(fetch_request_data_->Url())
->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) ||
(fetch_request_data_->Url().ProtocolIsData() &&
fetch_request_data_->SameOriginDataURLFlag()) ||
(fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) {
PerformSchemeFetch();
return;
}
if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) {
PerformNetworkError("Fetch API cannot load " +
fetch_request_data_->Url().GetString() +
". Request mode is \"same-origin\" but the URL\'s "
"origin is not same as the request origin " +
fetch_request_data_->Origin()->ToString() + ".");
return;
}
if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) {
fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting);
PerformSchemeFetch();
return;
}
if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI(
fetch_request_data_->Url().Protocol())) {
PerformNetworkError(
"Fetch API cannot load " + fetch_request_data_->Url().GetString() +
". URL scheme must be \"http\" or \"https\" for CORS request.");
return;
}
fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting);
PerformHTTPFetch();
}
|
CWE-200
| 187,150 | 7,811 |
57058051067850403300067361643086045776
| null | null | null |
Chrome
|
81ad563077484d112e544347da87c09dd2ba0af8
| 1 |
void DevToolsDownloadManagerDelegate::OnDownloadPathGenerated(
uint32_t download_id,
const content::DownloadTargetCallback& callback,
const base::FilePath& suggested_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
callback.Run(suggested_path,
content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")),
content::DOWNLOAD_INTERRUPT_REASON_NONE);
}
| 187,159 | 7,819 |
281806002873869670569182612323455583112
| null | null | null |
|
Chrome
|
ca1156974cbe707fd023a00ae62104528833a44e
| 1 |
void BaseAudioContext::Initialize() {
if (IsDestinationInitialized())
return;
FFTFrame::Initialize();
audio_worklet_ = AudioWorklet::Create(this);
if (destination_node_) {
destination_node_->Handler().Initialize();
listener_ = AudioListener::Create(*this);
}
}
|
CWE-416
| 187,166 | 7,826 |
142671235725804319583225065369489360121
| null | null | null |
Chrome
|
b1f87486936ca0d6d9abf4d3b9b423a9c976fd59
| 1 |
GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
const GURL& real_url) {
if (real_url.SchemeIs(kGuestScheme))
return real_url;
GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url);
url::Origin origin = url::Origin::Create(url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
url::Origin isolated_origin;
if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin))
return isolated_origin.GetURL();
if (!origin.host().empty() && origin.scheme() != url::kFileScheme) {
std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(
origin.host(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
std::string site = origin.scheme();
site += url::kStandardSchemeSeparator;
site += domain.empty() ? origin.host() : domain;
return GURL(site);
}
if (!origin.unique()) {
DCHECK(!origin.scheme().empty());
return GURL(origin.scheme() + ":");
} else if (url.has_scheme()) {
DCHECK(!url.scheme().empty());
return GURL(url.scheme() + ":");
}
DCHECK(!url.is_valid()) << url;
return GURL();
}
|
CWE-285
| 187,175 | 7,834 |
339629888976962297135466015649190208042
| null | null | null |
Chrome
|
7c3bb2970fd0890df611b1d8b345b60b1978c2d7
| 1 |
bool PlatformFontSkia::InitDefaultFont() {
if (g_default_font.Get())
return true;
bool success = false;
std::string family = kFallbackFontFamilyName;
int size_pixels = 12;
int style = Font::NORMAL;
Font::Weight weight = Font::Weight::NORMAL;
FontRenderParams params;
const SkiaFontDelegate* delegate = SkiaFontDelegate::instance();
if (delegate) {
delegate->GetDefaultFontDescription(&family, &size_pixels, &style, &weight,
¶ms);
} else if (default_font_description_) {
#if defined(OS_CHROMEOS)
FontRenderParamsQuery query;
CHECK(FontList::ParseDescription(*default_font_description_,
&query.families, &query.style,
&query.pixel_size, &query.weight))
<< "Failed to parse font description " << *default_font_description_;
params = gfx::GetFontRenderParams(query, &family);
size_pixels = query.pixel_size;
style = query.style;
weight = query.weight;
#else
NOTREACHED();
#endif
}
sk_sp<SkTypeface> typeface =
CreateSkTypeface(style & Font::ITALIC, weight, &family, &success);
if (!success)
return false;
g_default_font.Get() = new PlatformFontSkia(
std::move(typeface), family, size_pixels, style, weight, params);
return true;
}
|
CWE-862
| 187,200 | 7,855 |
66618136481925498209376654033531478930
| null | null | null |
Chrome
|
8247b125c7b6888dc1c3932e19d6d8fe5a74a460
| 1 |
bool RendererPermissionsPolicyDelegate::IsRestrictedUrl(
const GURL& document_url,
std::string* error) {
if (dispatcher_->IsExtensionActive(kWebStoreAppId)) {
if (error)
*error = errors::kCannotScriptGallery;
return true;
}
if (SearchBouncer::GetInstance()->IsNewTabPage(document_url)) {
if (error)
*error = errors::kCannotScriptNtp;
return true;
}
return false;
}
|
CWE-285
| 187,201 | 7,856 |
264227214820471756357155769417719186844
| null | null | null |
Chrome
|
a79e1bbb765af34d446e42d34cd00a312b381113
| 1 |
void OnSuggestionModelAdded(UiScene* scene,
UiBrowserInterface* browser,
Model* model,
SuggestionBinding* element_binding) {
auto icon = base::MakeUnique<VectorIcon>(100);
icon->SetDrawPhase(kPhaseForeground);
icon->SetType(kTypeOmniboxSuggestionIcon);
icon->set_hit_testable(false);
icon->SetSize(kSuggestionIconSizeDMM, kSuggestionIconSizeDMM);
BindColor(model, icon.get(), &ColorScheme::omnibox_icon,
&VectorIcon::SetColor);
VectorIcon* p_icon = icon.get();
auto icon_box = base::MakeUnique<UiElement>();
icon_box->SetDrawPhase(kPhaseNone);
icon_box->SetType(kTypeOmniboxSuggestionIconField);
icon_box->SetSize(kSuggestionIconFieldWidthDMM, kSuggestionHeightDMM);
icon_box->AddChild(std::move(icon));
auto content_text = base::MakeUnique<Text>(kSuggestionContentTextHeightDMM);
content_text->SetDrawPhase(kPhaseForeground);
content_text->SetType(kTypeOmniboxSuggestionContentText);
content_text->set_hit_testable(false);
content_text->SetTextLayoutMode(TextLayoutMode::kSingleLineFixedWidth);
content_text->SetSize(kSuggestionTextFieldWidthDMM, 0);
content_text->SetTextAlignment(UiTexture::kTextAlignmentLeft);
BindColor(model, content_text.get(), &ColorScheme::omnibox_suggestion_content,
&Text::SetColor);
Text* p_content_text = content_text.get();
auto description_text =
base::MakeUnique<Text>(kSuggestionDescriptionTextHeightDMM);
description_text->SetDrawPhase(kPhaseForeground);
description_text->SetType(kTypeOmniboxSuggestionDescriptionText);
description_text->set_hit_testable(false);
content_text->SetTextLayoutMode(TextLayoutMode::kSingleLineFixedWidth);
description_text->SetSize(kSuggestionTextFieldWidthDMM, 0);
description_text->SetTextAlignment(UiTexture::kTextAlignmentLeft);
BindColor(model, description_text.get(),
&ColorScheme::omnibox_suggestion_description, &Text::SetColor);
Text* p_description_text = description_text.get();
auto text_layout = base::MakeUnique<LinearLayout>(LinearLayout::kDown);
text_layout->SetType(kTypeOmniboxSuggestionTextLayout);
text_layout->set_hit_testable(false);
text_layout->set_margin(kSuggestionLineGapDMM);
text_layout->AddChild(std::move(content_text));
text_layout->AddChild(std::move(description_text));
auto right_margin = base::MakeUnique<UiElement>();
right_margin->SetDrawPhase(kPhaseNone);
right_margin->SetSize(kSuggestionRightMarginDMM, kSuggestionHeightDMM);
auto suggestion_layout = base::MakeUnique<LinearLayout>(LinearLayout::kRight);
suggestion_layout->SetType(kTypeOmniboxSuggestionLayout);
suggestion_layout->set_hit_testable(false);
suggestion_layout->AddChild(std::move(icon_box));
suggestion_layout->AddChild(std::move(text_layout));
suggestion_layout->AddChild(std::move(right_margin));
auto background = Create<Button>(
kNone, kPhaseForeground,
base::BindRepeating(
[](UiBrowserInterface* b, Model* m, SuggestionBinding* e) {
b->Navigate(e->model()->destination);
m->omnibox_input_active = false;
},
base::Unretained(browser), base::Unretained(model),
base::Unretained(element_binding)));
background->SetType(kTypeOmniboxSuggestionBackground);
background->set_hit_testable(true);
background->set_bubble_events(true);
background->set_bounds_contain_children(true);
background->set_hover_offset(0.0);
BindButtonColors(model, background.get(),
&ColorScheme::suggestion_button_colors,
&Button::SetButtonColors);
background->AddChild(std::move(suggestion_layout));
element_binding->bindings().push_back(
VR_BIND_FUNC(base::string16, SuggestionBinding, element_binding,
model()->content, Text, p_content_text, SetText));
element_binding->bindings().push_back(
base::MakeUnique<Binding<base::string16>>(
base::BindRepeating(
[](SuggestionBinding* m) { return m->model()->description; },
base::Unretained(element_binding)),
base::BindRepeating(
[](Text* v, const base::string16& text) {
v->SetVisibleImmediately(!text.empty());
v->set_requires_layout(!text.empty());
if (!text.empty()) {
v->SetText(text);
}
},
base::Unretained(p_description_text))));
element_binding->bindings().push_back(
VR_BIND(AutocompleteMatch::Type, SuggestionBinding, element_binding,
model()->type, VectorIcon, p_icon,
SetIcon(AutocompleteMatch::TypeToVectorIcon(value))));
element_binding->set_view(background.get());
scene->AddUiElement(kOmniboxSuggestions, std::move(background));
}
|
CWE-200
| 187,243 | 7,893 |
88426719643275924407420343886820327837
| null | null | null |
Chrome
|
87e204e0aaf7445afbd0d50af6849d857517ae70
| 1 |
PerformanceNavigationTiming::PerformanceNavigationTiming(
LocalFrame* frame,
ResourceTimingInfo* info,
TimeTicks time_origin,
const WebVector<WebServerTimingInfo>& server_timing)
: PerformanceResourceTiming(info ? info->InitialURL().GetString() : "",
"navigation",
time_origin,
server_timing),
ContextClient(frame),
resource_timing_info_(info) {
DCHECK(frame);
DCHECK(info);
}
|
CWE-200
| 187,247 | 7,897 |
278483109287912955081206774255914049114
| null | null | null |
Chrome
|
2ccbb407dccc976ae4bdbaa5ff2f777f4eb0723b
| 1 |
void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
if (!is_hidden_)
return;
TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
is_hidden_ = false;
if (new_content_rendering_timeout_ &&
new_content_rendering_timeout_->IsRunning()) {
new_content_rendering_timeout_->Stop();
ClearDisplayedGraphics();
}
SendScreenRects();
RestartHangMonitorTimeoutIfNecessary();
bool needs_repainting = true;
needs_repainting_on_restore_ = false;
Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
process_->WidgetRestored();
bool is_visible = true;
NotificationService::current()->Notify(
NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
Source<RenderWidgetHost>(this),
Details<bool>(&is_visible));
WasResized();
}
| 187,248 | 7,898 |
35750327934513957859531034336170074389
| null | null | null |
|
Chrome
|
67d9b414fa64448abc398ae9fc57c3ddf5de5998
| 1 |
scoped_refptr<Image> CSSPaintValue::GetImage(
const ImageResourceObserver& client,
const Document& document,
const ComputedStyle&,
const FloatSize& target_size) {
if (!generator_) {
generator_ = CSSPaintImageGenerator::Create(
GetName(), document, paint_image_generator_observer_);
}
if (!ParseInputArguments(document))
return nullptr;
return generator_->Paint(client, RoundedIntSize(target_size),
parsed_input_arguments_);
}
|
CWE-200
| 187,249 | 7,899 |
134061584196077552519829765151971936242
| null | null | null |
Chrome
|
46f5cfb6414c04b65cba4ec59ca992f338934fc9
| 1 |
bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
if (session->restricted() && !IsFrameHostAllowedForRestrictedSessions())
return false;
session->SetRenderer(frame_host_ ? frame_host_->GetProcess()->GetID()
: ChildProcessHost::kInvalidUniqueID,
frame_host_);
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(
base::WrapUnique(new protocol::TargetHandler(false /* browser_only */)));
session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
protocol::TracingHandler::Renderer,
frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0,
GetIOContext())));
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
if (EnsureAgent())
session->AttachToAgent(agent_ptr_);
if (sessions().size() == 1) {
if (!base::FeatureList::IsEnabled(features::kVizDisplayCompositor) &&
!base::FeatureList::IsEnabled(
features::kUseVideoCaptureApiForDevToolsSnapshots)) {
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
}
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
return true;
}
|
CWE-20
| 187,257 | 7,907 |
228237655791597527196058514901471867887
| null | null | null |
Chrome
|
1f35b6980f600ec93e167118c21959d5cbd7c5c4
| 1 |
void CredentialManagerImpl::OnProvisionalSaveComplete() {
DCHECK(form_manager_);
DCHECK(client_->IsSavingAndFillingEnabledForCurrentPage());
const autofill::PasswordForm& form = form_manager_->pending_credentials();
if (form_manager_->IsPendingCredentialsPublicSuffixMatch()) {
form_manager_->Save();
return;
}
if (!form.federation_origin.unique()) {
for (auto* match : form_manager_->form_fetcher()->GetFederatedMatches()) {
if (match->username_value == form.username_value &&
match->federation_origin.IsSameOriginWith(form.federation_origin)) {
form_manager_->Update(*match);
return;
}
}
} else if (!form_manager_->IsNewLogin()) {
form_manager_->Update(*form_manager_->preferred_match());
return;
}
client_->PromptUserToSaveOrUpdatePassword(std::move(form_manager_), false);
}
|
CWE-125
| 187,275 | 7,924 |
23707503991766113125448234075739571576
| null | null | null |
Chrome
|
7614790c80996d32a28218f4d1605b0908e9ddf6
| 1 |
ExtensionNavigationThrottle::WillStartOrRedirectRequest() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::WebContents* web_contents = navigation_handle()->GetWebContents();
ExtensionRegistry* registry =
ExtensionRegistry::Get(web_contents->GetBrowserContext());
const GURL& url = navigation_handle()->GetURL();
bool url_has_extension_scheme = url.SchemeIs(kExtensionScheme);
url::Origin target_origin = url::Origin::Create(url);
const Extension* target_extension = nullptr;
if (url_has_extension_scheme) {
target_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(url);
} else if (target_origin.scheme() == kExtensionScheme) {
DCHECK(url.SchemeIsFileSystem() || url.SchemeIsBlob());
target_extension =
registry->enabled_extensions().GetByID(target_origin.host());
} else {
return content::NavigationThrottle::PROCEED;
}
if (!target_extension) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
if (target_extension->is_hosted_app()) {
base::StringPiece resource_root_relative_path =
url.path_piece().empty() ? base::StringPiece()
: url.path_piece().substr(1);
if (!IconsInfo::GetIcons(target_extension)
.ContainsPath(resource_root_relative_path)) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
}
if (navigation_handle()->IsInMainFrame()) {
bool current_frame_is_extension_process =
!!registry->enabled_extensions().GetExtensionOrAppByURL(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL());
if (!url_has_extension_scheme && !current_frame_is_extension_process) {
if (target_origin.scheme() == kExtensionScheme &&
navigation_handle()->GetSuggestedFilename().has_value()) {
return content::NavigationThrottle::PROCEED;
}
bool has_webview_permission =
target_extension->permissions_data()->HasAPIPermission(
APIPermission::kWebView);
if (!has_webview_permission)
return content::NavigationThrottle::CANCEL;
}
guest_view::GuestViewBase* guest =
guest_view::GuestViewBase::FromWebContents(web_contents);
if (url_has_extension_scheme && guest) {
const std::string& owner_extension_id = guest->owner_host();
const Extension* owner_extension =
registry->enabled_extensions().GetByID(owner_extension_id);
std::string partition_domain;
std::string partition_id;
bool in_memory = false;
bool is_guest = WebViewGuest::GetGuestPartitionConfigForSite(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL(),
&partition_domain, &partition_id, &in_memory);
bool allowed = true;
url_request_util::AllowCrossRendererResourceLoadHelper(
is_guest, target_extension, owner_extension, partition_id, url.path(),
navigation_handle()->GetPageTransition(), &allowed);
if (!allowed)
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
content::RenderFrameHost* parent = navigation_handle()->GetParentFrame();
bool external_ancestor = false;
for (auto* ancestor = parent; ancestor; ancestor = ancestor->GetParent()) {
if (ancestor->GetLastCommittedOrigin() == target_origin)
continue;
if (url::Origin::Create(ancestor->GetLastCommittedURL()) == target_origin)
continue;
if (ancestor->GetLastCommittedURL().SchemeIs(
content::kChromeDevToolsScheme))
continue;
external_ancestor = true;
break;
}
if (external_ancestor) {
if (!url_has_extension_scheme)
return content::NavigationThrottle::CANCEL;
if (!WebAccessibleResourcesInfo::IsResourceWebAccessible(target_extension,
url.path()))
return content::NavigationThrottle::BLOCK_REQUEST;
if (target_extension->is_platform_app())
return content::NavigationThrottle::CANCEL;
const Extension* parent_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(
parent->GetSiteInstance()->GetSiteURL());
if (parent_extension && parent_extension->is_platform_app())
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
|
CWE-20
| 187,278 | 7,927 |
332886639999288613546883266655583738989
| null | null | null |
Chrome
|
c050720e317e5223bcbdcaafb816befa789ceaa9
| 1 |
bool NavigationControllerImpl::RendererDidNavigate(
RenderFrameHostImpl* rfh,
const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
LoadCommittedDetails* details,
bool is_navigation_within_page,
NavigationHandleImpl* navigation_handle) {
is_initial_navigation_ = false;
bool overriding_user_agent_changed = false;
if (GetLastCommittedEntry()) {
details->previous_url = GetLastCommittedEntry()->GetURL();
details->previous_entry_index = GetLastCommittedEntryIndex();
if (pending_entry_ &&
pending_entry_->GetIsOverridingUserAgent() !=
GetLastCommittedEntry()->GetIsOverridingUserAgent())
overriding_user_agent_changed = true;
} else {
details->previous_url = GURL();
details->previous_entry_index = -1;
}
bool was_restored = false;
DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
pending_entry_->restore_type() != RestoreType::NONE);
if (pending_entry_ && pending_entry_->restore_type() != RestoreType::NONE) {
pending_entry_->set_restore_type(RestoreType::NONE);
was_restored = true;
}
details->did_replace_entry = params.should_replace_current_entry;
details->type = ClassifyNavigation(rfh, params);
details->is_same_document = is_navigation_within_page;
if (PendingEntryMatchesHandle(navigation_handle)) {
if (pending_entry_->reload_type() != ReloadType::NONE) {
last_committed_reload_type_ = pending_entry_->reload_type();
last_committed_reload_time_ =
time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
} else if (!pending_entry_->is_renderer_initiated() ||
params.gesture == NavigationGestureUser) {
last_committed_reload_type_ = ReloadType::NONE;
last_committed_reload_time_ = base::Time();
}
}
switch (details->type) {
case NAVIGATION_TYPE_NEW_PAGE:
RendererDidNavigateToNewPage(rfh, params, details->is_same_document,
details->did_replace_entry,
navigation_handle);
break;
case NAVIGATION_TYPE_EXISTING_PAGE:
details->did_replace_entry = details->is_same_document;
RendererDidNavigateToExistingPage(rfh, params, details->is_same_document,
was_restored, navigation_handle);
break;
case NAVIGATION_TYPE_SAME_PAGE:
RendererDidNavigateToSamePage(rfh, params, navigation_handle);
break;
case NAVIGATION_TYPE_NEW_SUBFRAME:
RendererDidNavigateNewSubframe(rfh, params, details->is_same_document,
details->did_replace_entry);
break;
case NAVIGATION_TYPE_AUTO_SUBFRAME:
if (!RendererDidNavigateAutoSubframe(rfh, params)) {
NotifyEntryChanged(GetLastCommittedEntry());
return false;
}
break;
case NAVIGATION_TYPE_NAV_IGNORE:
if (pending_entry_) {
DiscardNonCommittedEntries();
delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
}
return false;
default:
NOTREACHED();
}
base::Time timestamp =
time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
DVLOG(1) << "Navigation finished at (smoothed) timestamp "
<< timestamp.ToInternalValue();
DiscardNonCommittedEntriesInternal();
DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
NavigationEntryImpl* active_entry = GetLastCommittedEntry();
active_entry->SetTimestamp(timestamp);
active_entry->SetHttpStatusCode(params.http_status_code);
FrameNavigationEntry* frame_entry =
active_entry->GetFrameEntry(rfh->frame_tree_node());
if (frame_entry) {
frame_entry->SetPageState(params.page_state);
frame_entry->set_redirect_chain(params.redirects);
}
if (!rfh->GetParent() &&
IsBlockedNavigation(navigation_handle->GetNetErrorCode())) {
DCHECK(params.url_is_unreachable);
active_entry->SetURL(GURL(url::kAboutBlankURL));
active_entry->SetVirtualURL(params.url);
if (frame_entry) {
frame_entry->SetPageState(
PageState::CreateFromURL(active_entry->GetURL()));
}
}
size_t redirect_chain_size = 0;
for (size_t i = 0; i < params.redirects.size(); ++i) {
redirect_chain_size += params.redirects[i].spec().length();
}
UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size);
active_entry->ResetForCommit(frame_entry);
if (!rfh->GetParent())
CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
active_entry->SetBindings(rfh->GetEnabledBindings());
details->entry = active_entry;
details->is_main_frame = !rfh->GetParent();
details->http_status_code = params.http_status_code;
NotifyNavigationEntryCommitted(details);
if (active_entry->GetURL().SchemeIs(url::kHttpsScheme) && !rfh->GetParent() &&
navigation_handle->GetNetErrorCode() == net::OK) {
UMA_HISTOGRAM_BOOLEAN("Navigation.SecureSchemeHasSSLStatus",
!!active_entry->GetSSL().certificate);
}
if (overriding_user_agent_changed)
delegate_->UpdateOverridingUserAgent();
int nav_entry_id = active_entry->GetUniqueID();
for (FrameTreeNode* node : delegate_->GetFrameTree()->Nodes())
node->current_frame_host()->set_nav_entry_id(nav_entry_id);
return true;
}
| 187,281 | 7,930 |
188550021980177198847004897567326628987
| null | null | null |
|
Chrome
|
75b803b1c81ed9fa5513cbff550232b4fb915e7b
| 1 |
v8::Local<v8::Value> ModuleSystem::RequireForJsInner(
v8::Local<v8::String> module_name) {
v8::EscapableHandleScope handle_scope(GetIsolate());
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Context::Scope context_scope(v8_context);
v8::Local<v8::Object> global(context()->v8_context()->Global());
v8::Local<v8::Value> modules_value;
if (!GetPrivate(global, kModulesField, &modules_value) ||
modules_value->IsUndefined()) {
Warn(GetIsolate(), "Extension view no longer exists");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Object> modules(v8::Local<v8::Object>::Cast(modules_value));
v8::Local<v8::Value> exports;
if (!GetProperty(v8_context, modules, module_name, &exports) ||
!exports->IsUndefined())
return handle_scope.Escape(exports);
exports = LoadModule(*v8::String::Utf8Value(module_name));
SetProperty(v8_context, modules, module_name, exports);
return handle_scope.Escape(exports);
}
|
CWE-284
| 187,290 | 7,938 |
271380316653586517619137075602480399783
| null | null | null |
Chrome
|
5289a5d4c98681e9a0f2d28da0c7aa35e282db57
| 1 |
void ServiceWorkerContainer::registerServiceWorkerImpl(ExecutionContext* executionContext, const KURL& rawScriptURL, const KURL& scope, PassOwnPtr<RegistrationCallbacks> callbacks)
{
if (!m_provider) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeState, "Failed to register a ServiceWorker: The document is in an invalid state."));
return;
}
RefPtr<SecurityOrigin> documentOrigin = executionContext->getSecurityOrigin();
String errorMessage;
if (!executionContext->isSecureContext(errorMessage)) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, errorMessage));
return;
}
KURL pageURL = KURL(KURL(), documentOrigin->toString());
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(pageURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the current origin ('" + documentOrigin->toString() + "') is not supported.")));
return;
}
KURL scriptURL = rawScriptURL;
scriptURL.removeFragmentIdentifier();
if (!documentOrigin->canRequest(scriptURL)) {
RefPtr<SecurityOrigin> scriptOrigin = SecurityOrigin::create(scriptURL);
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scriptURL ('" + scriptOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "').")));
return;
}
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(scriptURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the script ('" + scriptURL.getString() + "') is not supported.")));
return;
}
KURL patternURL = scope;
patternURL.removeFragmentIdentifier();
if (!documentOrigin->canRequest(patternURL)) {
RefPtr<SecurityOrigin> patternOrigin = SecurityOrigin::create(patternURL);
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scope ('" + patternOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "').")));
return;
}
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(patternURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the scope ('" + patternURL.getString() + "') is not supported.")));
return;
}
WebString webErrorMessage;
if (!m_provider->validateScopeAndScriptURL(patternURL, scriptURL, &webErrorMessage)) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeType, WebString::fromUTF8("Failed to register a ServiceWorker: " + webErrorMessage.utf8())));
return;
}
m_provider->registerServiceWorker(patternURL, scriptURL, callbacks.leakPtr());
}
|
CWE-284
| 187,307 | 7,952 |
8127412112075769177324722122161905987
| null | null | null |
Chrome
|
96dbafe288dbe2f0cc45fa3c39daf6d0c37acbab
| 1 |
xsltStylePreCompute(xsltStylesheetPtr style, xmlNodePtr inst) {
/*
* URGENT TODO: Normally inst->psvi Should never be reserved here,
* BUT: since if we include the same stylesheet from
* multiple imports, then the stylesheet will be parsed
* again. We simply must not try to compute the stylesheet again.
* TODO: Get to the point where we don't need to query the
* namespace- and local-name of the node, but can evaluate this
* using cctxt->style->inode->category;
*/
if ((inst == NULL) || (inst->type != XML_ELEMENT_NODE) ||
(inst->psvi != NULL))
return;
if (IS_XSLT_ELEM(inst)) {
xsltStylePreCompPtr cur;
if (IS_XSLT_NAME(inst, "apply-templates")) {
xsltCheckInstructionElement(style, inst);
xsltApplyTemplatesComp(style, inst);
} else if (IS_XSLT_NAME(inst, "with-param")) {
xsltCheckParentElement(style, inst, BAD_CAST "apply-templates",
BAD_CAST "call-template");
xsltWithParamComp(style, inst);
} else if (IS_XSLT_NAME(inst, "value-of")) {
xsltCheckInstructionElement(style, inst);
xsltValueOfComp(style, inst);
} else if (IS_XSLT_NAME(inst, "copy")) {
xsltCheckInstructionElement(style, inst);
xsltCopyComp(style, inst);
} else if (IS_XSLT_NAME(inst, "copy-of")) {
xsltCheckInstructionElement(style, inst);
xsltCopyOfComp(style, inst);
} else if (IS_XSLT_NAME(inst, "if")) {
xsltCheckInstructionElement(style, inst);
xsltIfComp(style, inst);
} else if (IS_XSLT_NAME(inst, "when")) {
xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL);
xsltWhenComp(style, inst);
} else if (IS_XSLT_NAME(inst, "choose")) {
xsltCheckInstructionElement(style, inst);
xsltChooseComp(style, inst);
} else if (IS_XSLT_NAME(inst, "for-each")) {
xsltCheckInstructionElement(style, inst);
xsltForEachComp(style, inst);
} else if (IS_XSLT_NAME(inst, "apply-imports")) {
xsltCheckInstructionElement(style, inst);
xsltApplyImportsComp(style, inst);
} else if (IS_XSLT_NAME(inst, "attribute")) {
xmlNodePtr parent = inst->parent;
if ((parent == NULL) || (parent->ns == NULL) ||
((parent->ns != inst->ns) &&
(!xmlStrEqual(parent->ns->href, inst->ns->href))) ||
(!xmlStrEqual(parent->name, BAD_CAST "attribute-set"))) {
xsltCheckInstructionElement(style, inst);
}
xsltAttributeComp(style, inst);
} else if (IS_XSLT_NAME(inst, "element")) {
xsltCheckInstructionElement(style, inst);
xsltElementComp(style, inst);
} else if (IS_XSLT_NAME(inst, "text")) {
xsltCheckInstructionElement(style, inst);
xsltTextComp(style, inst);
} else if (IS_XSLT_NAME(inst, "sort")) {
xsltCheckParentElement(style, inst, BAD_CAST "apply-templates",
BAD_CAST "for-each");
xsltSortComp(style, inst);
} else if (IS_XSLT_NAME(inst, "comment")) {
xsltCheckInstructionElement(style, inst);
xsltCommentComp(style, inst);
} else if (IS_XSLT_NAME(inst, "number")) {
xsltCheckInstructionElement(style, inst);
xsltNumberComp(style, inst);
} else if (IS_XSLT_NAME(inst, "processing-instruction")) {
xsltCheckInstructionElement(style, inst);
xsltProcessingInstructionComp(style, inst);
} else if (IS_XSLT_NAME(inst, "call-template")) {
xsltCheckInstructionElement(style, inst);
xsltCallTemplateComp(style, inst);
} else if (IS_XSLT_NAME(inst, "param")) {
if (xsltCheckTopLevelElement(style, inst, 0) == 0)
xsltCheckInstructionElement(style, inst);
xsltParamComp(style, inst);
} else if (IS_XSLT_NAME(inst, "variable")) {
if (xsltCheckTopLevelElement(style, inst, 0) == 0)
xsltCheckInstructionElement(style, inst);
xsltVariableComp(style, inst);
} else if (IS_XSLT_NAME(inst, "otherwise")) {
xsltCheckParentElement(style, inst, BAD_CAST "choose", NULL);
xsltCheckInstructionElement(style, inst);
return;
} else if (IS_XSLT_NAME(inst, "template")) {
xsltCheckTopLevelElement(style, inst, 1);
return;
} else if (IS_XSLT_NAME(inst, "output")) {
xsltCheckTopLevelElement(style, inst, 1);
return;
} else if (IS_XSLT_NAME(inst, "preserve-space")) {
xsltCheckTopLevelElement(style, inst, 1);
return;
} else if (IS_XSLT_NAME(inst, "strip-space")) {
xsltCheckTopLevelElement(style, inst, 1);
return;
} else if ((IS_XSLT_NAME(inst, "stylesheet")) ||
(IS_XSLT_NAME(inst, "transform"))) {
xmlNodePtr parent = inst->parent;
if ((parent == NULL) || (parent->type != XML_DOCUMENT_NODE)) {
xsltTransformError(NULL, style, inst,
"element %s only allowed only as root element\n",
inst->name);
style->errors++;
}
return;
} else if (IS_XSLT_NAME(inst, "key")) {
xsltCheckTopLevelElement(style, inst, 1);
return;
} else if (IS_XSLT_NAME(inst, "message")) {
xsltCheckInstructionElement(style, inst);
return;
} else if (IS_XSLT_NAME(inst, "attribute-set")) {
xsltCheckTopLevelElement(style, inst, 1);
return;
} else if (IS_XSLT_NAME(inst, "namespace-alias")) {
xsltCheckTopLevelElement(style, inst, 1);
return;
} else if (IS_XSLT_NAME(inst, "include")) {
xsltCheckTopLevelElement(style, inst, 1);
return;
} else if (IS_XSLT_NAME(inst, "import")) {
xsltCheckTopLevelElement(style, inst, 1);
return;
} else if (IS_XSLT_NAME(inst, "decimal-format")) {
xsltCheckTopLevelElement(style, inst, 1);
return;
} else if (IS_XSLT_NAME(inst, "fallback")) {
xsltCheckInstructionElement(style, inst);
return;
} else if (IS_XSLT_NAME(inst, "document")) {
xsltCheckInstructionElement(style, inst);
inst->psvi = (void *) xsltDocumentComp(style, inst,
(xsltTransformFunction) xsltDocumentElem);
} else {
xsltTransformError(NULL, style, inst,
"xsltStylePreCompute: unknown xsl:%s\n", inst->name);
if (style != NULL) style->warnings++;
}
cur = (xsltStylePreCompPtr) inst->psvi;
/*
* A ns-list is build for every XSLT item in the
* node-tree. This is needed for XPath expressions.
*/
if (cur != NULL) {
int i = 0;
cur->nsList = xmlGetNsList(inst->doc, inst);
if (cur->nsList != NULL) {
while (cur->nsList[i] != NULL)
i++;
}
cur->nsNr = i;
}
} else {
inst->psvi =
(void *) xsltPreComputeExtModuleElement(style, inst);
/*
* Unknown element, maybe registered at the context
* level. Mark it for later recognition.
*/
if (inst->psvi == NULL)
inst->psvi = (void *) xsltExtMarker;
}
}
|
CWE-119
| 187,340 | 7,979 |
311436744199642649246498261332323296934
| null | null | null |
Chrome
|
e3e16497d0d5639fb3257305ea369ba4ab8ba210
| 1 |
void InputConnectionImpl::CommitText(const base::string16& text,
int new_cursor_pos) {
StartStateUpdateTimer();
std::string error;
if (!ime_engine_->ClearComposition(input_context_id_, &error))
LOG(ERROR) << "ClearComposition failed: error=\"" << error << "\"";
if (IsControlChar(text)) {
SendControlKeyEvent(text);
return;
}
if (!ime_engine_->CommitText(input_context_id_,
base::UTF16ToUTF8(text).c_str(), &error))
LOG(ERROR) << "CommitText failed: error=\"" << error << "\"";
}
|
CWE-119
| 187,355 | 7,993 |
305688989729893508950319888195419784210
| null | null | null |
Chrome
|
9de81f45c73a8f9f215fc234a6adfe087b0eab74
| 1 |
PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame),
logging_state_active_(false),
was_username_autofilled_(false),
was_password_autofilled_(false),
weak_ptr_factory_(this) {
Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id()));
}
| 187,356 | 7,994 |
36861042565291050360678735538254210092
| null | null | null |
|
Android
|
e68cbc3e9e66df4231e70efa3e9c41abc12aea20
| 1 |
status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
{
const sp<ProcessState> proc(ProcessState::self());
status_t err;
const uint8_t *data = parcel->mData;
const binder_size_t *objects = parcel->mObjects;
size_t size = parcel->mObjectsSize;
int startPos = mDataPos;
int firstIndex = -1, lastIndex = -2;
if (len == 0) {
return NO_ERROR;
}
if ((offset > parcel->mDataSize)
|| (len > parcel->mDataSize)
|| (offset + len > parcel->mDataSize)) {
return BAD_VALUE;
}
for (int i = 0; i < (int) size; i++) {
size_t off = objects[i];
if ((off >= offset) && (off < offset + len)) {
if (firstIndex == -1) {
firstIndex = i;
}
lastIndex = i;
}
}
int numObjects = lastIndex - firstIndex + 1;
if ((mDataSize+len) > mDataCapacity) {
err = growData(len);
if (err != NO_ERROR) {
return err;
}
}
memcpy(mData + mDataPos, data + offset, len);
mDataPos += len;
mDataSize += len;
err = NO_ERROR;
if (numObjects > 0) {
if (mObjectsCapacity < mObjectsSize + numObjects) {
int newSize = ((mObjectsSize + numObjects)*3)/2;
binder_size_t *objects =
(binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t));
if (objects == (binder_size_t*)0) {
return NO_MEMORY;
}
mObjects = objects;
mObjectsCapacity = newSize;
}
int idx = mObjectsSize;
for (int i = firstIndex; i <= lastIndex; i++) {
size_t off = objects[i] - offset + startPos;
mObjects[idx++] = off;
mObjectsSize++;
flat_binder_object* flat
= reinterpret_cast<flat_binder_object*>(mData + off);
acquire_object(proc, *flat, this);
if (flat->type == BINDER_TYPE_FD) {
flat->handle = dup(flat->handle);
flat->cookie = 1;
mHasFds = mFdsKnown = true;
if (!mAllowFds) {
err = FDS_NOT_ALLOWED;
}
}
}
}
return err;
}
|
CWE-264
| 187,364 | 8,000 |
51133333841899130455833565204621209444
| null | null | null |
Android
|
e999f077f6ef59d20282f1e04786816a31fb8be6
| 1 |
static EAS_RESULT Parse_wave (SDLS_SYNTHESIZER_DATA *pDLSData, EAS_I32 pos, EAS_U16 waveIndex)
{
EAS_RESULT result;
EAS_U32 temp;
EAS_I32 size;
EAS_I32 endChunk;
EAS_I32 chunkPos;
EAS_I32 wsmpPos = 0;
EAS_I32 fmtPos = 0;
EAS_I32 dataPos = 0;
EAS_I32 dataSize = 0;
S_WSMP_DATA *p;
void *pSample;
S_WSMP_DATA wsmp;
/* seek to start of chunk */
chunkPos = pos + 12;
if ((result = EAS_HWFileSeek(pDLSData->hwInstData, pDLSData->fileHandle, pos)) != EAS_SUCCESS)
return result;
/* get the chunk type */
if ((result = NextChunk(pDLSData, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* make sure it is a wave chunk */
if (temp != CHUNK_WAVE)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Offset in ptbl does not point to wave chunk\n"); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* read to end of chunk */
pos = chunkPos;
endChunk = pos + size;
while (pos < endChunk)
{
chunkPos = pos;
/* get the chunk type */
if ((result = NextChunk(pDLSData, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* parse useful chunks */
switch (temp)
{
case CHUNK_WSMP:
wsmpPos = chunkPos + 8;
break;
case CHUNK_FMT:
fmtPos = chunkPos + 8;
break;
case CHUNK_DATA:
dataPos = chunkPos + 8;
dataSize = size;
break;
default:
break;
}
}
if (dataSize > MAX_DLS_WAVE_SIZE)
{
return EAS_ERROR_SOUND_LIBRARY;
}
/* for first pass, use temporary variable */
if (pDLSData->pDLS == NULL)
p = &wsmp;
else
p = &pDLSData->wsmpData[waveIndex];
/* set the defaults */
p->fineTune = 0;
p->unityNote = 60;
p->gain = 0;
p->loopStart = 0;
p->loopLength = 0;
/* must have a fmt chunk */
if (!fmtPos)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS wave chunk has no fmt chunk\n"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* must have a data chunk */
if (!dataPos)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS wave chunk has no data chunk\n"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* parse the wsmp chunk */
if (wsmpPos)
{
if ((result = Parse_wsmp(pDLSData, wsmpPos, p)) != EAS_SUCCESS)
return result;
}
/* parse the fmt chunk */
if ((result = Parse_fmt(pDLSData, fmtPos, p)) != EAS_SUCCESS)
return result;
/* calculate the size of the wavetable needed. We need only half
* the memory for 16-bit samples when in 8-bit mode, and we need
* double the memory for 8-bit samples in 16-bit mode. For
* unlooped samples, we may use ADPCM. If so, we need only 1/4
* the memory.
*
* We also need to add one for looped samples to allow for
* the first sample to be copied to the end of the loop.
*/
/* use ADPCM encode for unlooped 16-bit samples if ADPCM is enabled */
/*lint -e{506} -e{774} groundwork for future version to support 8 & 16 bit */
if (bitDepth == 8)
{
if (p->bitsPerSample == 8)
size = dataSize;
else
/*lint -e{704} use shift for performance */
size = dataSize >> 1;
if (p->loopLength)
size++;
}
else
{
if (p->bitsPerSample == 16)
size = dataSize;
else
/*lint -e{703} use shift for performance */
size = dataSize << 1;
if (p->loopLength)
size += 2;
}
/* for first pass, add size to wave pool size and return */
if (pDLSData->pDLS == NULL)
{
pDLSData->wavePoolSize += (EAS_U32) size;
return EAS_SUCCESS;
}
/* allocate memory and read in the sample data */
pSample = pDLSData->pDLS->pDLSSamples + pDLSData->wavePoolOffset;
pDLSData->pDLS->pDLSSampleOffsets[waveIndex] = pDLSData->wavePoolOffset;
pDLSData->pDLS->pDLSSampleLen[waveIndex] = (EAS_U32) size;
pDLSData->wavePoolOffset += (EAS_U32) size;
if (pDLSData->wavePoolOffset > pDLSData->wavePoolSize)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Wave pool exceeded allocation\n"); */ }
return EAS_ERROR_SOUND_LIBRARY;
}
if ((result = Parse_data(pDLSData, dataPos, dataSize, p, pSample)) != EAS_SUCCESS)
return result;
return EAS_SUCCESS;
}
|
CWE-189
| 187,378 | 8,014 |
21319537981250110024800294284209101145
| null | null | null |
Android
|
c82e31a7039a03dca7b37c65b7890ba5c1e18ced
| 1 |
status_t BnHDCP::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case HDCP_SET_OBSERVER:
{
CHECK_INTERFACE(IHDCP, data, reply);
sp<IHDCPObserver> observer =
interface_cast<IHDCPObserver>(data.readStrongBinder());
reply->writeInt32(setObserver(observer));
return OK;
}
case HDCP_INIT_ASYNC:
{
CHECK_INTERFACE(IHDCP, data, reply);
const char *host = data.readCString();
unsigned port = data.readInt32();
reply->writeInt32(initAsync(host, port));
return OK;
}
case HDCP_SHUTDOWN_ASYNC:
{
CHECK_INTERFACE(IHDCP, data, reply);
reply->writeInt32(shutdownAsync());
return OK;
}
case HDCP_GET_CAPS:
{
CHECK_INTERFACE(IHDCP, data, reply);
reply->writeInt32(getCaps());
return OK;
}
case HDCP_ENCRYPT:
{
size_t size = data.readInt32();
void *inData = malloc(2 * size);
void *outData = (uint8_t *)inData + size;
data.read(inData, size);
uint32_t streamCTR = data.readInt32();
uint64_t inputCTR;
status_t err = encrypt(inData, size, streamCTR, &inputCTR, outData);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt64(inputCTR);
reply->write(outData, size);
}
free(inData);
inData = outData = NULL;
return OK;
}
case HDCP_ENCRYPT_NATIVE:
{
CHECK_INTERFACE(IHDCP, data, reply);
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
size_t offset = data.readInt32();
size_t size = data.readInt32();
uint32_t streamCTR = data.readInt32();
void *outData = malloc(size);
uint64_t inputCTR;
status_t err = encryptNative(graphicBuffer, offset, size,
streamCTR, &inputCTR, outData);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt64(inputCTR);
reply->write(outData, size);
}
free(outData);
outData = NULL;
return OK;
}
case HDCP_DECRYPT:
{
size_t size = data.readInt32();
void *inData = malloc(2 * size);
void *outData = (uint8_t *)inData + size;
data.read(inData, size);
uint32_t streamCTR = data.readInt32();
uint64_t inputCTR = data.readInt64();
status_t err = decrypt(inData, size, streamCTR, inputCTR, outData);
reply->writeInt32(err);
if (err == OK) {
reply->write(outData, size);
}
free(inData);
inData = outData = NULL;
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
|
CWE-189
| 187,383 | 8,019 |
100821162213020152930684644090303863246
| null | null | null |
Android
|
51504928746edff6c94a1c498cf99c0a83bedaed
| 1 |
virtual ssize_t readAt(off64_t offset, void *buffer, size_t size) {
Parcel data, reply;
data.writeInterfaceToken(
IMediaHTTPConnection::getInterfaceDescriptor());
data.writeInt64(offset);
data.writeInt32(size);
status_t err = remote()->transact(READ_AT, data, &reply);
if (err != OK) {
ALOGE("remote readAt failed");
return UNKNOWN_ERROR;
}
int32_t exceptionCode = reply.readExceptionCode();
if (exceptionCode) {
return UNKNOWN_ERROR;
}
int32_t len = reply.readInt32();
if (len > 0) {
memcpy(buffer, mMemory->pointer(), len);
}
return len;
}
|
CWE-119
| 187,387 | 8,023 |
23993132887243499206409037242081950109
| null | null | null |
Android
|
2674a7218eaa3c87f2ee26d26da5b9170e10f859
| 1 |
status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) {
ALOGV("entering parseChunk %lld/%d", *offset, depth);
uint32_t hdr[2];
if (mDataSource->readAt(*offset, hdr, 8) < 8) {
return ERROR_IO;
}
uint64_t chunk_size = ntohl(hdr[0]);
uint32_t chunk_type = ntohl(hdr[1]);
off64_t data_offset = *offset + 8;
if (chunk_size == 1) {
if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) {
return ERROR_IO;
}
chunk_size = ntoh64(chunk_size);
data_offset += 8;
if (chunk_size < 16) {
return ERROR_MALFORMED;
}
} else if (chunk_size == 0) {
if (depth == 0) {
off64_t sourceSize;
if (mDataSource->getSize(&sourceSize) == OK) {
chunk_size = (sourceSize - *offset);
} else {
ALOGE("atom size is 0, and data source has no size");
return ERROR_MALFORMED;
}
} else {
*offset += 4;
return OK;
}
} else if (chunk_size < 8) {
ALOGE("invalid chunk size: %" PRIu64, chunk_size);
return ERROR_MALFORMED;
}
char chunk[5];
MakeFourCCString(chunk_type, chunk);
ALOGV("chunk: %s @ %lld, %d", chunk, *offset, depth);
#if 0
static const char kWhitespace[] = " ";
const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth];
printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size);
char buffer[256];
size_t n = chunk_size;
if (n > sizeof(buffer)) {
n = sizeof(buffer);
}
if (mDataSource->readAt(*offset, buffer, n)
< (ssize_t)n) {
return ERROR_IO;
}
hexdump(buffer, n);
#endif
PathAdder autoAdder(&mPath, chunk_type);
off64_t chunk_data_size = *offset + chunk_size - data_offset;
if (chunk_type != FOURCC('c', 'p', 'r', 't')
&& chunk_type != FOURCC('c', 'o', 'v', 'r')
&& mPath.size() == 5 && underMetaDataPath(mPath)) {
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
return OK;
}
switch(chunk_type) {
case FOURCC('m', 'o', 'o', 'v'):
case FOURCC('t', 'r', 'a', 'k'):
case FOURCC('m', 'd', 'i', 'a'):
case FOURCC('m', 'i', 'n', 'f'):
case FOURCC('d', 'i', 'n', 'f'):
case FOURCC('s', 't', 'b', 'l'):
case FOURCC('m', 'v', 'e', 'x'):
case FOURCC('m', 'o', 'o', 'f'):
case FOURCC('t', 'r', 'a', 'f'):
case FOURCC('m', 'f', 'r', 'a'):
case FOURCC('u', 'd', 't', 'a'):
case FOURCC('i', 'l', 's', 't'):
case FOURCC('s', 'i', 'n', 'f'):
case FOURCC('s', 'c', 'h', 'i'):
case FOURCC('e', 'd', 't', 's'):
{
if (chunk_type == FOURCC('s', 't', 'b', 'l')) {
ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size);
if (mDataSource->flags()
& (DataSource::kWantsPrefetching
| DataSource::kIsCachingDataSource)) {
sp<MPEG4DataSource> cachedSource =
new MPEG4DataSource(mDataSource);
if (cachedSource->setCachedRange(*offset, chunk_size) == OK) {
mDataSource = cachedSource;
}
}
mLastTrack->sampleTable = new SampleTable(mDataSource);
}
bool isTrack = false;
if (chunk_type == FOURCC('t', 'r', 'a', 'k')) {
isTrack = true;
Track *track = new Track;
track->next = NULL;
if (mLastTrack) {
mLastTrack->next = track;
} else {
mFirstTrack = track;
}
mLastTrack = track;
track->meta = new MetaData;
track->includes_expensive_metadata = false;
track->skipTrack = false;
track->timescale = 0;
track->meta->setCString(kKeyMIMEType, "application/octet-stream");
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
if (isTrack) {
if (mLastTrack->skipTrack) {
Track *cur = mFirstTrack;
if (cur == mLastTrack) {
delete cur;
mFirstTrack = mLastTrack = NULL;
} else {
while (cur && cur->next != mLastTrack) {
cur = cur->next;
}
cur->next = NULL;
delete mLastTrack;
mLastTrack = cur;
}
return OK;
}
status_t err = verifyTrack(mLastTrack);
if (err != OK) {
return err;
}
} else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) {
mInitCheck = OK;
if (!mIsDrm) {
return UNKNOWN_ERROR; // Return a dummy error.
} else {
return OK;
}
}
break;
}
case FOURCC('e', 'l', 's', 't'):
{
*offset += chunk_size;
uint8_t version;
if (mDataSource->readAt(data_offset, &version, 1) < 1) {
return ERROR_IO;
}
uint32_t entry_count;
if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) {
return ERROR_IO;
}
if (entry_count != 1) {
ALOGW("ignoring edit list with %d entries", entry_count);
} else if (mHeaderTimescale == 0) {
ALOGW("ignoring edit list because timescale is 0");
} else {
off64_t entriesoffset = data_offset + 8;
uint64_t segment_duration;
int64_t media_time;
if (version == 1) {
if (!mDataSource->getUInt64(entriesoffset, &segment_duration) ||
!mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) {
return ERROR_IO;
}
} else if (version == 0) {
uint32_t sd;
int32_t mt;
if (!mDataSource->getUInt32(entriesoffset, &sd) ||
!mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) {
return ERROR_IO;
}
segment_duration = sd;
media_time = mt;
} else {
return ERROR_IO;
}
uint64_t halfscale = mHeaderTimescale / 2;
segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale;
media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale;
int64_t duration;
int32_t samplerate;
if (!mLastTrack) {
return ERROR_MALFORMED;
}
if (mLastTrack->meta->findInt64(kKeyDuration, &duration) &&
mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) {
int64_t delay = (media_time * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderDelay, delay);
int64_t paddingus = duration - (segment_duration + media_time);
if (paddingus < 0) {
paddingus = 0;
}
int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples);
}
}
break;
}
case FOURCC('f', 'r', 'm', 'a'):
{
*offset += chunk_size;
uint32_t original_fourcc;
if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) {
return ERROR_IO;
}
original_fourcc = ntohl(original_fourcc);
ALOGV("read original format: %d", original_fourcc);
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc));
uint32_t num_channels = 0;
uint32_t sample_rate = 0;
if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) {
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
}
break;
}
case FOURCC('t', 'e', 'n', 'c'):
{
*offset += chunk_size;
if (chunk_size < 32) {
return ERROR_MALFORMED;
}
char buf[4];
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) {
return ERROR_IO;
}
uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf));
if (defaultAlgorithmId > 1) {
return ERROR_MALFORMED;
}
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) {
return ERROR_IO;
}
uint32_t defaultIVSize = ntohl(*((int32_t*)buf));
if ((defaultAlgorithmId == 0 && defaultIVSize != 0) ||
(defaultAlgorithmId != 0 && defaultIVSize == 0)) {
return ERROR_MALFORMED;
} else if (defaultIVSize != 0 &&
defaultIVSize != 8 &&
defaultIVSize != 16) {
return ERROR_MALFORMED;
}
uint8_t defaultKeyId[16];
if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) {
return ERROR_IO;
}
mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId);
mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize);
mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16);
break;
}
case FOURCC('t', 'k', 'h', 'd'):
{
*offset += chunk_size;
status_t err;
if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) {
return err;
}
break;
}
case FOURCC('p', 's', 's', 'h'):
{
*offset += chunk_size;
PsshInfo pssh;
if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) {
return ERROR_IO;
}
uint32_t psshdatalen = 0;
if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) {
return ERROR_IO;
}
pssh.datalen = ntohl(psshdatalen);
ALOGV("pssh data size: %d", pssh.datalen);
if (pssh.datalen + 20 > chunk_size) {
return ERROR_MALFORMED;
}
pssh.data = new (std::nothrow) uint8_t[pssh.datalen];
if (pssh.data == NULL) {
return ERROR_MALFORMED;
}
ALOGV("allocated pssh @ %p", pssh.data);
ssize_t requested = (ssize_t) pssh.datalen;
if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) {
return ERROR_IO;
}
mPssh.push_back(pssh);
break;
}
case FOURCC('m', 'd', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 4 || mLastTrack == NULL) {
return ERROR_MALFORMED;
}
uint8_t version;
if (mDataSource->readAt(
data_offset, &version, sizeof(version))
< (ssize_t)sizeof(version)) {
return ERROR_IO;
}
off64_t timescale_offset;
if (version == 1) {
timescale_offset = data_offset + 4 + 16;
} else if (version == 0) {
timescale_offset = data_offset + 4 + 8;
} else {
return ERROR_IO;
}
uint32_t timescale;
if (mDataSource->readAt(
timescale_offset, ×cale, sizeof(timescale))
< (ssize_t)sizeof(timescale)) {
return ERROR_IO;
}
mLastTrack->timescale = ntohl(timescale);
int64_t duration = 0;
if (version == 1) {
if (mDataSource->readAt(
timescale_offset + 4, &duration, sizeof(duration))
< (ssize_t)sizeof(duration)) {
return ERROR_IO;
}
if (duration != -1) {
duration = ntoh64(duration);
}
} else {
uint32_t duration32;
if (mDataSource->readAt(
timescale_offset + 4, &duration32, sizeof(duration32))
< (ssize_t)sizeof(duration32)) {
return ERROR_IO;
}
if (duration32 != 0xffffffff) {
duration = ntohl(duration32);
}
}
if (duration != 0) {
mLastTrack->meta->setInt64(
kKeyDuration, (duration * 1000000) / mLastTrack->timescale);
}
uint8_t lang[2];
off64_t lang_offset;
if (version == 1) {
lang_offset = timescale_offset + 4 + 8;
} else if (version == 0) {
lang_offset = timescale_offset + 4 + 4;
} else {
return ERROR_IO;
}
if (mDataSource->readAt(lang_offset, &lang, sizeof(lang))
< (ssize_t)sizeof(lang)) {
return ERROR_IO;
}
char lang_code[4];
lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60;
lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60;
lang_code[2] = (lang[1] & 0x1f) + 0x60;
lang_code[3] = '\0';
mLastTrack->meta->setCString(
kKeyMediaLanguage, lang_code);
break;
}
case FOURCC('s', 't', 's', 'd'):
{
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t buffer[8];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 8) < 8) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
uint32_t entry_count = U32_AT(&buffer[4]);
if (entry_count > 1) {
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) &&
strcasecmp(mime, "application/octet-stream")) {
mLastTrack->skipTrack = true;
*offset += chunk_size;
break;
}
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + 8;
for (uint32_t i = 0; i < entry_count; ++i) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'a'):
case FOURCC('e', 'n', 'c', 'a'):
case FOURCC('s', 'a', 'm', 'r'):
case FOURCC('s', 'a', 'w', 'b'):
{
uint8_t buffer[8 + 20];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index = U16_AT(&buffer[6]);
uint32_t num_channels = U16_AT(&buffer[16]);
uint16_t sample_size = U16_AT(&buffer[18]);
uint32_t sample_rate = U32_AT(&buffer[24]) >> 16;
if (chunk_type != FOURCC('e', 'n', 'c', 'a')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate);
}
ALOGV("*** coding='%s' %d channels, size %d, rate %d\n",
chunk, num_channels, sample_size, sample_rate);
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'v'):
case FOURCC('e', 'n', 'c', 'v'):
case FOURCC('s', '2', '6', '3'):
case FOURCC('H', '2', '6', '3'):
case FOURCC('h', '2', '6', '3'):
case FOURCC('a', 'v', 'c', '1'):
case FOURCC('h', 'v', 'c', '1'):
case FOURCC('h', 'e', 'v', '1'):
{
mHasVideo = true;
uint8_t buffer[78];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index = U16_AT(&buffer[6]);
uint16_t width = U16_AT(&buffer[6 + 18]);
uint16_t height = U16_AT(&buffer[6 + 20]);
if (width == 0) width = 352;
if (height == 0) height = 288;
if (chunk_type != FOURCC('e', 'n', 'c', 'v')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
}
mLastTrack->meta->setInt32(kKeyWidth, width);
mLastTrack->meta->setInt32(kKeyHeight, height);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('s', 't', 'c', 'o'):
case FOURCC('c', 'o', '6', '4'):
{
status_t err =
mLastTrack->sampleTable->setChunkOffsetParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'c'):
{
status_t err =
mLastTrack->sampleTable->setSampleToChunkParams(
data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'z'):
case FOURCC('s', 't', 'z', '2'):
{
status_t err =
mLastTrack->sampleTable->setSampleSizeParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
size_t max_size;
err = mLastTrack->sampleTable->getMaxSampleSize(&max_size);
if (err != OK) {
return err;
}
if (max_size != 0) {
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2);
} else {
int32_t width, height;
if (!mLastTrack->meta->findInt32(kKeyWidth, &width) ||
!mLastTrack->meta->findInt32(kKeyHeight, &height)) {
ALOGE("No width or height, assuming worst case 1080p");
width = 1920;
height = 1080;
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192;
} else {
max_size = width * height * 3 / 2;
}
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size);
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strncasecmp("video/", mime, 6)) {
size_t nSamples = mLastTrack->sampleTable->countSamples();
int64_t durationUs;
if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) {
if (durationUs > 0) {
int32_t frameRate = (nSamples * 1000000LL +
(durationUs >> 1)) / durationUs;
mLastTrack->meta->setInt32(kKeyFrameRate, frameRate);
}
}
}
break;
}
case FOURCC('s', 't', 't', 's'):
{
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('c', 't', 't', 's'):
{
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setCompositionTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 's'):
{
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setSyncSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('\xA9', 'x', 'y', 'z'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
char buffer[18];
off64_t location_length = chunk_data_size - 5;
if (location_length >= (off64_t) sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset + 4, buffer, location_length) < location_length) {
return ERROR_IO;
}
buffer[location_length] = '\0';
mFileMetaData->setCString(kKeyLocation, buffer);
break;
}
case FOURCC('e', 's', 'd', 's'):
{
*offset += chunk_size;
if (chunk_data_size < 4) {
return ERROR_MALFORMED;
}
uint8_t buffer[256];
if (chunk_data_size > (off64_t)sizeof(buffer)) {
return ERROR_BUFFER_TOO_SMALL;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
mLastTrack->meta->setData(
kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4);
if (mPath.size() >= 2
&& mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) {
status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio(
&buffer[4], chunk_data_size - 4);
if (err != OK) {
return err;
}
}
break;
}
case FOURCC('a', 'v', 'c', 'C'):
{
*offset += chunk_size;
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size);
break;
}
case FOURCC('h', 'v', 'c', 'C'):
{
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size);
*offset += chunk_size;
break;
}
case FOURCC('d', '2', '6', '3'):
{
*offset += chunk_size;
/*
* d263 contains a fixed 7 bytes part:
* vendor - 4 bytes
* version - 1 byte
* level - 1 byte
* profile - 1 byte
* optionally, "d263" box itself may contain a 16-byte
* bit rate box (bitr)
* average bit rate - 4 bytes
* max bit rate - 4 bytes
*/
char buffer[23];
if (chunk_data_size != 7 &&
chunk_data_size != 23) {
ALOGE("Incorrect D263 box size %lld", chunk_data_size);
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size);
break;
}
case FOURCC('m', 'e', 't', 'a'):
{
uint8_t buffer[4];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
*offset += chunk_size;
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 4) < 4) {
*offset += chunk_size;
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
*offset += chunk_size;
return OK;
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'e', 'a', 'n'):
case FOURCC('n', 'a', 'm', 'e'):
case FOURCC('d', 'a', 't', 'a'):
{
*offset += chunk_size;
if (mPath.size() == 6 && underMetaDataPath(mPath)) {
status_t err = parseITunesMetaData(data_offset, chunk_data_size);
if (err != OK) {
return err;
}
}
break;
}
case FOURCC('m', 'v', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 32) {
return ERROR_MALFORMED;
}
uint8_t header[32];
if (mDataSource->readAt(
data_offset, header, sizeof(header))
< (ssize_t)sizeof(header)) {
return ERROR_IO;
}
uint64_t creationTime;
uint64_t duration = 0;
if (header[0] == 1) {
creationTime = U64_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[20]);
duration = U64_AT(&header[24]);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (header[0] != 0) {
return ERROR_MALFORMED;
} else {
creationTime = U32_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[12]);
uint32_t d32 = U32_AT(&header[16]);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
}
if (duration != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
String8 s;
convertTimeToDate(creationTime, &s);
mFileMetaData->setCString(kKeyDate, s.string());
break;
}
case FOURCC('m', 'e', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t flags[4];
if (mDataSource->readAt(
data_offset, flags, sizeof(flags))
< (ssize_t)sizeof(flags)) {
return ERROR_IO;
}
uint64_t duration = 0;
if (flags[0] == 1) {
if (chunk_data_size < 12) {
return ERROR_MALFORMED;
}
mDataSource->getUInt64(data_offset + 4, &duration);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (flags[0] == 0) {
uint32_t d32;
mDataSource->getUInt32(data_offset + 4, &d32);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
} else {
return ERROR_MALFORMED;
}
if (duration != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
break;
}
case FOURCC('m', 'd', 'a', 't'):
{
ALOGV("mdat chunk, drm: %d", mIsDrm);
if (!mIsDrm) {
*offset += chunk_size;
break;
}
if (chunk_size < 8) {
return ERROR_MALFORMED;
}
return parseDrmSINF(offset, data_offset);
}
case FOURCC('h', 'd', 'l', 'r'):
{
*offset += chunk_size;
uint32_t buffer;
if (mDataSource->readAt(
data_offset + 8, &buffer, 4) < 4) {
return ERROR_IO;
}
uint32_t type = ntohl(buffer);
if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) {
mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP);
}
break;
}
case FOURCC('t', 'r', 'e', 'x'):
{
*offset += chunk_size;
if (chunk_data_size < 24) {
return ERROR_IO;
}
uint32_t duration;
Trex trex;
if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) ||
!mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) ||
!mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) ||
!mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) ||
!mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) {
return ERROR_IO;
}
mTrex.add(trex);
break;
}
case FOURCC('t', 'x', '3', 'g'):
{
uint32_t type;
const void *data;
size_t size = 0;
if (!mLastTrack->meta->findData(
kKeyTextFormatData, &type, &data, &size)) {
size = 0;
}
if (SIZE_MAX - chunk_size <= size) {
return ERROR_MALFORMED;
}
uint8_t *buffer = new uint8_t[size + chunk_size];
if (buffer == NULL) {
return ERROR_MALFORMED;
}
if (size > 0) {
memcpy(buffer, data, size);
}
if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size))
< chunk_size) {
delete[] buffer;
buffer = NULL;
*offset += chunk_size;
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyTextFormatData, 0, buffer, size + chunk_size);
delete[] buffer;
*offset += chunk_size;
break;
}
case FOURCC('c', 'o', 'v', 'r'):
{
*offset += chunk_size;
if (mFileMetaData != NULL) {
ALOGV("chunk_data_size = %lld and data_offset = %lld",
chunk_data_size, data_offset);
sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) {
return ERROR_IO;
}
const int kSkipBytesOfDataBox = 16;
if (chunk_data_size <= kSkipBytesOfDataBox) {
return ERROR_MALFORMED;
}
mFileMetaData->setData(
kKeyAlbumArt, MetaData::TYPE_NONE,
buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox);
}
break;
}
case FOURCC('t', 'i', 't', 'l'):
case FOURCC('p', 'e', 'r', 'f'):
case FOURCC('a', 'u', 't', 'h'):
case FOURCC('g', 'n', 'r', 'e'):
case FOURCC('a', 'l', 'b', 'm'):
case FOURCC('y', 'r', 'r', 'c'):
{
*offset += chunk_size;
status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth);
if (err != OK) {
return err;
}
break;
}
case FOURCC('I', 'D', '3', '2'):
{
*offset += chunk_size;
if (chunk_data_size < 6) {
return ERROR_MALFORMED;
}
parseID3v2MetaData(data_offset + 6);
break;
}
case FOURCC('-', '-', '-', '-'):
{
mLastCommentMean.clear();
mLastCommentName.clear();
mLastCommentData.clear();
*offset += chunk_size;
break;
}
case FOURCC('s', 'i', 'd', 'x'):
{
parseSegmentIndex(data_offset, chunk_data_size);
*offset += chunk_size;
return UNKNOWN_ERROR; // stop parsing after sidx
}
default:
{
*offset += chunk_size;
break;
}
}
return OK;
}
|
CWE-189
| 187,388 | 8,024 |
27595787619421068599422293845331979056
| null | null | null |
Android
|
f4f7e0c102819f039ebb1972b3dba1d3186bc1d1
| 1 |
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;
}
|
CWE-119
| 187,389 | 8,025 |
273114330204908454787348035529381798706
| null | null | null |
Android
|
f4a88c8ed4f8186b3d6e2852993e063fc33ff231
| 1 |
status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) {
ALOGV("entering parseChunk %lld/%d", *offset, depth);
uint32_t hdr[2];
if (mDataSource->readAt(*offset, hdr, 8) < 8) {
return ERROR_IO;
}
uint64_t chunk_size = ntohl(hdr[0]);
uint32_t chunk_type = ntohl(hdr[1]);
off64_t data_offset = *offset + 8;
if (chunk_size == 1) {
if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) {
return ERROR_IO;
}
chunk_size = ntoh64(chunk_size);
data_offset += 8;
if (chunk_size < 16) {
return ERROR_MALFORMED;
}
} else if (chunk_size == 0) {
if (depth == 0) {
off64_t sourceSize;
if (mDataSource->getSize(&sourceSize) == OK) {
chunk_size = (sourceSize - *offset);
} else {
ALOGE("atom size is 0, and data source has no size");
return ERROR_MALFORMED;
}
} else {
*offset += 4;
return OK;
}
} else if (chunk_size < 8) {
ALOGE("invalid chunk size: %" PRIu64, chunk_size);
return ERROR_MALFORMED;
}
char chunk[5];
MakeFourCCString(chunk_type, chunk);
ALOGV("chunk: %s @ %lld, %d", chunk, *offset, depth);
#if 0
static const char kWhitespace[] = " ";
const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth];
printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size);
char buffer[256];
size_t n = chunk_size;
if (n > sizeof(buffer)) {
n = sizeof(buffer);
}
if (mDataSource->readAt(*offset, buffer, n)
< (ssize_t)n) {
return ERROR_IO;
}
hexdump(buffer, n);
#endif
PathAdder autoAdder(&mPath, chunk_type);
off64_t chunk_data_size = *offset + chunk_size - data_offset;
if (chunk_type != FOURCC('c', 'p', 'r', 't')
&& chunk_type != FOURCC('c', 'o', 'v', 'r')
&& mPath.size() == 5 && underMetaDataPath(mPath)) {
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
return OK;
}
switch(chunk_type) {
case FOURCC('m', 'o', 'o', 'v'):
case FOURCC('t', 'r', 'a', 'k'):
case FOURCC('m', 'd', 'i', 'a'):
case FOURCC('m', 'i', 'n', 'f'):
case FOURCC('d', 'i', 'n', 'f'):
case FOURCC('s', 't', 'b', 'l'):
case FOURCC('m', 'v', 'e', 'x'):
case FOURCC('m', 'o', 'o', 'f'):
case FOURCC('t', 'r', 'a', 'f'):
case FOURCC('m', 'f', 'r', 'a'):
case FOURCC('u', 'd', 't', 'a'):
case FOURCC('i', 'l', 's', 't'):
case FOURCC('s', 'i', 'n', 'f'):
case FOURCC('s', 'c', 'h', 'i'):
case FOURCC('e', 'd', 't', 's'):
{
if (chunk_type == FOURCC('s', 't', 'b', 'l')) {
ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size);
if (mDataSource->flags()
& (DataSource::kWantsPrefetching
| DataSource::kIsCachingDataSource)) {
sp<MPEG4DataSource> cachedSource =
new MPEG4DataSource(mDataSource);
if (cachedSource->setCachedRange(*offset, chunk_size) == OK) {
mDataSource = cachedSource;
}
}
mLastTrack->sampleTable = new SampleTable(mDataSource);
}
bool isTrack = false;
if (chunk_type == FOURCC('t', 'r', 'a', 'k')) {
isTrack = true;
Track *track = new Track;
track->next = NULL;
if (mLastTrack) {
mLastTrack->next = track;
} else {
mFirstTrack = track;
}
mLastTrack = track;
track->meta = new MetaData;
track->includes_expensive_metadata = false;
track->skipTrack = false;
track->timescale = 0;
track->meta->setCString(kKeyMIMEType, "application/octet-stream");
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
if (isTrack) {
if (mLastTrack->skipTrack) {
Track *cur = mFirstTrack;
if (cur == mLastTrack) {
delete cur;
mFirstTrack = mLastTrack = NULL;
} else {
while (cur && cur->next != mLastTrack) {
cur = cur->next;
}
cur->next = NULL;
delete mLastTrack;
mLastTrack = cur;
}
return OK;
}
status_t err = verifyTrack(mLastTrack);
if (err != OK) {
return err;
}
} else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) {
mInitCheck = OK;
if (!mIsDrm) {
return UNKNOWN_ERROR; // Return a dummy error.
} else {
return OK;
}
}
break;
}
case FOURCC('e', 'l', 's', 't'):
{
*offset += chunk_size;
uint8_t version;
if (mDataSource->readAt(data_offset, &version, 1) < 1) {
return ERROR_IO;
}
uint32_t entry_count;
if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) {
return ERROR_IO;
}
if (entry_count != 1) {
ALOGW("ignoring edit list with %d entries", entry_count);
} else if (mHeaderTimescale == 0) {
ALOGW("ignoring edit list because timescale is 0");
} else {
off64_t entriesoffset = data_offset + 8;
uint64_t segment_duration;
int64_t media_time;
if (version == 1) {
if (!mDataSource->getUInt64(entriesoffset, &segment_duration) ||
!mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) {
return ERROR_IO;
}
} else if (version == 0) {
uint32_t sd;
int32_t mt;
if (!mDataSource->getUInt32(entriesoffset, &sd) ||
!mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) {
return ERROR_IO;
}
segment_duration = sd;
media_time = mt;
} else {
return ERROR_IO;
}
uint64_t halfscale = mHeaderTimescale / 2;
segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale;
media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale;
int64_t duration;
int32_t samplerate;
if (!mLastTrack) {
return ERROR_MALFORMED;
}
if (mLastTrack->meta->findInt64(kKeyDuration, &duration) &&
mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) {
int64_t delay = (media_time * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderDelay, delay);
int64_t paddingus = duration - (segment_duration + media_time);
if (paddingus < 0) {
paddingus = 0;
}
int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples);
}
}
break;
}
case FOURCC('f', 'r', 'm', 'a'):
{
*offset += chunk_size;
uint32_t original_fourcc;
if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) {
return ERROR_IO;
}
original_fourcc = ntohl(original_fourcc);
ALOGV("read original format: %d", original_fourcc);
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc));
uint32_t num_channels = 0;
uint32_t sample_rate = 0;
if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) {
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
}
break;
}
case FOURCC('t', 'e', 'n', 'c'):
{
*offset += chunk_size;
if (chunk_size < 32) {
return ERROR_MALFORMED;
}
char buf[4];
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) {
return ERROR_IO;
}
uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf));
if (defaultAlgorithmId > 1) {
return ERROR_MALFORMED;
}
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) {
return ERROR_IO;
}
uint32_t defaultIVSize = ntohl(*((int32_t*)buf));
if ((defaultAlgorithmId == 0 && defaultIVSize != 0) ||
(defaultAlgorithmId != 0 && defaultIVSize == 0)) {
return ERROR_MALFORMED;
} else if (defaultIVSize != 0 &&
defaultIVSize != 8 &&
defaultIVSize != 16) {
return ERROR_MALFORMED;
}
uint8_t defaultKeyId[16];
if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) {
return ERROR_IO;
}
mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId);
mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize);
mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16);
break;
}
case FOURCC('t', 'k', 'h', 'd'):
{
*offset += chunk_size;
status_t err;
if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) {
return err;
}
break;
}
case FOURCC('p', 's', 's', 'h'):
{
*offset += chunk_size;
PsshInfo pssh;
if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) {
return ERROR_IO;
}
uint32_t psshdatalen = 0;
if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) {
return ERROR_IO;
}
pssh.datalen = ntohl(psshdatalen);
ALOGV("pssh data size: %d", pssh.datalen);
if (pssh.datalen + 20 > chunk_size) {
return ERROR_MALFORMED;
}
pssh.data = new (std::nothrow) uint8_t[pssh.datalen];
if (pssh.data == NULL) {
return ERROR_MALFORMED;
}
ALOGV("allocated pssh @ %p", pssh.data);
ssize_t requested = (ssize_t) pssh.datalen;
if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) {
return ERROR_IO;
}
mPssh.push_back(pssh);
break;
}
case FOURCC('m', 'd', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 4 || mLastTrack == NULL) {
return ERROR_MALFORMED;
}
uint8_t version;
if (mDataSource->readAt(
data_offset, &version, sizeof(version))
< (ssize_t)sizeof(version)) {
return ERROR_IO;
}
off64_t timescale_offset;
if (version == 1) {
timescale_offset = data_offset + 4 + 16;
} else if (version == 0) {
timescale_offset = data_offset + 4 + 8;
} else {
return ERROR_IO;
}
uint32_t timescale;
if (mDataSource->readAt(
timescale_offset, ×cale, sizeof(timescale))
< (ssize_t)sizeof(timescale)) {
return ERROR_IO;
}
mLastTrack->timescale = ntohl(timescale);
int64_t duration = 0;
if (version == 1) {
if (mDataSource->readAt(
timescale_offset + 4, &duration, sizeof(duration))
< (ssize_t)sizeof(duration)) {
return ERROR_IO;
}
if (duration != -1) {
duration = ntoh64(duration);
}
} else {
uint32_t duration32;
if (mDataSource->readAt(
timescale_offset + 4, &duration32, sizeof(duration32))
< (ssize_t)sizeof(duration32)) {
return ERROR_IO;
}
if (duration32 != 0xffffffff) {
duration = ntohl(duration32);
}
}
if (duration != 0) {
mLastTrack->meta->setInt64(
kKeyDuration, (duration * 1000000) / mLastTrack->timescale);
}
uint8_t lang[2];
off64_t lang_offset;
if (version == 1) {
lang_offset = timescale_offset + 4 + 8;
} else if (version == 0) {
lang_offset = timescale_offset + 4 + 4;
} else {
return ERROR_IO;
}
if (mDataSource->readAt(lang_offset, &lang, sizeof(lang))
< (ssize_t)sizeof(lang)) {
return ERROR_IO;
}
char lang_code[4];
lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60;
lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60;
lang_code[2] = (lang[1] & 0x1f) + 0x60;
lang_code[3] = '\0';
mLastTrack->meta->setCString(
kKeyMediaLanguage, lang_code);
break;
}
case FOURCC('s', 't', 's', 'd'):
{
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t buffer[8];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 8) < 8) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
uint32_t entry_count = U32_AT(&buffer[4]);
if (entry_count > 1) {
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) &&
strcasecmp(mime, "application/octet-stream")) {
mLastTrack->skipTrack = true;
*offset += chunk_size;
break;
}
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + 8;
for (uint32_t i = 0; i < entry_count; ++i) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'a'):
case FOURCC('e', 'n', 'c', 'a'):
case FOURCC('s', 'a', 'm', 'r'):
case FOURCC('s', 'a', 'w', 'b'):
{
uint8_t buffer[8 + 20];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index = U16_AT(&buffer[6]);
uint32_t num_channels = U16_AT(&buffer[16]);
uint16_t sample_size = U16_AT(&buffer[18]);
uint32_t sample_rate = U32_AT(&buffer[24]) >> 16;
if (chunk_type != FOURCC('e', 'n', 'c', 'a')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate);
}
ALOGV("*** coding='%s' %d channels, size %d, rate %d\n",
chunk, num_channels, sample_size, sample_rate);
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'v'):
case FOURCC('e', 'n', 'c', 'v'):
case FOURCC('s', '2', '6', '3'):
case FOURCC('H', '2', '6', '3'):
case FOURCC('h', '2', '6', '3'):
case FOURCC('a', 'v', 'c', '1'):
case FOURCC('h', 'v', 'c', '1'):
case FOURCC('h', 'e', 'v', '1'):
{
mHasVideo = true;
uint8_t buffer[78];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index = U16_AT(&buffer[6]);
uint16_t width = U16_AT(&buffer[6 + 18]);
uint16_t height = U16_AT(&buffer[6 + 20]);
if (width == 0) width = 352;
if (height == 0) height = 288;
if (chunk_type != FOURCC('e', 'n', 'c', 'v')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
}
mLastTrack->meta->setInt32(kKeyWidth, width);
mLastTrack->meta->setInt32(kKeyHeight, height);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('s', 't', 'c', 'o'):
case FOURCC('c', 'o', '6', '4'):
{
status_t err =
mLastTrack->sampleTable->setChunkOffsetParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'c'):
{
status_t err =
mLastTrack->sampleTable->setSampleToChunkParams(
data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'z'):
case FOURCC('s', 't', 'z', '2'):
{
status_t err =
mLastTrack->sampleTable->setSampleSizeParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
size_t max_size;
err = mLastTrack->sampleTable->getMaxSampleSize(&max_size);
if (err != OK) {
return err;
}
if (max_size != 0) {
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2);
} else {
int32_t width, height;
if (!mLastTrack->meta->findInt32(kKeyWidth, &width) ||
!mLastTrack->meta->findInt32(kKeyHeight, &height)) {
ALOGE("No width or height, assuming worst case 1080p");
width = 1920;
height = 1080;
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192;
} else {
max_size = width * height * 3 / 2;
}
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size);
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strncasecmp("video/", mime, 6)) {
size_t nSamples = mLastTrack->sampleTable->countSamples();
int64_t durationUs;
if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) {
if (durationUs > 0) {
int32_t frameRate = (nSamples * 1000000LL +
(durationUs >> 1)) / durationUs;
mLastTrack->meta->setInt32(kKeyFrameRate, frameRate);
}
}
}
break;
}
case FOURCC('s', 't', 't', 's'):
{
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('c', 't', 't', 's'):
{
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setCompositionTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 's'):
{
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setSyncSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('\xA9', 'x', 'y', 'z'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
char buffer[18];
off64_t location_length = chunk_data_size - 5;
if (location_length >= (off64_t) sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset + 4, buffer, location_length) < location_length) {
return ERROR_IO;
}
buffer[location_length] = '\0';
mFileMetaData->setCString(kKeyLocation, buffer);
break;
}
case FOURCC('e', 's', 'd', 's'):
{
*offset += chunk_size;
if (chunk_data_size < 4) {
return ERROR_MALFORMED;
}
uint8_t buffer[256];
if (chunk_data_size > (off64_t)sizeof(buffer)) {
return ERROR_BUFFER_TOO_SMALL;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
mLastTrack->meta->setData(
kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4);
if (mPath.size() >= 2
&& mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) {
status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio(
&buffer[4], chunk_data_size - 4);
if (err != OK) {
return err;
}
}
break;
}
case FOURCC('a', 'v', 'c', 'C'):
{
*offset += chunk_size;
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size);
break;
}
case FOURCC('h', 'v', 'c', 'C'):
{
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size);
*offset += chunk_size;
break;
}
case FOURCC('d', '2', '6', '3'):
{
*offset += chunk_size;
/*
* d263 contains a fixed 7 bytes part:
* vendor - 4 bytes
* version - 1 byte
* level - 1 byte
* profile - 1 byte
* optionally, "d263" box itself may contain a 16-byte
* bit rate box (bitr)
* average bit rate - 4 bytes
* max bit rate - 4 bytes
*/
char buffer[23];
if (chunk_data_size != 7 &&
chunk_data_size != 23) {
ALOGE("Incorrect D263 box size %lld", chunk_data_size);
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size);
break;
}
case FOURCC('m', 'e', 't', 'a'):
{
uint8_t buffer[4];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
*offset += chunk_size;
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 4) < 4) {
*offset += chunk_size;
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
*offset += chunk_size;
return OK;
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'e', 'a', 'n'):
case FOURCC('n', 'a', 'm', 'e'):
case FOURCC('d', 'a', 't', 'a'):
{
*offset += chunk_size;
if (mPath.size() == 6 && underMetaDataPath(mPath)) {
status_t err = parseITunesMetaData(data_offset, chunk_data_size);
if (err != OK) {
return err;
}
}
break;
}
case FOURCC('m', 'v', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 32) {
return ERROR_MALFORMED;
}
uint8_t header[32];
if (mDataSource->readAt(
data_offset, header, sizeof(header))
< (ssize_t)sizeof(header)) {
return ERROR_IO;
}
uint64_t creationTime;
uint64_t duration = 0;
if (header[0] == 1) {
creationTime = U64_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[20]);
duration = U64_AT(&header[24]);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (header[0] != 0) {
return ERROR_MALFORMED;
} else {
creationTime = U32_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[12]);
uint32_t d32 = U32_AT(&header[16]);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
}
if (duration != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
String8 s;
convertTimeToDate(creationTime, &s);
mFileMetaData->setCString(kKeyDate, s.string());
break;
}
case FOURCC('m', 'e', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t flags[4];
if (mDataSource->readAt(
data_offset, flags, sizeof(flags))
< (ssize_t)sizeof(flags)) {
return ERROR_IO;
}
uint64_t duration = 0;
if (flags[0] == 1) {
if (chunk_data_size < 12) {
return ERROR_MALFORMED;
}
mDataSource->getUInt64(data_offset + 4, &duration);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (flags[0] == 0) {
uint32_t d32;
mDataSource->getUInt32(data_offset + 4, &d32);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
} else {
return ERROR_MALFORMED;
}
if (duration != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
break;
}
case FOURCC('m', 'd', 'a', 't'):
{
ALOGV("mdat chunk, drm: %d", mIsDrm);
if (!mIsDrm) {
*offset += chunk_size;
break;
}
if (chunk_size < 8) {
return ERROR_MALFORMED;
}
return parseDrmSINF(offset, data_offset);
}
case FOURCC('h', 'd', 'l', 'r'):
{
*offset += chunk_size;
uint32_t buffer;
if (mDataSource->readAt(
data_offset + 8, &buffer, 4) < 4) {
return ERROR_IO;
}
uint32_t type = ntohl(buffer);
if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) {
mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP);
}
break;
}
case FOURCC('t', 'r', 'e', 'x'):
{
*offset += chunk_size;
if (chunk_data_size < 24) {
return ERROR_IO;
}
uint32_t duration;
Trex trex;
if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) ||
!mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) ||
!mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) ||
!mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) ||
!mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) {
return ERROR_IO;
}
mTrex.add(trex);
break;
}
case FOURCC('t', 'x', '3', 'g'):
{
uint32_t type;
const void *data;
size_t size = 0;
if (!mLastTrack->meta->findData(
kKeyTextFormatData, &type, &data, &size)) {
size = 0;
}
uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size];
if (buffer == NULL) {
return ERROR_MALFORMED;
}
if (size > 0) {
memcpy(buffer, data, size);
}
if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size))
< chunk_size) {
delete[] buffer;
buffer = NULL;
*offset += chunk_size;
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyTextFormatData, 0, buffer, size + chunk_size);
delete[] buffer;
*offset += chunk_size;
break;
}
case FOURCC('c', 'o', 'v', 'r'):
{
*offset += chunk_size;
if (mFileMetaData != NULL) {
ALOGV("chunk_data_size = %lld and data_offset = %lld",
chunk_data_size, data_offset);
sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) {
return ERROR_IO;
}
const int kSkipBytesOfDataBox = 16;
mFileMetaData->setData(
kKeyAlbumArt, MetaData::TYPE_NONE,
buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox);
}
break;
}
case FOURCC('t', 'i', 't', 'l'):
case FOURCC('p', 'e', 'r', 'f'):
case FOURCC('a', 'u', 't', 'h'):
case FOURCC('g', 'n', 'r', 'e'):
case FOURCC('a', 'l', 'b', 'm'):
case FOURCC('y', 'r', 'r', 'c'):
{
*offset += chunk_size;
status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth);
if (err != OK) {
return err;
}
break;
}
case FOURCC('I', 'D', '3', '2'):
{
*offset += chunk_size;
if (chunk_data_size < 6) {
return ERROR_MALFORMED;
}
parseID3v2MetaData(data_offset + 6);
break;
}
case FOURCC('-', '-', '-', '-'):
{
mLastCommentMean.clear();
mLastCommentName.clear();
mLastCommentData.clear();
*offset += chunk_size;
break;
}
case FOURCC('s', 'i', 'd', 'x'):
{
parseSegmentIndex(data_offset, chunk_data_size);
*offset += chunk_size;
return UNKNOWN_ERROR; // stop parsing after sidx
}
default:
{
*offset += chunk_size;
break;
}
}
return OK;
}
|
CWE-119
| 187,390 | 8,026 |
221766710213051466482825495789610930772
| null | null | null |
Android
|
463a6f807e187828442949d1924e143cf07778c6
| 1 |
status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) {
ALOGV("entering parseChunk %lld/%d", *offset, depth);
uint32_t hdr[2];
if (mDataSource->readAt(*offset, hdr, 8) < 8) {
return ERROR_IO;
}
uint64_t chunk_size = ntohl(hdr[0]);
uint32_t chunk_type = ntohl(hdr[1]);
off64_t data_offset = *offset + 8;
if (chunk_size == 1) {
if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) {
return ERROR_IO;
}
chunk_size = ntoh64(chunk_size);
data_offset += 8;
if (chunk_size < 16) {
return ERROR_MALFORMED;
}
} else if (chunk_size == 0) {
if (depth == 0) {
off64_t sourceSize;
if (mDataSource->getSize(&sourceSize) == OK) {
chunk_size = (sourceSize - *offset);
} else {
ALOGE("atom size is 0, and data source has no size");
return ERROR_MALFORMED;
}
} else {
*offset += 4;
return OK;
}
} else if (chunk_size < 8) {
ALOGE("invalid chunk size: %" PRIu64, chunk_size);
return ERROR_MALFORMED;
}
char chunk[5];
MakeFourCCString(chunk_type, chunk);
ALOGV("chunk: %s @ %lld, %d", chunk, *offset, depth);
#if 0
static const char kWhitespace[] = " ";
const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth];
printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size);
char buffer[256];
size_t n = chunk_size;
if (n > sizeof(buffer)) {
n = sizeof(buffer);
}
if (mDataSource->readAt(*offset, buffer, n)
< (ssize_t)n) {
return ERROR_IO;
}
hexdump(buffer, n);
#endif
PathAdder autoAdder(&mPath, chunk_type);
off64_t chunk_data_size = *offset + chunk_size - data_offset;
if (chunk_type != FOURCC('c', 'p', 'r', 't')
&& chunk_type != FOURCC('c', 'o', 'v', 'r')
&& mPath.size() == 5 && underMetaDataPath(mPath)) {
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
return OK;
}
switch(chunk_type) {
case FOURCC('m', 'o', 'o', 'v'):
case FOURCC('t', 'r', 'a', 'k'):
case FOURCC('m', 'd', 'i', 'a'):
case FOURCC('m', 'i', 'n', 'f'):
case FOURCC('d', 'i', 'n', 'f'):
case FOURCC('s', 't', 'b', 'l'):
case FOURCC('m', 'v', 'e', 'x'):
case FOURCC('m', 'o', 'o', 'f'):
case FOURCC('t', 'r', 'a', 'f'):
case FOURCC('m', 'f', 'r', 'a'):
case FOURCC('u', 'd', 't', 'a'):
case FOURCC('i', 'l', 's', 't'):
case FOURCC('s', 'i', 'n', 'f'):
case FOURCC('s', 'c', 'h', 'i'):
case FOURCC('e', 'd', 't', 's'):
{
if (chunk_type == FOURCC('s', 't', 'b', 'l')) {
ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size);
if (mDataSource->flags()
& (DataSource::kWantsPrefetching
| DataSource::kIsCachingDataSource)) {
sp<MPEG4DataSource> cachedSource =
new MPEG4DataSource(mDataSource);
if (cachedSource->setCachedRange(*offset, chunk_size) == OK) {
mDataSource = cachedSource;
}
}
mLastTrack->sampleTable = new SampleTable(mDataSource);
}
bool isTrack = false;
if (chunk_type == FOURCC('t', 'r', 'a', 'k')) {
isTrack = true;
Track *track = new Track;
track->next = NULL;
if (mLastTrack) {
mLastTrack->next = track;
} else {
mFirstTrack = track;
}
mLastTrack = track;
track->meta = new MetaData;
track->includes_expensive_metadata = false;
track->skipTrack = false;
track->timescale = 0;
track->meta->setCString(kKeyMIMEType, "application/octet-stream");
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
if (isTrack) {
if (mLastTrack->skipTrack) {
Track *cur = mFirstTrack;
if (cur == mLastTrack) {
delete cur;
mFirstTrack = mLastTrack = NULL;
} else {
while (cur && cur->next != mLastTrack) {
cur = cur->next;
}
cur->next = NULL;
delete mLastTrack;
mLastTrack = cur;
}
return OK;
}
status_t err = verifyTrack(mLastTrack);
if (err != OK) {
return err;
}
} else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) {
mInitCheck = OK;
if (!mIsDrm) {
return UNKNOWN_ERROR; // Return a dummy error.
} else {
return OK;
}
}
break;
}
case FOURCC('e', 'l', 's', 't'):
{
*offset += chunk_size;
uint8_t version;
if (mDataSource->readAt(data_offset, &version, 1) < 1) {
return ERROR_IO;
}
uint32_t entry_count;
if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) {
return ERROR_IO;
}
if (entry_count != 1) {
ALOGW("ignoring edit list with %d entries", entry_count);
} else if (mHeaderTimescale == 0) {
ALOGW("ignoring edit list because timescale is 0");
} else {
off64_t entriesoffset = data_offset + 8;
uint64_t segment_duration;
int64_t media_time;
if (version == 1) {
if (!mDataSource->getUInt64(entriesoffset, &segment_duration) ||
!mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) {
return ERROR_IO;
}
} else if (version == 0) {
uint32_t sd;
int32_t mt;
if (!mDataSource->getUInt32(entriesoffset, &sd) ||
!mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) {
return ERROR_IO;
}
segment_duration = sd;
media_time = mt;
} else {
return ERROR_IO;
}
uint64_t halfscale = mHeaderTimescale / 2;
segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale;
media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale;
int64_t duration;
int32_t samplerate;
if (!mLastTrack) {
return ERROR_MALFORMED;
}
if (mLastTrack->meta->findInt64(kKeyDuration, &duration) &&
mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) {
int64_t delay = (media_time * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderDelay, delay);
int64_t paddingus = duration - (segment_duration + media_time);
if (paddingus < 0) {
paddingus = 0;
}
int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples);
}
}
break;
}
case FOURCC('f', 'r', 'm', 'a'):
{
*offset += chunk_size;
uint32_t original_fourcc;
if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) {
return ERROR_IO;
}
original_fourcc = ntohl(original_fourcc);
ALOGV("read original format: %d", original_fourcc);
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc));
uint32_t num_channels = 0;
uint32_t sample_rate = 0;
if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) {
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
}
break;
}
case FOURCC('t', 'e', 'n', 'c'):
{
*offset += chunk_size;
if (chunk_size < 32) {
return ERROR_MALFORMED;
}
char buf[4];
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) {
return ERROR_IO;
}
uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf));
if (defaultAlgorithmId > 1) {
return ERROR_MALFORMED;
}
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) {
return ERROR_IO;
}
uint32_t defaultIVSize = ntohl(*((int32_t*)buf));
if ((defaultAlgorithmId == 0 && defaultIVSize != 0) ||
(defaultAlgorithmId != 0 && defaultIVSize == 0)) {
return ERROR_MALFORMED;
} else if (defaultIVSize != 0 &&
defaultIVSize != 8 &&
defaultIVSize != 16) {
return ERROR_MALFORMED;
}
uint8_t defaultKeyId[16];
if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) {
return ERROR_IO;
}
mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId);
mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize);
mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16);
break;
}
case FOURCC('t', 'k', 'h', 'd'):
{
*offset += chunk_size;
status_t err;
if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) {
return err;
}
break;
}
case FOURCC('p', 's', 's', 'h'):
{
*offset += chunk_size;
PsshInfo pssh;
if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) {
return ERROR_IO;
}
uint32_t psshdatalen = 0;
if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) {
return ERROR_IO;
}
pssh.datalen = ntohl(psshdatalen);
ALOGV("pssh data size: %d", pssh.datalen);
if (pssh.datalen + 20 > chunk_size) {
return ERROR_MALFORMED;
}
pssh.data = new (std::nothrow) uint8_t[pssh.datalen];
if (pssh.data == NULL) {
return ERROR_MALFORMED;
}
ALOGV("allocated pssh @ %p", pssh.data);
ssize_t requested = (ssize_t) pssh.datalen;
if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) {
return ERROR_IO;
}
mPssh.push_back(pssh);
break;
}
case FOURCC('m', 'd', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 4 || mLastTrack == NULL) {
return ERROR_MALFORMED;
}
uint8_t version;
if (mDataSource->readAt(
data_offset, &version, sizeof(version))
< (ssize_t)sizeof(version)) {
return ERROR_IO;
}
off64_t timescale_offset;
if (version == 1) {
timescale_offset = data_offset + 4 + 16;
} else if (version == 0) {
timescale_offset = data_offset + 4 + 8;
} else {
return ERROR_IO;
}
uint32_t timescale;
if (mDataSource->readAt(
timescale_offset, ×cale, sizeof(timescale))
< (ssize_t)sizeof(timescale)) {
return ERROR_IO;
}
mLastTrack->timescale = ntohl(timescale);
int64_t duration = 0;
if (version == 1) {
if (mDataSource->readAt(
timescale_offset + 4, &duration, sizeof(duration))
< (ssize_t)sizeof(duration)) {
return ERROR_IO;
}
if (duration != -1) {
duration = ntoh64(duration);
}
} else {
uint32_t duration32;
if (mDataSource->readAt(
timescale_offset + 4, &duration32, sizeof(duration32))
< (ssize_t)sizeof(duration32)) {
return ERROR_IO;
}
if (duration32 != 0xffffffff) {
duration = ntohl(duration32);
}
}
if (duration != 0) {
mLastTrack->meta->setInt64(
kKeyDuration, (duration * 1000000) / mLastTrack->timescale);
}
uint8_t lang[2];
off64_t lang_offset;
if (version == 1) {
lang_offset = timescale_offset + 4 + 8;
} else if (version == 0) {
lang_offset = timescale_offset + 4 + 4;
} else {
return ERROR_IO;
}
if (mDataSource->readAt(lang_offset, &lang, sizeof(lang))
< (ssize_t)sizeof(lang)) {
return ERROR_IO;
}
char lang_code[4];
lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60;
lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60;
lang_code[2] = (lang[1] & 0x1f) + 0x60;
lang_code[3] = '\0';
mLastTrack->meta->setCString(
kKeyMediaLanguage, lang_code);
break;
}
case FOURCC('s', 't', 's', 'd'):
{
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t buffer[8];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 8) < 8) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
uint32_t entry_count = U32_AT(&buffer[4]);
if (entry_count > 1) {
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) &&
strcasecmp(mime, "application/octet-stream")) {
mLastTrack->skipTrack = true;
*offset += chunk_size;
break;
}
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + 8;
for (uint32_t i = 0; i < entry_count; ++i) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'a'):
case FOURCC('e', 'n', 'c', 'a'):
case FOURCC('s', 'a', 'm', 'r'):
case FOURCC('s', 'a', 'w', 'b'):
{
uint8_t buffer[8 + 20];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index = U16_AT(&buffer[6]);
uint32_t num_channels = U16_AT(&buffer[16]);
uint16_t sample_size = U16_AT(&buffer[18]);
uint32_t sample_rate = U32_AT(&buffer[24]) >> 16;
if (chunk_type != FOURCC('e', 'n', 'c', 'a')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate);
}
ALOGV("*** coding='%s' %d channels, size %d, rate %d\n",
chunk, num_channels, sample_size, sample_rate);
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'v'):
case FOURCC('e', 'n', 'c', 'v'):
case FOURCC('s', '2', '6', '3'):
case FOURCC('H', '2', '6', '3'):
case FOURCC('h', '2', '6', '3'):
case FOURCC('a', 'v', 'c', '1'):
case FOURCC('h', 'v', 'c', '1'):
case FOURCC('h', 'e', 'v', '1'):
{
mHasVideo = true;
uint8_t buffer[78];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index = U16_AT(&buffer[6]);
uint16_t width = U16_AT(&buffer[6 + 18]);
uint16_t height = U16_AT(&buffer[6 + 20]);
if (width == 0) width = 352;
if (height == 0) height = 288;
if (chunk_type != FOURCC('e', 'n', 'c', 'v')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
}
mLastTrack->meta->setInt32(kKeyWidth, width);
mLastTrack->meta->setInt32(kKeyHeight, height);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('s', 't', 'c', 'o'):
case FOURCC('c', 'o', '6', '4'):
{
status_t err =
mLastTrack->sampleTable->setChunkOffsetParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'c'):
{
status_t err =
mLastTrack->sampleTable->setSampleToChunkParams(
data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'z'):
case FOURCC('s', 't', 'z', '2'):
{
status_t err =
mLastTrack->sampleTable->setSampleSizeParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
size_t max_size;
err = mLastTrack->sampleTable->getMaxSampleSize(&max_size);
if (err != OK) {
return err;
}
if (max_size != 0) {
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2);
} else {
int32_t width, height;
if (!mLastTrack->meta->findInt32(kKeyWidth, &width) ||
!mLastTrack->meta->findInt32(kKeyHeight, &height)) {
ALOGE("No width or height, assuming worst case 1080p");
width = 1920;
height = 1080;
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192;
} else {
max_size = width * height * 3 / 2;
}
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size);
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strncasecmp("video/", mime, 6)) {
size_t nSamples = mLastTrack->sampleTable->countSamples();
int64_t durationUs;
if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) {
if (durationUs > 0) {
int32_t frameRate = (nSamples * 1000000LL +
(durationUs >> 1)) / durationUs;
mLastTrack->meta->setInt32(kKeyFrameRate, frameRate);
}
}
}
break;
}
case FOURCC('s', 't', 't', 's'):
{
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('c', 't', 't', 's'):
{
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setCompositionTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 's'):
{
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setSyncSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('\xA9', 'x', 'y', 'z'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
char buffer[18];
off64_t location_length = chunk_data_size - 5;
if (location_length >= (off64_t) sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset + 4, buffer, location_length) < location_length) {
return ERROR_IO;
}
buffer[location_length] = '\0';
mFileMetaData->setCString(kKeyLocation, buffer);
break;
}
case FOURCC('e', 's', 'd', 's'):
{
*offset += chunk_size;
if (chunk_data_size < 4) {
return ERROR_MALFORMED;
}
uint8_t buffer[256];
if (chunk_data_size > (off64_t)sizeof(buffer)) {
return ERROR_BUFFER_TOO_SMALL;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
mLastTrack->meta->setData(
kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4);
if (mPath.size() >= 2
&& mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) {
status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio(
&buffer[4], chunk_data_size - 4);
if (err != OK) {
return err;
}
}
break;
}
case FOURCC('a', 'v', 'c', 'C'):
{
*offset += chunk_size;
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size);
break;
}
case FOURCC('h', 'v', 'c', 'C'):
{
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size);
*offset += chunk_size;
break;
}
case FOURCC('d', '2', '6', '3'):
{
*offset += chunk_size;
/*
* d263 contains a fixed 7 bytes part:
* vendor - 4 bytes
* version - 1 byte
* level - 1 byte
* profile - 1 byte
* optionally, "d263" box itself may contain a 16-byte
* bit rate box (bitr)
* average bit rate - 4 bytes
* max bit rate - 4 bytes
*/
char buffer[23];
if (chunk_data_size != 7 &&
chunk_data_size != 23) {
ALOGE("Incorrect D263 box size %lld", chunk_data_size);
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size);
break;
}
case FOURCC('m', 'e', 't', 'a'):
{
uint8_t buffer[4];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
*offset += chunk_size;
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 4) < 4) {
*offset += chunk_size;
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
*offset += chunk_size;
return OK;
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'e', 'a', 'n'):
case FOURCC('n', 'a', 'm', 'e'):
case FOURCC('d', 'a', 't', 'a'):
{
*offset += chunk_size;
if (mPath.size() == 6 && underMetaDataPath(mPath)) {
status_t err = parseITunesMetaData(data_offset, chunk_data_size);
if (err != OK) {
return err;
}
}
break;
}
case FOURCC('m', 'v', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 32) {
return ERROR_MALFORMED;
}
uint8_t header[32];
if (mDataSource->readAt(
data_offset, header, sizeof(header))
< (ssize_t)sizeof(header)) {
return ERROR_IO;
}
uint64_t creationTime;
uint64_t duration = 0;
if (header[0] == 1) {
creationTime = U64_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[20]);
duration = U64_AT(&header[24]);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (header[0] != 0) {
return ERROR_MALFORMED;
} else {
creationTime = U32_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[12]);
uint32_t d32 = U32_AT(&header[16]);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
}
if (duration != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
String8 s;
convertTimeToDate(creationTime, &s);
mFileMetaData->setCString(kKeyDate, s.string());
break;
}
case FOURCC('m', 'e', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t flags[4];
if (mDataSource->readAt(
data_offset, flags, sizeof(flags))
< (ssize_t)sizeof(flags)) {
return ERROR_IO;
}
uint64_t duration = 0;
if (flags[0] == 1) {
if (chunk_data_size < 12) {
return ERROR_MALFORMED;
}
mDataSource->getUInt64(data_offset + 4, &duration);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (flags[0] == 0) {
uint32_t d32;
mDataSource->getUInt32(data_offset + 4, &d32);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
} else {
return ERROR_MALFORMED;
}
if (duration != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
break;
}
case FOURCC('m', 'd', 'a', 't'):
{
ALOGV("mdat chunk, drm: %d", mIsDrm);
if (!mIsDrm) {
*offset += chunk_size;
break;
}
if (chunk_size < 8) {
return ERROR_MALFORMED;
}
return parseDrmSINF(offset, data_offset);
}
case FOURCC('h', 'd', 'l', 'r'):
{
*offset += chunk_size;
uint32_t buffer;
if (mDataSource->readAt(
data_offset + 8, &buffer, 4) < 4) {
return ERROR_IO;
}
uint32_t type = ntohl(buffer);
if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) {
mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP);
}
break;
}
case FOURCC('t', 'r', 'e', 'x'):
{
*offset += chunk_size;
if (chunk_data_size < 24) {
return ERROR_IO;
}
uint32_t duration;
Trex trex;
if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) ||
!mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) ||
!mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) ||
!mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) ||
!mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) {
return ERROR_IO;
}
mTrex.add(trex);
break;
}
case FOURCC('t', 'x', '3', 'g'):
{
uint32_t type;
const void *data;
size_t size = 0;
if (!mLastTrack->meta->findData(
kKeyTextFormatData, &type, &data, &size)) {
size = 0;
}
uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size];
if (buffer == NULL) {
return ERROR_MALFORMED;
}
if (size > 0) {
memcpy(buffer, data, size);
}
if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size))
< chunk_size) {
delete[] buffer;
buffer = NULL;
*offset += chunk_size;
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyTextFormatData, 0, buffer, size + chunk_size);
delete[] buffer;
*offset += chunk_size;
break;
}
case FOURCC('c', 'o', 'v', 'r'):
{
*offset += chunk_size;
if (mFileMetaData != NULL) {
ALOGV("chunk_data_size = %lld and data_offset = %lld",
chunk_data_size, data_offset);
sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1);
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) {
return ERROR_IO;
}
const int kSkipBytesOfDataBox = 16;
if (chunk_data_size <= kSkipBytesOfDataBox) {
return ERROR_MALFORMED;
}
mFileMetaData->setData(
kKeyAlbumArt, MetaData::TYPE_NONE,
buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox);
}
break;
}
case FOURCC('t', 'i', 't', 'l'):
case FOURCC('p', 'e', 'r', 'f'):
case FOURCC('a', 'u', 't', 'h'):
case FOURCC('g', 'n', 'r', 'e'):
case FOURCC('a', 'l', 'b', 'm'):
case FOURCC('y', 'r', 'r', 'c'):
{
*offset += chunk_size;
status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth);
if (err != OK) {
return err;
}
break;
}
case FOURCC('I', 'D', '3', '2'):
{
*offset += chunk_size;
if (chunk_data_size < 6) {
return ERROR_MALFORMED;
}
parseID3v2MetaData(data_offset + 6);
break;
}
case FOURCC('-', '-', '-', '-'):
{
mLastCommentMean.clear();
mLastCommentName.clear();
mLastCommentData.clear();
*offset += chunk_size;
break;
}
case FOURCC('s', 'i', 'd', 'x'):
{
parseSegmentIndex(data_offset, chunk_data_size);
*offset += chunk_size;
return UNKNOWN_ERROR; // stop parsing after sidx
}
default:
{
*offset += chunk_size;
break;
}
}
return OK;
}
|
CWE-119
| 187,391 | 8,027 |
134531541806590023779597954492430346181
| null | null | null |
Android
|
5e751957ba692658b7f67eb03ae5ddb2cd3d970c
| 1 |
status_t ESDS::parseESDescriptor(size_t offset, size_t size) {
if (size < 3) {
return ERROR_MALFORMED;
}
offset += 2; // skip ES_ID
size -= 2;
unsigned streamDependenceFlag = mData[offset] & 0x80;
unsigned URL_Flag = mData[offset] & 0x40;
unsigned OCRstreamFlag = mData[offset] & 0x20;
++offset;
--size;
if (streamDependenceFlag) {
offset += 2;
size -= 2;
}
if (URL_Flag) {
if (offset >= size) {
return ERROR_MALFORMED;
}
unsigned URLlength = mData[offset];
offset += URLlength + 1;
size -= URLlength + 1;
}
if (OCRstreamFlag) {
offset += 2;
size -= 2;
if ((offset >= size || mData[offset] != kTag_DecoderConfigDescriptor)
&& offset - 2 < size
&& mData[offset - 2] == kTag_DecoderConfigDescriptor) {
offset -= 2;
size += 2;
ALOGW("Found malformed 'esds' atom, ignoring missing OCR_ES_Id.");
}
}
if (offset >= size) {
return ERROR_MALFORMED;
}
uint8_t tag;
size_t sub_offset, sub_size;
status_t err = skipDescriptorHeader(
offset, size, &tag, &sub_offset, &sub_size);
if (err != OK) {
return err;
}
if (tag != kTag_DecoderConfigDescriptor) {
return ERROR_MALFORMED;
}
err = parseDecoderConfigDescriptor(sub_offset, sub_size);
return err;
}
|
CWE-189
| 187,392 | 8,028 |
251778599478684276636244536595568896329
| null | null | null |
Android
|
d44e5bde18a41beda39d49189bef7f2ba7c8f3cb
| 1 |
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);
}
|
CWE-189
| 187,394 | 8,029 |
104165536811189073630917968198942145348
| null | null | null |
Android
|
7dcd0ec9c91688cfa3f679804ba6e132f9811254
| 1 |
native_handle* Parcel::readNativeHandle() const
{
int numFds, numInts;
status_t err;
err = readInt32(&numFds);
if (err != NO_ERROR) return 0;
err = readInt32(&numInts);
if (err != NO_ERROR) return 0;
native_handle* h = native_handle_create(numFds, numInts);
for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
h->data[i] = dup(readFileDescriptor());
if (h->data[i] < 0) err = BAD_VALUE;
}
err = read(h->data + numFds, sizeof(int)*numInts);
if (err != NO_ERROR) {
native_handle_close(h);
native_handle_delete(h);
h = 0;
}
return h;
}
|
CWE-189
| 187,395 | 8,030 |
182889183101894725948095678711971881548
| null | null | null |
Android
|
89c03b3b9ff74a507a8b8334c50b08b334483556
| 1 |
status_t SampleIterator::seekTo(uint32_t sampleIndex) {
ALOGV("seekTo(%d)", sampleIndex);
if (sampleIndex >= mTable->mNumSampleSizes) {
return ERROR_END_OF_STREAM;
}
if (mTable->mSampleToChunkOffset < 0
|| mTable->mChunkOffsetOffset < 0
|| mTable->mSampleSizeOffset < 0
|| mTable->mTimeToSampleCount == 0) {
return ERROR_MALFORMED;
}
if (mInitialized && mCurrentSampleIndex == sampleIndex) {
return OK;
}
if (!mInitialized || sampleIndex < mFirstChunkSampleIndex) {
reset();
}
if (sampleIndex >= mStopChunkSampleIndex) {
status_t err;
if ((err = findChunkRange(sampleIndex)) != OK) {
ALOGE("findChunkRange failed");
return err;
}
}
CHECK(sampleIndex < mStopChunkSampleIndex);
if (mSamplesPerChunk == 0) {
ALOGE("b/22802344");
return ERROR_MALFORMED;
}
uint32_t chunk =
(sampleIndex - mFirstChunkSampleIndex) / mSamplesPerChunk
+ mFirstChunk;
if (!mInitialized || chunk != mCurrentChunkIndex) {
mCurrentChunkIndex = chunk;
status_t err;
if ((err = getChunkOffset(chunk, &mCurrentChunkOffset)) != OK) {
ALOGE("getChunkOffset return error");
return err;
}
mCurrentChunkSampleSizes.clear();
uint32_t firstChunkSampleIndex =
mFirstChunkSampleIndex
+ mSamplesPerChunk * (mCurrentChunkIndex - mFirstChunk);
for (uint32_t i = 0; i < mSamplesPerChunk; ++i) {
size_t sampleSize;
if ((err = getSampleSizeDirect(
firstChunkSampleIndex + i, &sampleSize)) != OK) {
ALOGE("getSampleSizeDirect return error");
return err;
}
mCurrentChunkSampleSizes.push(sampleSize);
}
}
uint32_t chunkRelativeSampleIndex =
(sampleIndex - mFirstChunkSampleIndex) % mSamplesPerChunk;
mCurrentSampleOffset = mCurrentChunkOffset;
for (uint32_t i = 0; i < chunkRelativeSampleIndex; ++i) {
mCurrentSampleOffset += mCurrentChunkSampleSizes[i];
}
mCurrentSampleSize = mCurrentChunkSampleSizes[chunkRelativeSampleIndex];
if (sampleIndex < mTTSSampleIndex) {
mTimeToSampleIndex = 0;
mTTSSampleIndex = 0;
mTTSSampleTime = 0;
mTTSCount = 0;
mTTSDuration = 0;
}
status_t err;
if ((err = findSampleTimeAndDuration(
sampleIndex, &mCurrentSampleTime, &mCurrentSampleDuration)) != OK) {
ALOGE("findSampleTime return error");
return err;
}
mCurrentSampleIndex = sampleIndex;
mInitialized = true;
return OK;
}
|
CWE-200
| 187,400 | 8,034 |
115645474102852150956194563155948473239
| null | null | null |
Android
|
fdb1b40e7bb147c07bda988c9501ad223795d12d
| 1 |
int vp9_alloc_context_buffers(VP9_COMMON *cm, int width, int height) {
int new_mi_size;
vp9_set_mb_mi(cm, width, height);
new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows);
if (cm->mi_alloc_size < new_mi_size) {
cm->free_mi(cm);
if (cm->alloc_mi(cm, new_mi_size))
goto fail;
}
if (cm->seg_map_alloc_size < cm->mi_rows * cm->mi_cols) {
free_seg_map(cm);
if (alloc_seg_map(cm, cm->mi_rows * cm->mi_cols))
goto fail;
}
if (cm->above_context_alloc_cols < cm->mi_cols) {
vpx_free(cm->above_context);
cm->above_context = (ENTROPY_CONTEXT *)vpx_calloc(
2 * mi_cols_aligned_to_sb(cm->mi_cols) * MAX_MB_PLANE,
sizeof(*cm->above_context));
if (!cm->above_context) goto fail;
vpx_free(cm->above_seg_context);
cm->above_seg_context = (PARTITION_CONTEXT *)vpx_calloc(
mi_cols_aligned_to_sb(cm->mi_cols), sizeof(*cm->above_seg_context));
if (!cm->above_seg_context) goto fail;
cm->above_context_alloc_cols = cm->mi_cols;
}
return 0;
fail:
vp9_free_context_buffers(cm);
return 1;
}
|
CWE-20
| 187,403 | 8,037 |
3857975046340091369285126403616547252
| null | null | null |
Android
|
3b1c9f692c4d4b7a683c2b358fc89e831a641b88
| 1 |
status_t MediaHTTP::connect(
const char *uri,
const KeyedVector<String8, String8> *headers,
off64_t /* offset */) {
if (mInitCheck != OK) {
return mInitCheck;
}
KeyedVector<String8, String8> extHeaders;
if (headers != NULL) {
extHeaders = *headers;
}
if (extHeaders.indexOfKey(String8("User-Agent")) < 0) {
extHeaders.add(String8("User-Agent"), String8(MakeUserAgent().c_str()));
}
bool success = mHTTPConnection->connect(uri, &extHeaders);
mLastHeaders = extHeaders;
mLastURI = uri;
mCachedSizeValid = false;
if (success) {
AString sanitized = uriDebugString(uri);
mName = String8::format("MediaHTTP(%s)", sanitized.c_str());
}
return success ? OK : UNKNOWN_ERROR;
}
|
CWE-119
| 187,408 | 8,040 |
46246661838968122712948820373142448951
| null | null | null |
Android
|
c894aa36be535886a8e5ff02cdbcd07dd24618f6
| 1 |
status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData)
{
Mutex::Autolock _l(mLock);
ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
if (mState == DESTROYED || mEffectInterface == NULL) {
return NO_INIT;
}
if (mStatus != NO_ERROR) {
return mStatus;
}
if (cmdCode == EFFECT_CMD_GET_PARAM &&
(*replySize < sizeof(effect_param_t) ||
((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) {
android_errorWriteLog(0x534e4554, "29251553");
return -EINVAL;
}
status_t status = (*mEffectInterface)->command(mEffectInterface,
cmdCode,
cmdSize,
pCmdData,
replySize,
pReplyData);
if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
uint32_t size = (replySize == NULL) ? 0 : *replySize;
for (size_t i = 1; i < mHandles.size(); i++) {
EffectHandle *h = mHandles[i];
if (h != NULL && !h->destroyed_l()) {
h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
}
}
}
return status;
}
|
CWE-200
| 187,409 | 8,041 |
186065196266317279891737225911987212129
| null | null | null |
Android
|
0c3b93c8c2027e74af642967eee5c142c8fd185d
| 1 |
status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
ALOGV("setNextPlayer");
Mutex::Autolock l(mLock);
sp<Client> c = static_cast<Client*>(player.get());
mNextClient = c;
if (c != NULL) {
if (mAudioOutput != NULL) {
mAudioOutput->setNextOutput(c->mAudioOutput);
} else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
ALOGE("no current audio output");
}
if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
mPlayer->setNextPlayer(mNextClient->getPlayer());
}
}
return OK;
}
|
CWE-264
| 187,420 | 8,052 |
6735926774297518125257858876733449690
| null | null | null |
Android
|
047eec456943dc082e33220d28abb7df4e089f69
| 1 |
static int svc_can_register(const uint16_t *name, size_t name_len, pid_t spid, uid_t uid)
{
const char *perm = "add";
if (uid >= AID_APP) {
return 0; /* Don't allow apps to register services */
}
return check_mac_perms_from_lookup(spid, uid, perm, str8(name, name_len)) ? 1 : 0;
}
|
CWE-264
| 187,425 | 8,057 |
333350833508657224088100166457913693044
| null | null | null |
Android
|
97837bb6cbac21ea679843a0037779d3834bed64
| 1 |
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;
}
|
CWE-284
| 187,426 | 8,058 |
147675475152290092765818530548185153495
| null | null | null |
Android
|
014b01706cc64dc9c2ad94a96f62e07c058d0b5d
| 1 |
void close_all_sockets(atransport* t) {
asocket* s;
/* this is a little gross, but since s->close() *will* modify
** the list out from under you, your options are limited.
*/
std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
restart:
for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
if (s->transport == t || (s->peer && s->peer->transport == t)) {
local_socket_close(s);
goto restart;
}
}
}
|
CWE-264
| 187,427 | 8,059 |
48596368302748879229394287847811642751
| null | null | null |
Android
|
4974dcbd0289a2530df2ee2a25b5f92775df80da
| 1 |
static vpx_codec_err_t decoder_peek_si_internal(const uint8_t *data,
unsigned int data_sz,
vpx_codec_stream_info_t *si,
int *is_intra_only,
vpx_decrypt_cb decrypt_cb,
void *decrypt_state) {
int intra_only_flag = 0;
uint8_t clear_buffer[9];
if (data + data_sz <= data)
return VPX_CODEC_INVALID_PARAM;
si->is_kf = 0;
si->w = si->h = 0;
if (decrypt_cb) {
data_sz = VPXMIN(sizeof(clear_buffer), data_sz);
decrypt_cb(decrypt_state, data, clear_buffer, data_sz);
data = clear_buffer;
}
{
int show_frame;
int error_resilient;
struct vpx_read_bit_buffer rb = { data, data + data_sz, 0, NULL, NULL };
const int frame_marker = vpx_rb_read_literal(&rb, 2);
const BITSTREAM_PROFILE profile = vp9_read_profile(&rb);
if (frame_marker != VP9_FRAME_MARKER)
return VPX_CODEC_UNSUP_BITSTREAM;
if (profile >= MAX_PROFILES)
return VPX_CODEC_UNSUP_BITSTREAM;
if ((profile >= 2 && data_sz <= 1) || data_sz < 1)
return VPX_CODEC_UNSUP_BITSTREAM;
if (vpx_rb_read_bit(&rb)) { // show an existing frame
vpx_rb_read_literal(&rb, 3); // Frame buffer to show.
return VPX_CODEC_OK;
}
if (data_sz <= 8)
return VPX_CODEC_UNSUP_BITSTREAM;
si->is_kf = !vpx_rb_read_bit(&rb);
show_frame = vpx_rb_read_bit(&rb);
error_resilient = vpx_rb_read_bit(&rb);
if (si->is_kf) {
if (!vp9_read_sync_code(&rb))
return VPX_CODEC_UNSUP_BITSTREAM;
if (!parse_bitdepth_colorspace_sampling(profile, &rb))
return VPX_CODEC_UNSUP_BITSTREAM;
vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h);
} else {
intra_only_flag = show_frame ? 0 : vpx_rb_read_bit(&rb);
rb.bit_offset += error_resilient ? 0 : 2; // reset_frame_context
if (intra_only_flag) {
if (!vp9_read_sync_code(&rb))
return VPX_CODEC_UNSUP_BITSTREAM;
if (profile > PROFILE_0) {
if (!parse_bitdepth_colorspace_sampling(profile, &rb))
return VPX_CODEC_UNSUP_BITSTREAM;
}
rb.bit_offset += REF_FRAMES; // refresh_frame_flags
vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h);
}
}
}
if (is_intra_only != NULL)
*is_intra_only = intra_only_flag;
return VPX_CODEC_OK;
}
|
CWE-119
| 187,431 | 8,063 |
37903833722496751600969113569856027714
| null | null | null |
Android
|
cadfb7a3c96d4fef06656cf37143e1b3e62cae86
| 1 |
EAS_RESULT DLSParser (EAS_HW_DATA_HANDLE hwInstData, EAS_FILE_HANDLE fileHandle, EAS_I32 offset, EAS_DLSLIB_HANDLE *ppDLS)
{
EAS_RESULT result;
SDLS_SYNTHESIZER_DATA dls;
EAS_U32 temp;
EAS_I32 pos;
EAS_I32 chunkPos;
EAS_I32 size;
EAS_I32 instSize;
EAS_I32 rgnPoolSize;
EAS_I32 artPoolSize;
EAS_I32 waveLenSize;
EAS_I32 endDLS;
EAS_I32 wvplPos;
EAS_I32 wvplSize;
EAS_I32 linsPos;
EAS_I32 linsSize;
EAS_I32 ptblPos;
EAS_I32 ptblSize;
void *p;
/* zero counts and pointers */
EAS_HWMemSet(&dls, 0, sizeof(dls));
/* save file handle and hwInstData to save copying pointers around */
dls.hwInstData = hwInstData;
dls.fileHandle = fileHandle;
/* NULL return value in case of error */
*ppDLS = NULL;
/* seek to start of DLS and read in RIFF tag and set processor endian flag */
if ((result = EAS_HWFileSeek(dls.hwInstData, dls.fileHandle, offset)) != EAS_SUCCESS)
return result;
if ((result = EAS_HWReadFile(dls.hwInstData, dls.fileHandle, &temp, sizeof(temp), &size)) != EAS_SUCCESS)
return result;
/* check for processor endian-ness */
dls.bigEndian = (temp == CHUNK_RIFF);
/* first chunk should be DLS */
pos = offset;
if ((result = NextChunk(&dls, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
if (temp != CHUNK_DLS)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Expected DLS chunk, got %08lx\n", temp); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* no instrument or wavepool chunks */
linsSize = wvplSize = ptblSize = linsPos = wvplPos = ptblPos = 0;
/* scan the chunks in the DLS list */
endDLS = offset + size;
pos = offset + 12;
while (pos < endDLS)
{
chunkPos = pos;
/* get the next chunk type */
if ((result = NextChunk(&dls, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* parse useful chunks */
switch (temp)
{
case CHUNK_CDL:
if ((result = Parse_cdl(&dls, size, &temp)) != EAS_SUCCESS)
return result;
if (!temp)
return EAS_ERROR_UNRECOGNIZED_FORMAT;
break;
case CHUNK_LINS:
linsPos = chunkPos + 12;
linsSize = size - 4;
break;
case CHUNK_WVPL:
wvplPos = chunkPos + 12;
wvplSize = size - 4;
break;
case CHUNK_PTBL:
ptblPos = chunkPos + 8;
ptblSize = size - 4;
break;
default:
break;
}
}
/* must have a lins chunk */
if (linsSize == 0)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No lins chunk found"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* must have a wvpl chunk */
if (wvplSize == 0)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No wvpl chunk found"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* must have a ptbl chunk */
if ((ptblSize == 0) || (ptblSize > DLS_MAX_WAVE_COUNT * sizeof(POOLCUE) + sizeof(POOLTABLE)))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No ptbl chunk found"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* pre-parse the wave pool chunk */
if ((result = Parse_ptbl(&dls, ptblPos, wvplPos, wvplSize)) != EAS_SUCCESS)
return result;
/* limit check */
if ((dls.waveCount == 0) || (dls.waveCount > DLS_MAX_WAVE_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #waves [%u]\n", dls.waveCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* allocate memory for wsmp data */
dls.wsmpData = EAS_HWMalloc(dls.hwInstData, (EAS_I32) (sizeof(S_WSMP_DATA) * dls.waveCount));
if (dls.wsmpData == NULL)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "EAS_HWMalloc for wsmp data failed\n"); */ }
return EAS_ERROR_MALLOC_FAILED;
}
EAS_HWMemSet(dls.wsmpData, 0, (EAS_I32) (sizeof(S_WSMP_DATA) * dls.waveCount));
/* pre-parse the lins chunk */
result = Parse_lins(&dls, linsPos, linsSize);
if (result == EAS_SUCCESS)
{
/* limit check */
if ((dls.regionCount == 0) || (dls.regionCount > DLS_MAX_REGION_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #regions [%u]\n", dls.regionCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* limit check */
if ((dls.artCount == 0) || (dls.artCount > DLS_MAX_ART_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #articulations [%u]\n", dls.regionCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* limit check */
if ((dls.instCount == 0) || (dls.instCount > DLS_MAX_INST_COUNT))
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #instruments [%u]\n", dls.instCount); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* Allocate memory for the converted DLS data */
/* calculate size of instrument data */
instSize = (EAS_I32) (sizeof(S_PROGRAM) * dls.instCount);
/* calculate size of region pool */
rgnPoolSize = (EAS_I32) (sizeof(S_DLS_REGION) * dls.regionCount);
/* calculate size of articulation pool, add one for default articulation */
dls.artCount++;
artPoolSize = (EAS_I32) (sizeof(S_DLS_ARTICULATION) * dls.artCount);
/* calculate size of wave length and offset arrays */
waveLenSize = (EAS_I32) (dls.waveCount * sizeof(EAS_U32));
/* calculate final memory size */
size = (EAS_I32) sizeof(S_EAS) + instSize + rgnPoolSize + artPoolSize + (2 * waveLenSize) + (EAS_I32) dls.wavePoolSize;
if (size <= 0) {
return EAS_ERROR_FILE_FORMAT;
}
/* allocate the main EAS chunk */
dls.pDLS = EAS_HWMalloc(dls.hwInstData, size);
if (dls.pDLS == NULL)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "EAS_HWMalloc failed for DLS memory allocation size %ld\n", size); */ }
return EAS_ERROR_MALLOC_FAILED;
}
EAS_HWMemSet(dls.pDLS, 0, size);
dls.pDLS->refCount = 1;
p = PtrOfs(dls.pDLS, sizeof(S_EAS));
/* setup pointer to programs */
dls.pDLS->numDLSPrograms = (EAS_U16) dls.instCount;
dls.pDLS->pDLSPrograms = p;
p = PtrOfs(p, instSize);
/* setup pointer to regions */
dls.pDLS->pDLSRegions = p;
dls.pDLS->numDLSRegions = (EAS_U16) dls.regionCount;
p = PtrOfs(p, rgnPoolSize);
/* setup pointer to articulations */
dls.pDLS->numDLSArticulations = (EAS_U16) dls.artCount;
dls.pDLS->pDLSArticulations = p;
p = PtrOfs(p, artPoolSize);
/* setup pointer to wave length table */
dls.pDLS->numDLSSamples = (EAS_U16) dls.waveCount;
dls.pDLS->pDLSSampleLen = p;
p = PtrOfs(p, waveLenSize);
/* setup pointer to wave offsets table */
dls.pDLS->pDLSSampleOffsets = p;
p = PtrOfs(p, waveLenSize);
/* setup pointer to wave pool */
dls.pDLS->pDLSSamples = p;
/* clear filter flag */
dls.filterUsed = EAS_FALSE;
/* parse the wave pool and load samples */
result = Parse_ptbl(&dls, ptblPos, wvplPos, wvplSize);
}
/* create the default articulation */
Convert_art(&dls, &defaultArt, 0);
dls.artCount = 1;
/* parse the lins chunk and load instruments */
dls.regionCount = dls.instCount = 0;
if (result == EAS_SUCCESS)
result = Parse_lins(&dls, linsPos, linsSize);
/* clean up any temporary objects that were allocated */
if (dls.wsmpData)
EAS_HWFree(dls.hwInstData, dls.wsmpData);
/* if successful, return a pointer to the EAS collection */
if (result == EAS_SUCCESS)
{
*ppDLS = dls.pDLS;
#ifdef _DEBUG_DLS
DumpDLS(dls.pDLS);
#endif
}
/* something went wrong, deallocate the EAS collection */
else
DLSCleanup(dls.hwInstData, dls.pDLS);
return result;
}
|
CWE-284
| 187,434 | 8,066 |
129549297689813421984121922695354944074
| null | null | null |
Android
|
7109ce3f8f90a28ca9f0ee6e14f6ac5e414c62cf
| 1 |
WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
/* ! */
dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle);
WORD32 i4_err_status = 0;
UWORD8 *pu1_buf = NULL;
WORD32 buflen;
UWORD32 u4_max_ofst, u4_length_of_start_code = 0;
UWORD32 bytes_consumed = 0;
UWORD32 cur_slice_is_nonref = 0;
UWORD32 u4_next_is_aud;
UWORD32 u4_first_start_code_found = 0;
WORD32 ret = 0,api_ret_value = IV_SUCCESS;
WORD32 header_data_left = 0,frame_data_left = 0;
UWORD8 *pu1_bitstrm_buf;
ivd_video_decode_ip_t *ps_dec_ip;
ivd_video_decode_op_t *ps_dec_op;
ithread_set_name((void*)"Parse_thread");
ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip;
ps_dec_op = (ivd_video_decode_op_t *)pv_api_op;
{
UWORD32 u4_size;
u4_size = ps_dec_op->u4_size;
memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t));
ps_dec_op->u4_size = u4_size;
}
ps_dec->pv_dec_out = ps_dec_op;
if(ps_dec->init_done != 1)
{
return IV_FAIL;
}
/*Data memory barries instruction,so that bitstream write by the application is complete*/
DATA_SYNC();
if(0 == ps_dec->u1_flushfrm)
{
if(ps_dec_ip->pv_stream_buffer == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL;
return IV_FAIL;
}
if(ps_dec_ip->u4_num_Bytes <= 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV;
return IV_FAIL;
}
}
ps_dec->u1_pic_decode_done = 0;
ps_dec_op->u4_num_bytes_consumed = 0;
ps_dec->ps_out_buffer = NULL;
if(ps_dec_ip->u4_size
>= offsetof(ivd_video_decode_ip_t, s_out_buffer))
ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer;
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 0;
ps_dec->s_disp_op.u4_error_code = 1;
ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS;
if(0 == ps_dec->u4_share_disp_buf
&& ps_dec->i4_decode_header == 0)
{
UWORD32 i;
if(ps_dec->ps_out_buffer->u4_num_bufs == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS;
return IV_FAIL;
}
for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++)
{
if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL;
return IV_FAIL;
}
if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |=
IVD_DISP_FRM_ZERO_OP_BUF_SIZE;
return IV_FAIL;
}
}
}
if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT)
{
ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER;
return IV_FAIL;
}
/* ! */
ps_dec->u4_ts = ps_dec_ip->u4_ts;
ps_dec_op->u4_error_code = 0;
ps_dec_op->e_pic_type = -1;
ps_dec_op->u4_output_present = 0;
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec->i4_frametype = -1;
ps_dec->i4_content_type = -1;
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
{
if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded)
{
ps_dec->u1_top_bottom_decoded = 0;
}
}
ps_dec->u4_slice_start_code_found = 0;
/* In case the deocder is not in flush mode(in shared mode),
then decoder has to pick up a buffer to write current frame.
Check if a frame is available in such cases */
if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1
&& ps_dec->u1_flushfrm == 0)
{
UWORD32 i;
WORD32 disp_avail = 0, free_id;
/* Check if at least one buffer is available with the codec */
/* If not then return to application with error */
for(i = 0; i < ps_dec->u1_pic_bufs; i++)
{
if(0 == ps_dec->u4_disp_buf_mapping[i]
|| 1 == ps_dec->u4_disp_buf_to_be_freed[i])
{
disp_avail = 1;
break;
}
}
if(0 == disp_avail)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
while(1)
{
pic_buffer_t *ps_pic_buf;
ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id);
if(ps_pic_buf == NULL)
{
UWORD32 i, display_queued = 0;
/* check if any buffer was given for display which is not returned yet */
for(i = 0; i < (MAX_DISP_BUFS_NEW); i++)
{
if(0 != ps_dec->u4_disp_buf_mapping[i])
{
display_queued = 1;
break;
}
}
/* If some buffer is queued for display, then codec has to singal an error and wait
for that buffer to be returned.
If nothing is queued for display then codec has ownership of all display buffers
and it can reuse any of the existing buffers and continue decoding */
if(1 == display_queued)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
}
else
{
/* If the buffer is with display, then mark it as in use and then look for a buffer again */
if(1 == ps_dec->u4_disp_buf_mapping[free_id])
{
ih264_buf_mgr_set_status(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
}
else
{
/**
* Found a free buffer for present call. Release it now.
* Will be again obtained later.
*/
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
break;
}
}
}
}
if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
ps_dec->u4_output_present = 1;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
ps_dec_op->u4_new_seq = 0;
ps_dec_op->u4_output_present = ps_dec->u4_output_present;
ps_dec_op->u4_progressive_frame_flag =
ps_dec->s_disp_op.u4_progressive_frame_flag;
ps_dec_op->e_output_format =
ps_dec->s_disp_op.e_output_format;
ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf;
ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type;
ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts;
ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id;
/*In the case of flush ,since no frame is decoded set pic type as invalid*/
ps_dec_op->u4_is_ref_flag = -1;
ps_dec_op->e_pic_type = IV_NA_FRAME;
ps_dec_op->u4_frame_decoded_flag = 0;
if(0 == ps_dec->s_disp_op.u4_error_code)
{
return (IV_SUCCESS);
}
else
return (IV_FAIL);
}
if(ps_dec->u1_res_changed == 1)
{
/*if resolution has changed and all buffers have been flushed, reset decoder*/
ih264d_init_decoder(ps_dec);
}
ps_dec->u4_prev_nal_skipped = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->u2_total_mbs_coded = 0;
ps_dec->u2_cur_slice_num = 0;
ps_dec->cur_dec_mb_num = 0;
ps_dec->cur_recon_mb_num = 0;
ps_dec->u4_first_slice_in_pic = 2;
ps_dec->u1_first_pb_nal_in_pic = 1;
ps_dec->u1_slice_header_done = 0;
ps_dec->u1_dangling_field = 0;
ps_dec->u4_dec_thread_created = 0;
ps_dec->u4_bs_deblk_thread_created = 0;
ps_dec->u4_cur_bs_mb_num = 0;
ps_dec->u4_start_recon_deblk = 0;
DEBUG_THREADS_PRINTF(" Starting process call\n");
ps_dec->u4_pic_buf_got = 0;
do
{
WORD32 buf_size;
pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer
+ ps_dec_op->u4_num_bytes_consumed;
u4_max_ofst = ps_dec_ip->u4_num_Bytes
- ps_dec_op->u4_num_bytes_consumed;
/* If dynamic bitstream buffer is not allocated and
* header decode is done, then allocate dynamic bitstream buffer
*/
if((NULL == ps_dec->pu1_bits_buf_dynamic) &&
(ps_dec->i4_header_decoded & 1))
{
WORD32 size;
void *pv_buf;
void *pv_mem_ctxt = ps_dec->pv_mem_ctxt;
size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2);
pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pu1_bits_buf_dynamic = pv_buf;
ps_dec->u4_dynamic_bits_buf_size = size;
}
if(ps_dec->pu1_bits_buf_dynamic)
{
pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic;
buf_size = ps_dec->u4_dynamic_bits_buf_size;
}
else
{
pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static;
buf_size = ps_dec->u4_static_bits_buf_size;
}
u4_next_is_aud = 0;
buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst,
&u4_length_of_start_code,
&u4_next_is_aud);
if(buflen == -1)
buflen = 0;
/* Ignore bytes beyond the allocated size of intermediate buffer */
buflen = MIN(buflen, buf_size);
bytes_consumed = buflen + u4_length_of_start_code;
ps_dec_op->u4_num_bytes_consumed += bytes_consumed;
{
UWORD8 u1_firstbyte, u1_nal_ref_idc;
if(ps_dec->i4_app_skip_mode == IVD_SKIP_B)
{
u1_firstbyte = *(pu1_buf + u4_length_of_start_code);
u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte));
if(u1_nal_ref_idc == 0)
{
/*skip non reference frames*/
cur_slice_is_nonref = 1;
continue;
}
else
{
if(1 == cur_slice_is_nonref)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -=
bytes_consumed;
ps_dec_op->e_pic_type = IV_B_FRAME;
ps_dec_op->u4_error_code =
IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size =
sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
}
}
}
if(buflen)
{
memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code,
buflen);
/* Decoder may read extra 8 bytes near end of the frame */
if((buflen + 8) < buf_size)
{
memset(pu1_bitstrm_buf + buflen, 0, 8);
}
u4_first_start_code_found = 1;
}
else
{
/*start code not found*/
if(u4_first_start_code_found == 0)
{
/*no start codes found in current process call*/
ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND;
ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA;
if(ps_dec->u4_pic_buf_got == 0)
{
ih264d_fill_output_struct_from_context(ps_dec,
ps_dec_op);
ps_dec_op->u4_error_code = ps_dec->i4_error_code;
ps_dec_op->u4_frame_decoded_flag = 0;
return (IV_FAIL);
}
else
{
ps_dec->u1_pic_decode_done = 1;
continue;
}
}
else
{
/* a start code has already been found earlier in the same process call*/
frame_data_left = 0;
continue;
}
}
ps_dec->u4_return_to_app = 0;
ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op,
pu1_bitstrm_buf, buflen);
if(ret != OK)
{
UWORD32 error = ih264d_map_error(ret);
ps_dec_op->u4_error_code = error | ret;
api_ret_value = IV_FAIL;
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_MEM_ALLOC_FAILED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T)
|| (ret == ERROR_INV_SPS_PPS_T))
{
ps_dec->u4_slice_start_code_found = 0;
break;
}
if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC))
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
api_ret_value = IV_FAIL;
break;
}
if(ret == ERROR_IN_LAST_SLICE_OF_PIC)
{
api_ret_value = IV_FAIL;
break;
}
}
if(ps_dec->u4_return_to_app)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
header_data_left = ((ps_dec->i4_decode_header == 1)
&& (ps_dec->i4_header_decoded != 3)
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
frame_data_left = (((ps_dec->i4_decode_header == 0)
&& ((ps_dec->u1_pic_decode_done == 0)
|| (u4_next_is_aud == 1)))
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
}
while(( header_data_left == 1)||(frame_data_left == 1));
if((ps_dec->u4_slice_start_code_found == 1)
&& (ret != IVD_MEM_ALLOC_FAILED)
&& ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
WORD32 num_mb_skipped;
WORD32 prev_slice_err;
pocstruct_t temp_poc;
WORD32 ret1;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0))
prev_slice_err = 1;
else
prev_slice_err = 2;
ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num,
&temp_poc, prev_slice_err);
if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T))
{
return IV_FAIL;
}
}
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_MEM_ALLOC_FAILED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T)
|| (ret == ERROR_INV_SPS_PPS_T))
{
/* signal the decode thread */
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet */
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
/* dont consume bitstream for change in resolution case */
if(ret == IVD_RES_CHANGED)
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
}
return IV_FAIL;
}
if(ps_dec->u1_separate_parse)
{
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_num_cores == 2)
{
/*do deblocking of all mbs*/
if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0))
{
UWORD32 u4_num_mbs,u4_max_addr;
tfr_ctxt_t s_tfr_ctxt;
tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt;
pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr;
/*BS is done for all mbs while parsing*/
u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1;
ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1;
ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt,
ps_dec->u2_frm_wd_in_mbs, 0);
u4_num_mbs = u4_max_addr
- ps_dec->u4_cur_deblk_mb_num + 1;
DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs);
if(u4_num_mbs != 0)
ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs,
ps_tfr_cxt,1);
ps_dec->u4_start_recon_deblk = 0;
}
}
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
}
DATA_SYNC();
if((ps_dec_op->u4_error_code & 0xff)
!= ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED)
{
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
}
if(ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->u4_prev_nal_skipped)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
if((ps_dec->u4_slice_start_code_found == 1)
&& (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status))
{
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
if(ps_dec->ps_cur_slice->u1_field_pic_flag)
{
if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag)
{
ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY;
}
else
{
ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY;
}
}
/* if new frame in not found (if we are still getting slices from previous frame)
* ih264d_deblock_display is not called. Such frames will not be added to reference /display
*/
if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)
{
/* Calling Function to deblock Picture and Display */
ret = ih264d_deblock_display(ps_dec);
if(ret != 0)
{
return IV_FAIL;
}
}
/*set to complete ,as we dont support partial frame decode*/
if(ps_dec->i4_header_decoded == 3)
{
ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1;
}
/*Update the i4_frametype at the end of picture*/
if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_dec->i4_frametype = IV_IDR_FRAME;
}
else if(ps_dec->i4_pic_type == B_SLICE)
{
ps_dec->i4_frametype = IV_B_FRAME;
}
else if(ps_dec->i4_pic_type == P_SLICE)
{
ps_dec->i4_frametype = IV_P_FRAME;
}
else if(ps_dec->i4_pic_type == I_SLICE)
{
ps_dec->i4_frametype = IV_I_FRAME;
}
else
{
H264_DEC_DEBUG_PRINT("Shouldn't come here\n");
}
ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded
- ps_dec->ps_cur_slice->u1_field_pic_flag;
}
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
{
/* In case the decoder is configured to run in low delay mode,
* then get display buffer and then format convert.
* Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles
*/
if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode)
&& ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 1;
}
}
ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op);
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_output_present &&
(ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht))
{
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht
- ps_dec->u4_fmt_conv_cur_row;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
}
if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1)
{
ps_dec_op->u4_progressive_frame_flag = 1;
if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid)))
{
if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag)
&& (0 == ps_dec->ps_sps->u1_mb_aff_flag))
ps_dec_op->u4_progressive_frame_flag = 0;
}
}
/*Data memory barrier instruction,so that yuv write by the library is complete*/
DATA_SYNC();
H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n",
ps_dec_op->u4_num_bytes_consumed);
return api_ret_value;
}
|
CWE-284
| 187,435 | 8,067 |
176342596394453705442305320854815243280
| null | null | null |
Android
|
9f9ba255a0c59544f3555c9c45512c3a2fac5fad
| 1 |
bool SoftVPX::outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader) {
uint32_t width = outputBufferWidth();
uint32_t height = outputBufferHeight();
uint64_t nFilledLen = width;
nFilledLen *= height;
if (nFilledLen > UINT32_MAX / 3) {
ALOGE("b/29421675, nFilledLen overflow %llu w %u h %u", nFilledLen, width, height);
android_errorWriteLog(0x534e4554, "29421675");
return false;
} else if (outHeader->nAllocLen < outHeader->nFilledLen) {
ALOGE("b/27597103, buffer too small");
android_errorWriteLog(0x534e4554, "27597103");
return false;
}
return true;
}
|
CWE-119
| 187,436 | 8,068 |
66696249750732110228447481250024311595
| null | null | null |
Android
|
c2639afac631f5c1ffddf70ee8a6fe943d0bedf9
| 1 |
void SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) {
BufferInfo *inInfo = NULL;
OMX_BUFFERHEADERTYPE *inHeader = NULL;
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
if (inHeader) {
if (inHeader->nOffset == 0 && inHeader->nFilledLen) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEos = true;
}
mConfig->pInputBuffer =
inHeader->pBuffer + inHeader->nOffset;
mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
} else {
mConfig->pInputBuffer = NULL;
mConfig->inputBufferCurrentLength = 0;
}
mConfig->inputBufferMaxLength = 0;
mConfig->inputBufferUsedLength = 0;
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
if ((int32)outHeader->nAllocLen < mConfig->outputFrameSize) {
ALOGE("input buffer too small: got %u, expected %u",
outHeader->nAllocLen, mConfig->outputFrameSize);
android_errorWriteLog(0x534e4554, "27793371");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return;
}
mConfig->pOutputBuffer =
reinterpret_cast<int16_t *>(outHeader->pBuffer);
ERROR_CODE decoderErr;
if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
!= NO_DECODING_ERROR) {
ALOGV("mp3 decoder returned error %d", decoderErr);
if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
&& decoderErr != SIDE_INFO_ERROR) {
ALOGE("mp3 decoder returned error %d", decoderErr);
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
mSignalledError = true;
return;
}
if (mConfig->outputFrameSize == 0) {
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
}
if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) {
if (!mIsFirst) {
outHeader->nOffset = 0;
outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
memset(outHeader->pBuffer, 0, outHeader->nFilledLen);
}
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mSignalledOutputEos = true;
} else {
ALOGV_IF(mIsFirst, "insufficient data for first frame, sending silence");
memset(outHeader->pBuffer,
0,
mConfig->outputFrameSize * sizeof(int16_t));
if (inHeader) {
mConfig->inputBufferUsedLength = inHeader->nFilledLen;
}
}
} else if (mConfig->samplingRate != mSamplingRate
|| mConfig->num_channels != mNumChannels) {
mSamplingRate = mConfig->samplingRate;
mNumChannels = mConfig->num_channels;
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
return;
}
if (mIsFirst) {
mIsFirst = false;
outHeader->nOffset =
kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
outHeader->nFilledLen =
mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
} else if (!mSignalledOutputEos) {
outHeader->nOffset = 0;
outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
}
outHeader->nTimeStamp =
mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
if (inHeader) {
CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
inHeader->nOffset += mConfig->inputBufferUsedLength;
inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
|
CWE-264
| 187,437 | 8,069 |
154590744829326919130524818637563682639
| null | null | null |
Android
|
1e9801783770917728b7edbdeff3d0ec09c621ac
| 1 |
void SimpleSoftOMXComponent::onPortEnable(OMX_U32 portIndex, bool enable) {
CHECK_LT(portIndex, mPorts.size());
PortInfo *port = &mPorts.editItemAt(portIndex);
CHECK_EQ((int)port->mTransition, (int)PortInfo::NONE);
CHECK(port->mDef.bEnabled == !enable);
if (!enable) {
port->mDef.bEnabled = OMX_FALSE;
port->mTransition = PortInfo::DISABLING;
for (size_t i = 0; i < port->mBuffers.size(); ++i) {
BufferInfo *buffer = &port->mBuffers.editItemAt(i);
if (buffer->mOwnedByUs) {
buffer->mOwnedByUs = false;
if (port->mDef.eDir == OMX_DirInput) {
notifyEmptyBufferDone(buffer->mHeader);
} else {
CHECK_EQ(port->mDef.eDir, OMX_DirOutput);
notifyFillBufferDone(buffer->mHeader);
}
}
}
port->mQueue.clear();
} else {
port->mTransition = PortInfo::ENABLING;
}
checkTransitions();
}
|
CWE-264
| 187,438 | 8,070 |
11372754031162218971713245718333467565
| null | null | null |
Android
|
a209ff12ba9617c10550678ff93d01fb72a33399
| 1 |
static byte parseHexByte(const char * &str) {
byte b = parseHexChar(str[0]);
if (str[1] == ':' || str[1] == '\0') {
str += 2;
return b;
} else {
b = b << 4 | parseHexChar(str[1]);
str += 3;
return b;
}
}
|
CWE-200
| 187,522 | 8,144 |
286529297307740120949187079802454666188
| null | null | null |
Android
|
8e438e153f661e9df8db0ac41d587e940352df06
| 1 |
void SoftAAC2::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
UCHAR* inBuffer[FILEREAD_MAX_LAYERS];
UINT inBufferLength[FILEREAD_MAX_LAYERS] = {0};
UINT bytesValid[FILEREAD_MAX_LAYERS] = {0};
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || mEndOfInput) && !outQueue.empty()) {
if (!inQueue.empty()) {
INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT];
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
mEndOfInput = (inHeader->nFlags & OMX_BUFFERFLAG_EOS) != 0;
if (mInputBufferCount == 0 && !(inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG)) {
ALOGE("first buffer should have OMX_BUFFERFLAG_CODECCONFIG set");
inHeader->nFlags |= OMX_BUFFERFLAG_CODECCONFIG;
}
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) != 0) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
inBuffer[0] = inHeader->pBuffer + inHeader->nOffset;
inBufferLength[0] = inHeader->nFilledLen;
AAC_DECODER_ERROR decoderErr =
aacDecoder_ConfigRaw(mAACDecoder,
inBuffer,
inBufferLength);
if (decoderErr != AAC_DEC_OK) {
ALOGW("aacDecoder_ConfigRaw decoderErr = 0x%4.4x", decoderErr);
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
mInputBufferCount++;
mOutputBufferCount++; // fake increase of outputBufferCount to keep the counters aligned
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
configureDownmix();
if (mStreamInfo->sampleRate && mStreamInfo->numChannels) {
ALOGI("Initially configuring decoder: %d Hz, %d channels",
mStreamInfo->sampleRate,
mStreamInfo->numChannels);
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
}
return;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
continue;
}
if (mIsADTS) {
size_t adtsHeaderSize = 0;
const uint8_t *adtsHeader = inHeader->pBuffer + inHeader->nOffset;
bool signalError = false;
if (inHeader->nFilledLen < 7) {
ALOGE("Audio data too short to contain even the ADTS header. "
"Got %d bytes.", inHeader->nFilledLen);
hexdump(adtsHeader, inHeader->nFilledLen);
signalError = true;
} else {
bool protectionAbsent = (adtsHeader[1] & 1);
unsigned aac_frame_length =
((adtsHeader[3] & 3) << 11)
| (adtsHeader[4] << 3)
| (adtsHeader[5] >> 5);
if (inHeader->nFilledLen < aac_frame_length) {
ALOGE("Not enough audio data for the complete frame. "
"Got %d bytes, frame size according to the ADTS "
"header is %u bytes.",
inHeader->nFilledLen, aac_frame_length);
hexdump(adtsHeader, inHeader->nFilledLen);
signalError = true;
} else {
adtsHeaderSize = (protectionAbsent ? 7 : 9);
inBuffer[0] = (UCHAR *)adtsHeader + adtsHeaderSize;
inBufferLength[0] = aac_frame_length - adtsHeaderSize;
inHeader->nOffset += adtsHeaderSize;
inHeader->nFilledLen -= adtsHeaderSize;
}
}
if (signalError) {
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorStreamCorrupt, ERROR_MALFORMED, NULL);
return;
}
mBufferSizes.add(inBufferLength[0]);
if (mLastInHeader != inHeader) {
mBufferTimestamps.add(inHeader->nTimeStamp);
mLastInHeader = inHeader;
} else {
int64_t currentTime = mBufferTimestamps.top();
currentTime += mStreamInfo->aacSamplesPerFrame *
1000000ll / mStreamInfo->aacSampleRate;
mBufferTimestamps.add(currentTime);
}
} else {
inBuffer[0] = inHeader->pBuffer + inHeader->nOffset;
inBufferLength[0] = inHeader->nFilledLen;
mLastInHeader = inHeader;
mBufferTimestamps.add(inHeader->nTimeStamp);
mBufferSizes.add(inHeader->nFilledLen);
}
bytesValid[0] = inBufferLength[0];
INT prevSampleRate = mStreamInfo->sampleRate;
INT prevNumChannels = mStreamInfo->numChannels;
aacDecoder_Fill(mAACDecoder,
inBuffer,
inBufferLength,
bytesValid);
mDrcWrap.submitStreamData(mStreamInfo);
mDrcWrap.update();
UINT inBufferUsedLength = inBufferLength[0] - bytesValid[0];
inHeader->nFilledLen -= inBufferUsedLength;
inHeader->nOffset += inBufferUsedLength;
AAC_DECODER_ERROR decoderErr;
int numLoops = 0;
do {
if (outputDelayRingBufferSpaceLeft() <
(mStreamInfo->frameSize * mStreamInfo->numChannels)) {
ALOGV("skipping decode: not enough space left in ringbuffer");
break;
}
int numConsumed = mStreamInfo->numTotalBytes;
decoderErr = aacDecoder_DecodeFrame(mAACDecoder,
tmpOutBuffer,
2048 * MAX_CHANNEL_COUNT,
0 /* flags */);
numConsumed = mStreamInfo->numTotalBytes - numConsumed;
numLoops++;
if (decoderErr == AAC_DEC_NOT_ENOUGH_BITS) {
break;
}
mDecodedSizes.add(numConsumed);
if (decoderErr != AAC_DEC_OK) {
ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr);
}
if (bytesValid[0] != 0) {
ALOGE("bytesValid[0] != 0 should never happen");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
size_t numOutBytes =
mStreamInfo->frameSize * sizeof(int16_t) * mStreamInfo->numChannels;
if (decoderErr == AAC_DEC_OK) {
if (!outputDelayRingBufferPutSamples(tmpOutBuffer,
mStreamInfo->frameSize * mStreamInfo->numChannels)) {
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
} else {
ALOGW("AAC decoder returned error 0x%4.4x, substituting silence", decoderErr);
memset(tmpOutBuffer, 0, numOutBytes); // TODO: check for overflow
if (!outputDelayRingBufferPutSamples(tmpOutBuffer,
mStreamInfo->frameSize * mStreamInfo->numChannels)) {
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
if (inHeader) {
inHeader->nFilledLen = 0;
}
aacDecoder_SetParam(mAACDecoder, AAC_TPDEC_CLEAR_BUFFER, 1);
mBufferSizes.pop();
int n = 0;
for (int i = 0; i < numLoops; i++) {
n += mDecodedSizes.itemAt(mDecodedSizes.size() - numLoops + i);
}
mBufferSizes.add(n);
}
/*
* AAC+/eAAC+ streams can be signalled in two ways: either explicitly
* or implicitly, according to MPEG4 spec. AAC+/eAAC+ is a dual
* rate system and the sampling rate in the final output is actually
* doubled compared with the core AAC decoder sampling rate.
*
* Explicit signalling is done by explicitly defining SBR audio object
* type in the bitstream. Implicit signalling is done by embedding
* SBR content in AAC extension payload specific to SBR, and hence
* requires an AAC decoder to perform pre-checks on actual audio frames.
*
* Thus, we could not say for sure whether a stream is
* AAC+/eAAC+ until the first data frame is decoded.
*/
if (mInputBufferCount <= 2 || mOutputBufferCount > 1) { // TODO: <= 1
if (mStreamInfo->sampleRate != prevSampleRate ||
mStreamInfo->numChannels != prevNumChannels) {
ALOGI("Reconfiguring decoder: %d->%d Hz, %d->%d channels",
prevSampleRate, mStreamInfo->sampleRate,
prevNumChannels, mStreamInfo->numChannels);
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
if (inHeader && inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
mInputBufferCount++;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
return;
}
} else if (!mStreamInfo->sampleRate || !mStreamInfo->numChannels) {
ALOGW("Invalid AAC stream");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
if (inHeader && inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
mInputBufferCount++;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else {
ALOGV("inHeader->nFilledLen = %d", inHeader ? inHeader->nFilledLen : 0);
}
} while (decoderErr == AAC_DEC_OK);
}
int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels;
if (!mEndOfInput && mOutputDelayCompensated < outputDelay) {
int32_t toCompensate = outputDelay - mOutputDelayCompensated;
int32_t discard = outputDelayRingBufferSamplesAvailable();
if (discard > toCompensate) {
discard = toCompensate;
}
int32_t discarded = outputDelayRingBufferGetSamples(0, discard);
mOutputDelayCompensated += discarded;
continue;
}
if (mEndOfInput) {
while (mOutputDelayCompensated > 0) {
INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT];
mDrcWrap.submitStreamData(mStreamInfo);
mDrcWrap.update();
AAC_DECODER_ERROR decoderErr =
aacDecoder_DecodeFrame(mAACDecoder,
tmpOutBuffer,
2048 * MAX_CHANNEL_COUNT,
AACDEC_FLUSH);
if (decoderErr != AAC_DEC_OK) {
ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr);
}
int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels;
if (tmpOutBufferSamples > mOutputDelayCompensated) {
tmpOutBufferSamples = mOutputDelayCompensated;
}
outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples);
mOutputDelayCompensated -= tmpOutBufferSamples;
}
}
while (!outQueue.empty()
&& outputDelayRingBufferSamplesAvailable()
>= mStreamInfo->frameSize * mStreamInfo->numChannels) {
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (outHeader->nOffset != 0) {
ALOGE("outHeader->nOffset != 0 is not handled");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
INT_PCM *outBuffer =
reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset);
int samplesize = mStreamInfo->numChannels * sizeof(int16_t);
if (outHeader->nOffset
+ mStreamInfo->frameSize * samplesize
> outHeader->nAllocLen) {
ALOGE("buffer overflow");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
int available = outputDelayRingBufferSamplesAvailable();
int numSamples = outHeader->nAllocLen / sizeof(int16_t);
if (numSamples > available) {
numSamples = available;
}
int64_t currentTime = 0;
if (available) {
int numFrames = numSamples / (mStreamInfo->frameSize * mStreamInfo->numChannels);
numSamples = numFrames * (mStreamInfo->frameSize * mStreamInfo->numChannels);
ALOGV("%d samples available (%d), or %d frames",
numSamples, available, numFrames);
int64_t *nextTimeStamp = &mBufferTimestamps.editItemAt(0);
currentTime = *nextTimeStamp;
int32_t *currentBufLeft = &mBufferSizes.editItemAt(0);
for (int i = 0; i < numFrames; i++) {
int32_t decodedSize = mDecodedSizes.itemAt(0);
mDecodedSizes.removeAt(0);
ALOGV("decoded %d of %d", decodedSize, *currentBufLeft);
if (*currentBufLeft > decodedSize) {
*currentBufLeft -= decodedSize;
*nextTimeStamp += mStreamInfo->aacSamplesPerFrame *
1000000ll / mStreamInfo->aacSampleRate;
ALOGV("adjusted nextTimeStamp/size to %lld/%d",
(long long) *nextTimeStamp, *currentBufLeft);
} else {
if (mBufferTimestamps.size() > 0) {
mBufferTimestamps.removeAt(0);
nextTimeStamp = &mBufferTimestamps.editItemAt(0);
mBufferSizes.removeAt(0);
currentBufLeft = &mBufferSizes.editItemAt(0);
ALOGV("moved to next time/size: %lld/%d",
(long long) *nextTimeStamp, *currentBufLeft);
}
numFrames = i + 1;
numSamples = numFrames * mStreamInfo->frameSize * mStreamInfo->numChannels;
break;
}
}
ALOGV("getting %d from ringbuffer", numSamples);
int32_t ns = outputDelayRingBufferGetSamples(outBuffer, numSamples);
if (ns != numSamples) {
ALOGE("not a complete frame of samples available");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
}
outHeader->nFilledLen = numSamples * sizeof(int16_t);
if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mEndOfOutput = true;
} else {
outHeader->nFlags = 0;
}
outHeader->nTimeStamp = currentTime;
mOutputBufferCount++;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
ALOGV("out timestamp %lld / %d", outHeader->nTimeStamp, outHeader->nFilledLen);
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
if (mEndOfInput) {
int ringBufAvail = outputDelayRingBufferSamplesAvailable();
if (!outQueue.empty()
&& ringBufAvail < mStreamInfo->frameSize * mStreamInfo->numChannels) {
if (!mEndOfOutput) {
mEndOfOutput = true;
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(outHeader->pBuffer
+ outHeader->nOffset);
int32_t ns = outputDelayRingBufferGetSamples(outBuffer, ringBufAvail);
if (ns < 0) {
ns = 0;
}
outHeader->nFilledLen = ns;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outHeader->nTimeStamp = mBufferTimestamps.itemAt(0);
mBufferTimestamps.clear();
mBufferSizes.clear();
mDecodedSizes.clear();
mOutputBufferCount++;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
break; // if outQueue not empty but no more output
}
}
}
}
|
CWE-20
| 187,535 | 8,156 |
260137757108904583233377798845934464620
| null | null | null |
Android
|
7554755536019e439433c515eeb44e701fb3bfb2
| 1 |
WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
/* ! */
dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle);
WORD32 i4_err_status = 0;
UWORD8 *pu1_buf = NULL;
WORD32 buflen;
UWORD32 u4_max_ofst, u4_length_of_start_code = 0;
UWORD32 bytes_consumed = 0;
UWORD32 cur_slice_is_nonref = 0;
UWORD32 u4_next_is_aud;
UWORD32 u4_first_start_code_found = 0;
WORD32 ret = 0,api_ret_value = IV_SUCCESS;
WORD32 header_data_left = 0,frame_data_left = 0;
UWORD8 *pu1_bitstrm_buf;
ivd_video_decode_ip_t *ps_dec_ip;
ivd_video_decode_op_t *ps_dec_op;
ithread_set_name((void*)"Parse_thread");
ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip;
ps_dec_op = (ivd_video_decode_op_t *)pv_api_op;
{
UWORD32 u4_size;
u4_size = ps_dec_op->u4_size;
memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t));
ps_dec_op->u4_size = u4_size;
}
ps_dec->pv_dec_out = ps_dec_op;
if(ps_dec->init_done != 1)
{
return IV_FAIL;
}
/*Data memory barries instruction,so that bitstream write by the application is complete*/
DATA_SYNC();
if(0 == ps_dec->u1_flushfrm)
{
if(ps_dec_ip->pv_stream_buffer == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL;
return IV_FAIL;
}
if(ps_dec_ip->u4_num_Bytes <= 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV;
return IV_FAIL;
}
}
ps_dec->u1_pic_decode_done = 0;
ps_dec_op->u4_num_bytes_consumed = 0;
ps_dec->ps_out_buffer = NULL;
if(ps_dec_ip->u4_size
>= offsetof(ivd_video_decode_ip_t, s_out_buffer))
ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer;
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 0;
ps_dec->s_disp_op.u4_error_code = 1;
ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS;
if(0 == ps_dec->u4_share_disp_buf
&& ps_dec->i4_decode_header == 0)
{
UWORD32 i;
if(ps_dec->ps_out_buffer->u4_num_bufs == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS;
return IV_FAIL;
}
for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++)
{
if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL;
return IV_FAIL;
}
if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0)
{
ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->u4_error_code |=
IVD_DISP_FRM_ZERO_OP_BUF_SIZE;
return IV_FAIL;
}
}
}
if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT)
{
ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER;
return IV_FAIL;
}
/* ! */
ps_dec->u4_ts = ps_dec_ip->u4_ts;
ps_dec_op->u4_error_code = 0;
ps_dec_op->e_pic_type = -1;
ps_dec_op->u4_output_present = 0;
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec->i4_frametype = -1;
ps_dec->i4_content_type = -1;
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
{
if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded)
{
ps_dec->u1_top_bottom_decoded = 0;
}
}
ps_dec->u4_slice_start_code_found = 0;
/* In case the deocder is not in flush mode(in shared mode),
then decoder has to pick up a buffer to write current frame.
Check if a frame is available in such cases */
if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1
&& ps_dec->u1_flushfrm == 0)
{
UWORD32 i;
WORD32 disp_avail = 0, free_id;
/* Check if at least one buffer is available with the codec */
/* If not then return to application with error */
for(i = 0; i < ps_dec->u1_pic_bufs; i++)
{
if(0 == ps_dec->u4_disp_buf_mapping[i]
|| 1 == ps_dec->u4_disp_buf_to_be_freed[i])
{
disp_avail = 1;
break;
}
}
if(0 == disp_avail)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
while(1)
{
pic_buffer_t *ps_pic_buf;
ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id);
if(ps_pic_buf == NULL)
{
UWORD32 i, display_queued = 0;
/* check if any buffer was given for display which is not returned yet */
for(i = 0; i < (MAX_DISP_BUFS_NEW); i++)
{
if(0 != ps_dec->u4_disp_buf_mapping[i])
{
display_queued = 1;
break;
}
}
/* If some buffer is queued for display, then codec has to singal an error and wait
for that buffer to be returned.
If nothing is queued for display then codec has ownership of all display buffers
and it can reuse any of the existing buffers and continue decoding */
if(1 == display_queued)
{
/* If something is queued for display wait for that buffer to be returned */
ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
return (IV_FAIL);
}
}
else
{
/* If the buffer is with display, then mark it as in use and then look for a buffer again */
if(1 == ps_dec->u4_disp_buf_mapping[free_id])
{
ih264_buf_mgr_set_status(
(buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
}
else
{
/**
* Found a free buffer for present call. Release it now.
* Will be again obtained later.
*/
ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr,
free_id,
BUF_MGR_IO);
break;
}
}
}
}
if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
ps_dec->u4_output_present = 1;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
ps_dec_op->u4_new_seq = 0;
ps_dec_op->u4_output_present = ps_dec->u4_output_present;
ps_dec_op->u4_progressive_frame_flag =
ps_dec->s_disp_op.u4_progressive_frame_flag;
ps_dec_op->e_output_format =
ps_dec->s_disp_op.e_output_format;
ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf;
ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type;
ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts;
ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id;
/*In the case of flush ,since no frame is decoded set pic type as invalid*/
ps_dec_op->u4_is_ref_flag = -1;
ps_dec_op->e_pic_type = IV_NA_FRAME;
ps_dec_op->u4_frame_decoded_flag = 0;
if(0 == ps_dec->s_disp_op.u4_error_code)
{
return (IV_SUCCESS);
}
else
return (IV_FAIL);
}
if(ps_dec->u1_res_changed == 1)
{
/*if resolution has changed and all buffers have been flushed, reset decoder*/
ih264d_init_decoder(ps_dec);
}
ps_dec->u4_prev_nal_skipped = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->u2_total_mbs_coded = 0;
ps_dec->u2_cur_slice_num = 0;
ps_dec->cur_dec_mb_num = 0;
ps_dec->cur_recon_mb_num = 0;
ps_dec->u4_first_slice_in_pic = 2;
ps_dec->u1_slice_header_done = 0;
ps_dec->u1_dangling_field = 0;
ps_dec->u4_dec_thread_created = 0;
ps_dec->u4_bs_deblk_thread_created = 0;
ps_dec->u4_cur_bs_mb_num = 0;
ps_dec->u4_start_recon_deblk = 0;
DEBUG_THREADS_PRINTF(" Starting process call\n");
ps_dec->u4_pic_buf_got = 0;
do
{
WORD32 buf_size;
pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer
+ ps_dec_op->u4_num_bytes_consumed;
u4_max_ofst = ps_dec_ip->u4_num_Bytes
- ps_dec_op->u4_num_bytes_consumed;
/* If dynamic bitstream buffer is not allocated and
* header decode is done, then allocate dynamic bitstream buffer
*/
if((NULL == ps_dec->pu1_bits_buf_dynamic) &&
(ps_dec->i4_header_decoded & 1))
{
WORD32 size;
void *pv_buf;
void *pv_mem_ctxt = ps_dec->pv_mem_ctxt;
size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2);
pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size);
RETURN_IF((NULL == pv_buf), IV_FAIL);
ps_dec->pu1_bits_buf_dynamic = pv_buf;
ps_dec->u4_dynamic_bits_buf_size = size;
}
if(ps_dec->pu1_bits_buf_dynamic)
{
pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic;
buf_size = ps_dec->u4_dynamic_bits_buf_size;
}
else
{
pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static;
buf_size = ps_dec->u4_static_bits_buf_size;
}
u4_next_is_aud = 0;
buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst,
&u4_length_of_start_code,
&u4_next_is_aud);
if(buflen == -1)
buflen = 0;
/* Ignore bytes beyond the allocated size of intermediate buffer */
buflen = MIN(buflen, buf_size);
bytes_consumed = buflen + u4_length_of_start_code;
ps_dec_op->u4_num_bytes_consumed += bytes_consumed;
{
UWORD8 u1_firstbyte, u1_nal_ref_idc;
if(ps_dec->i4_app_skip_mode == IVD_SKIP_B)
{
u1_firstbyte = *(pu1_buf + u4_length_of_start_code);
u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte));
if(u1_nal_ref_idc == 0)
{
/*skip non reference frames*/
cur_slice_is_nonref = 1;
continue;
}
else
{
if(1 == cur_slice_is_nonref)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -=
bytes_consumed;
ps_dec_op->e_pic_type = IV_B_FRAME;
ps_dec_op->u4_error_code =
IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1
<< IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size =
sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
}
}
}
if(buflen)
{
memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code,
buflen);
/* Decoder may read extra 8 bytes near end of the frame */
if((buflen + 8) < buf_size)
{
memset(pu1_bitstrm_buf + buflen, 0, 8);
}
u4_first_start_code_found = 1;
}
else
{
/*start code not found*/
if(u4_first_start_code_found == 0)
{
/*no start codes found in current process call*/
ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND;
ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA;
if(ps_dec->u4_pic_buf_got == 0)
{
ih264d_fill_output_struct_from_context(ps_dec,
ps_dec_op);
ps_dec_op->u4_error_code = ps_dec->i4_error_code;
ps_dec_op->u4_frame_decoded_flag = 0;
return (IV_FAIL);
}
else
{
ps_dec->u1_pic_decode_done = 1;
continue;
}
}
else
{
/* a start code has already been found earlier in the same process call*/
frame_data_left = 0;
continue;
}
}
ps_dec->u4_return_to_app = 0;
ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op,
pu1_bitstrm_buf, buflen);
if(ret != OK)
{
UWORD32 error = ih264d_map_error(ret);
ps_dec_op->u4_error_code = error | ret;
api_ret_value = IV_FAIL;
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_MEM_ALLOC_FAILED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T))
{
break;
}
if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC))
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
api_ret_value = IV_FAIL;
break;
}
if(ret == ERROR_IN_LAST_SLICE_OF_PIC)
{
api_ret_value = IV_FAIL;
break;
}
}
if(ps_dec->u4_return_to_app)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
header_data_left = ((ps_dec->i4_decode_header == 1)
&& (ps_dec->i4_header_decoded != 3)
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
frame_data_left = (((ps_dec->i4_decode_header == 0)
&& ((ps_dec->u1_pic_decode_done == 0)
|| (u4_next_is_aud == 1)))
&& (ps_dec_op->u4_num_bytes_consumed
< ps_dec_ip->u4_num_Bytes));
}
while(( header_data_left == 1)||(frame_data_left == 1));
if((ps_dec->u4_slice_start_code_found == 1)
&& (ret != IVD_MEM_ALLOC_FAILED)
&& ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
WORD32 num_mb_skipped;
WORD32 prev_slice_err;
pocstruct_t temp_poc;
WORD32 ret1;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0))
prev_slice_err = 1;
else
prev_slice_err = 2;
ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num,
&temp_poc, prev_slice_err);
if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T))
{
return IV_FAIL;
}
}
if((ret == IVD_RES_CHANGED)
|| (ret == IVD_MEM_ALLOC_FAILED)
|| (ret == ERROR_UNAVAIL_PICBUF_T)
|| (ret == ERROR_UNAVAIL_MVBUF_T))
{
/* signal the decode thread */
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet */
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
/* dont consume bitstream for change in resolution case */
if(ret == IVD_RES_CHANGED)
{
ps_dec_op->u4_num_bytes_consumed -= bytes_consumed;
}
return IV_FAIL;
}
if(ps_dec->u1_separate_parse)
{
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_num_cores == 2)
{
/*do deblocking of all mbs*/
if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0))
{
UWORD32 u4_num_mbs,u4_max_addr;
tfr_ctxt_t s_tfr_ctxt;
tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt;
pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr;
/*BS is done for all mbs while parsing*/
u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1;
ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1;
ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt,
ps_dec->u2_frm_wd_in_mbs, 0);
u4_num_mbs = u4_max_addr
- ps_dec->u4_cur_deblk_mb_num + 1;
DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs);
if(u4_num_mbs != 0)
ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs,
ps_tfr_cxt,1);
ps_dec->u4_start_recon_deblk = 0;
}
}
/*signal the decode thread*/
ih264d_signal_decode_thread(ps_dec);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
}
DATA_SYNC();
if((ps_dec_op->u4_error_code & 0xff)
!= ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED)
{
ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width;
ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height;
}
if(ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3)
{
ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA);
}
if(ps_dec->u4_prev_nal_skipped)
{
/*We have encountered a referenced frame,return to app*/
ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED;
ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM);
ps_dec_op->u4_frame_decoded_flag = 0;
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
return (IV_FAIL);
}
if((ps_dec->u4_slice_start_code_found == 1)
&& (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status))
{
/*
* For field pictures, set the bottom and top picture decoded u4_flag correctly.
*/
if(ps_dec->ps_cur_slice->u1_field_pic_flag)
{
if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag)
{
ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY;
}
else
{
ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY;
}
}
/* if new frame in not found (if we are still getting slices from previous frame)
* ih264d_deblock_display is not called. Such frames will not be added to reference /display
*/
if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)
{
/* Calling Function to deblock Picture and Display */
ret = ih264d_deblock_display(ps_dec);
if(ret != 0)
{
return IV_FAIL;
}
}
/*set to complete ,as we dont support partial frame decode*/
if(ps_dec->i4_header_decoded == 3)
{
ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1;
}
/*Update the i4_frametype at the end of picture*/
if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_dec->i4_frametype = IV_IDR_FRAME;
}
else if(ps_dec->i4_pic_type == B_SLICE)
{
ps_dec->i4_frametype = IV_B_FRAME;
}
else if(ps_dec->i4_pic_type == P_SLICE)
{
ps_dec->i4_frametype = IV_P_FRAME;
}
else if(ps_dec->i4_pic_type == I_SLICE)
{
ps_dec->i4_frametype = IV_I_FRAME;
}
else
{
H264_DEC_DEBUG_PRINT("Shouldn't come here\n");
}
ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2;
ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded
- ps_dec->ps_cur_slice->u1_field_pic_flag;
}
/* close deblock thread if it is not closed yet*/
if(ps_dec->u4_num_cores == 3)
{
ih264d_signal_bs_deblk_thread(ps_dec);
}
{
/* In case the decoder is configured to run in low delay mode,
* then get display buffer and then format convert.
* Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles
*/
if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode)
&& ps_dec->u1_init_dec_flag)
{
ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
if(0 == ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = 0;
ps_dec->u4_output_present = 1;
}
}
ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op);
/* If Format conversion is not complete,
complete it here */
if(ps_dec->u4_output_present &&
(ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht))
{
ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht
- ps_dec->u4_fmt_conv_cur_row;
ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op),
ps_dec->u4_fmt_conv_cur_row,
ps_dec->u4_fmt_conv_num_rows);
ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows;
}
ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op));
}
if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1)
{
ps_dec_op->u4_progressive_frame_flag = 1;
if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid)))
{
if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag)
&& (0 == ps_dec->ps_sps->u1_mb_aff_flag))
ps_dec_op->u4_progressive_frame_flag = 0;
}
}
/*Data memory barrier instruction,so that yuv write by the library is complete*/
DATA_SYNC();
H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n",
ps_dec_op->u4_num_bytes_consumed);
return api_ret_value;
}
|
CWE-172
| 187,538 | 8,159 |
337237439284486299826820848156495811271
| null | null | null |
Android
|
a4567c66f4764442c6cb7b5c1858810194480fb5
| 1 |
void SoftHEVC::onQueueFilled(OMX_U32 portIndex) {
UNUSED(portIndex);
if (mSignalledError) {
return;
}
if (mOutputPortSettingsChange != NONE) {
return;
}
if (NULL == mCodecCtx) {
if (OK != initDecoder()) {
return;
}
}
if (outputBufferWidth() != mStride) {
/* Set the run-time (dynamic) parameters */
mStride = outputBufferWidth();
setParams(mStride);
}
List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
/* If input EOS is seen and decoder is not in flush mode,
* set the decoder in flush mode.
* There can be a case where EOS is sent along with last picture data
* In that case, only after decoding that input data, decoder has to be
* put in flush. This case is handled here */
if (mReceivedEOS && !mIsInFlush) {
setFlushMode();
}
while (!outQueue.empty()) {
BufferInfo *inInfo;
OMX_BUFFERHEADERTYPE *inHeader;
BufferInfo *outInfo;
OMX_BUFFERHEADERTYPE *outHeader;
size_t timeStampIx;
inInfo = NULL;
inHeader = NULL;
if (!mIsInFlush) {
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
} else {
break;
}
}
outInfo = *outQueue.begin();
outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
outHeader->nTimeStamp = 0;
outHeader->nOffset = 0;
if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) {
mReceivedEOS = true;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
setFlushMode();
}
}
/* Get a free slot in timestamp array to hold input timestamp */
{
size_t i;
timeStampIx = 0;
for (i = 0; i < MAX_TIME_STAMPS; i++) {
if (!mTimeStampsValid[i]) {
timeStampIx = i;
break;
}
}
if (inHeader != NULL) {
mTimeStampsValid[timeStampIx] = true;
mTimeStamps[timeStampIx] = inHeader->nTimeStamp;
}
}
{
ivd_video_decode_ip_t s_dec_ip;
ivd_video_decode_op_t s_dec_op;
WORD32 timeDelay, timeTaken;
size_t sizeY, sizeUV;
if (!setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) {
ALOGE("Decoder arg setup failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
GETTIME(&mTimeStart, NULL);
/* Compute time elapsed between end of previous decode()
* to start of current decode() */
TIME_DIFF(mTimeEnd, mTimeStart, timeDelay);
IV_API_CALL_STATUS_T status;
status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op);
bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF));
GETTIME(&mTimeEnd, NULL);
/* Compute time taken for decode() */
TIME_DIFF(mTimeStart, mTimeEnd, timeTaken);
ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay,
s_dec_op.u4_num_bytes_consumed);
if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) {
mFlushNeeded = true;
}
if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) {
/* If the input did not contain picture data, then ignore
* the associated timestamp */
mTimeStampsValid[timeStampIx] = false;
}
if (mChangingResolution && !s_dec_op.u4_output_present) {
mChangingResolution = false;
resetDecoder();
resetPlugin();
continue;
}
if (resChanged) {
mChangingResolution = true;
if (mFlushNeeded) {
setFlushMode();
}
continue;
}
if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) {
uint32_t width = s_dec_op.u4_pic_wd;
uint32_t height = s_dec_op.u4_pic_ht;
bool portWillReset = false;
handlePortSettingsChange(&portWillReset, width, height);
if (portWillReset) {
resetDecoder();
return;
}
}
if (s_dec_op.u4_output_present) {
outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2;
outHeader->nTimeStamp = mTimeStamps[s_dec_op.u4_ts];
mTimeStampsValid[s_dec_op.u4_ts] = false;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
} else {
/* If in flush mode and no output is returned by the codec,
* then come out of flush mode */
mIsInFlush = false;
/* If EOS was recieved on input port and there is no output
* from the codec, then signal EOS on output port */
if (mReceivedEOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags |= OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
resetPlugin();
}
}
}
if (inHeader != NULL) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
}
|
CWE-172
| 187,539 | 8,160 |
169293408990322690773022320819810476215
| null | null | null |
Android
|
9cd8c3289c91254b3955bd7347cf605d6fa032c6
| 1 |
status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData)
{
Mutex::Autolock _l(mLock);
ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
if (mState == DESTROYED || mEffectInterface == NULL) {
return NO_INIT;
}
if (mStatus != NO_ERROR) {
return mStatus;
}
status_t status = (*mEffectInterface)->command(mEffectInterface,
cmdCode,
cmdSize,
pCmdData,
replySize,
pReplyData);
if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
uint32_t size = (replySize == NULL) ? 0 : *replySize;
for (size_t i = 1; i < mHandles.size(); i++) {
EffectHandle *h = mHandles[i];
if (h != NULL && !h->destroyed_l()) {
h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
}
}
}
return status;
}
|
CWE-20
| 187,540 | 8,161 |
128598111816536058121390029632040128451
| null | null | null |
Android
|
bae671597d47b9e5955c4cb742e468cebfd7ca6b
| 1 |
static void ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase,
unsigned ExifLength, int NestingLevel)
{
int de;
int a;
int NumDirEntries;
unsigned ThumbnailOffset = 0;
unsigned ThumbnailSize = 0;
char IndentString[25];
printf("ProcessExifDir");
if (NestingLevel > 4){
ErrNonfatal("Maximum directory nesting exceeded (corrupt exif header)", 0,0);
return;
}
memset(IndentString, ' ', 25);
IndentString[NestingLevel * 4] = '\0';
NumDirEntries = Get16u(DirStart);
#define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry))
{
unsigned char * DirEnd;
DirEnd = DIR_ENTRY_ADDR(DirStart, NumDirEntries);
if (DirEnd+4 > (OffsetBase+ExifLength)){
if (DirEnd+2 == OffsetBase+ExifLength || DirEnd == OffsetBase+ExifLength){
}else{
ErrNonfatal("Illegally sized exif subdirectory (%d entries)",NumDirEntries,0);
return;
}
}
if (DumpExifMap){
printf("Map: %05d-%05d: Directory\n",(int)(DirStart-OffsetBase), (int)(DirEnd+4-OffsetBase));
}
}
if (ShowTags){
printf("(dir has %d entries)\n",NumDirEntries);
}
for (de=0;de<NumDirEntries;de++){
int Tag, Format, Components;
unsigned char * ValuePtr;
int ByteCount;
unsigned char * DirEntry;
DirEntry = DIR_ENTRY_ADDR(DirStart, de);
Tag = Get16u(DirEntry);
Format = Get16u(DirEntry+2);
Components = Get32u(DirEntry+4);
if ((Format-1) >= NUM_FORMATS) {
ErrNonfatal("Illegal number format %d for tag %04x", Format, Tag);
continue;
}
if ((unsigned)Components > 0x10000){
ErrNonfatal("Illegal number of components %d for tag %04x", Components, Tag);
continue;
}
ByteCount = Components * BytesPerFormat[Format];
if (ByteCount > 4){
unsigned OffsetVal;
OffsetVal = Get32u(DirEntry+8);
if (OffsetVal+ByteCount > ExifLength){
ErrNonfatal("Illegal value pointer for tag %04x", Tag,0);
continue;
}
ValuePtr = OffsetBase+OffsetVal;
if (OffsetVal > ImageInfo.LargestExifOffset){
ImageInfo.LargestExifOffset = OffsetVal;
}
if (DumpExifMap){
printf("Map: %05d-%05d: Data for tag %04x\n",OffsetVal, OffsetVal+ByteCount, Tag);
}
}else{
ValuePtr = DirEntry+8;
}
if (Tag == TAG_MAKER_NOTE){
if (ShowTags){
printf("%s Maker note: ",IndentString);
}
ProcessMakerNote(ValuePtr, ByteCount, OffsetBase, ExifLength);
continue;
}
if (ShowTags){
for (a=0;;a++){
if (a >= (int)TAG_TABLE_SIZE){
printf("%s", IndentString);
printf(" Unknown Tag %04x Value = ", Tag);
break;
}
if (TagTable[a].Tag == Tag){
printf("%s", IndentString);
printf(" %s = ",TagTable[a].Desc);
break;
}
}
switch(Format){
case FMT_BYTE:
if(ByteCount>1){
printf("%.*ls\n", ByteCount/2, (wchar_t *)ValuePtr);
}else{
PrintFormatNumber(ValuePtr, Format, ByteCount);
printf("\n");
}
break;
case FMT_UNDEFINED:
case FMT_STRING:
{
printf("\"%s\"", ValuePtr);
}
break;
default:
PrintFormatNumber(ValuePtr, Format, ByteCount);
printf("\n");
}
}
switch(Tag){
case TAG_MAKE:
strncpy(ImageInfo.CameraMake, (char *)ValuePtr, ByteCount < 31 ? ByteCount : 31);
break;
case TAG_MODEL:
strncpy(ImageInfo.CameraModel, (char *)ValuePtr, ByteCount < 39 ? ByteCount : 39);
break;
case TAG_SUBSEC_TIME:
strlcpy(ImageInfo.SubSecTime, (char *)ValuePtr, sizeof(ImageInfo.SubSecTime));
break;
case TAG_SUBSEC_TIME_ORIG:
strlcpy(ImageInfo.SubSecTimeOrig, (char *)ValuePtr,
sizeof(ImageInfo.SubSecTimeOrig));
break;
case TAG_SUBSEC_TIME_DIG:
strlcpy(ImageInfo.SubSecTimeDig, (char *)ValuePtr,
sizeof(ImageInfo.SubSecTimeDig));
break;
case TAG_DATETIME_DIGITIZED:
strlcpy(ImageInfo.DigitizedTime, (char *)ValuePtr,
sizeof(ImageInfo.DigitizedTime));
if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){
ErrNonfatal("More than %d date fields! This is nuts", MAX_DATE_COPIES, 0);
break;
}
ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] =
(char *)ValuePtr - (char *)OffsetBase;
break;
case TAG_DATETIME_ORIGINAL:
strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19);
case TAG_DATETIME:
if (!isdigit(ImageInfo.DateTime[0])){
strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19);
}
if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){
ErrNonfatal("More than %d date fields! This is nuts", MAX_DATE_COPIES, 0);
break;
}
ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] =
(char *)ValuePtr - (char *)OffsetBase;
break;
case TAG_WINXP_COMMENT:
if (ImageInfo.Comments[0]){ // We already have a jpeg comment.
if (ShowTags) printf("Windows XP commend and other comment in header\n");
break; // Already have a windows comment, skip this one.
}
if (ByteCount > 1){
if (ByteCount > MAX_COMMENT_SIZE) ByteCount = MAX_COMMENT_SIZE;
memcpy(ImageInfo.Comments, ValuePtr, ByteCount);
ImageInfo.CommentWidchars = ByteCount/2;
}
break;
case TAG_USERCOMMENT:
if (ImageInfo.Comments[0]){ // We already have a jpeg comment.
if (ShowTags) printf("Multiple comments in exif header\n");
break; // Already have a windows comment, skip this one.
}
for (a=ByteCount;;){
a--;
if ((ValuePtr)[a] == ' '){
(ValuePtr)[a] = '\0';
}else{
break;
}
if (a == 0) break;
}
{
int msiz = ExifLength - (ValuePtr-OffsetBase);
if (msiz > ByteCount) msiz = ByteCount;
if (msiz > MAX_COMMENT_SIZE - 1) msiz = MAX_COMMENT_SIZE - 1;
if (msiz > 5 && memcmp(ValuePtr, "ASCII", 5) == 0) {
for (a = 5; a < 10 && a < msiz; a++) {
int c = (ValuePtr)[a];
if (c != '\0' && c != ' ') {
strncpy(ImageInfo.Comments,
(char *)ValuePtr + a, msiz - a);
break;
}
}
} else {
strncpy(ImageInfo.Comments, (char *)ValuePtr, msiz);
}
}
break;
case TAG_FNUMBER:
ImageInfo.ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_APERTURE:
case TAG_MAXAPERTURE:
if (ImageInfo.ApertureFNumber == 0){
ImageInfo.ApertureFNumber
= (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2)*0.5);
}
break;
case TAG_FOCALLENGTH:
ImageInfo.FocalLength.num = Get32u(ValuePtr);
ImageInfo.FocalLength.denom = Get32u(4+(char *)ValuePtr);
break;
case TAG_SUBJECT_DISTANCE:
ImageInfo.Distance = (float)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_EXPOSURETIME:
ImageInfo.ExposureTime = (float)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_SHUTTERSPEED:
if (ImageInfo.ExposureTime == 0){
ImageInfo.ExposureTime
= (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2)));
}
break;
case TAG_FLASH:
ImageInfo.FlashUsed=(int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_ORIENTATION:
if (NumOrientations >= 2){
ErrNonfatal("More than two orientation tags!",0,0);
break;
}
OrientationPtr[NumOrientations] = ValuePtr;
OrientationNumFormat[NumOrientations] = Format;
if (NumOrientations == 0){
ImageInfo.Orientation = (int)ConvertAnyFormat(ValuePtr, Format);
}
if (ImageInfo.Orientation < 0 || ImageInfo.Orientation > 8){
ErrNonfatal("Undefined rotation value %d", ImageInfo.Orientation, 0);
ImageInfo.Orientation = 0;
}
NumOrientations += 1;
break;
case TAG_EXIF_IMAGELENGTH:
case TAG_EXIF_IMAGEWIDTH:
a = (int)ConvertAnyFormat(ValuePtr, Format);
if (ExifImageWidth < a) ExifImageWidth = a;
break;
case TAG_FOCAL_PLANE_XRES:
FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_FOCAL_PLANE_UNITS:
switch((int)ConvertAnyFormat(ValuePtr, Format)){
case 1: FocalplaneUnits = 25.4; break; // inch
case 2:
FocalplaneUnits = 25.4;
break;
case 3: FocalplaneUnits = 10; break; // centimeter
case 4: FocalplaneUnits = 1; break; // millimeter
case 5: FocalplaneUnits = .001; break; // micrometer
}
break;
case TAG_EXPOSURE_BIAS:
ImageInfo.ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_WHITEBALANCE:
ImageInfo.Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_LIGHT_SOURCE:
ImageInfo.LightSource = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_METERING_MODE:
ImageInfo.MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_EXPOSURE_PROGRAM:
ImageInfo.ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_EXPOSURE_INDEX:
if (ImageInfo.ISOequivalent == 0){
ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
}
break;
case TAG_EXPOSURE_MODE:
ImageInfo.ExposureMode = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_ISO_EQUIVALENT:
ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_DIGITALZOOMRATIO:
ImageInfo.DigitalZoomRatio = (float)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_THUMBNAIL_OFFSET:
ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format);
DirWithThumbnailPtrs = DirStart;
break;
case TAG_THUMBNAIL_LENGTH:
ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format);
ImageInfo.ThumbnailSizeOffset = ValuePtr-OffsetBase;
break;
case TAG_EXIF_OFFSET:
if (ShowTags) printf("%s Exif Dir:",IndentString);
case TAG_INTEROP_OFFSET:
if (Tag == TAG_INTEROP_OFFSET && ShowTags) printf("%s Interop Dir:",IndentString);
{
unsigned char * SubdirStart;
SubdirStart = OffsetBase + Get32u(ValuePtr);
if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
ErrNonfatal("Illegal exif or interop ofset directory link",0,0);
}else{
ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
}
continue;
}
break;
case TAG_GPSINFO:
if (ShowTags) printf("%s GPS info dir:",IndentString);
{
unsigned char * SubdirStart;
SubdirStart = OffsetBase + Get32u(ValuePtr);
if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
ErrNonfatal("Illegal GPS directory link",0,0);
}else{
ProcessGpsInfo(SubdirStart, ByteCount, OffsetBase, ExifLength);
}
continue;
}
break;
case TAG_FOCALLENGTH_35MM:
ImageInfo.FocalLength35mmEquiv = (unsigned)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_DISTANCE_RANGE:
ImageInfo.DistanceRange = (int)ConvertAnyFormat(ValuePtr, Format);
break;
}
}
{
unsigned char * SubdirStart;
unsigned Offset;
if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength){
printf("DirStart %p offset from dirstart %d", DirStart, 2+12*NumDirEntries);
Offset = Get32u(DirStart+2+12*NumDirEntries);
if (Offset){
SubdirStart = OffsetBase + Offset;
if (SubdirStart > OffsetBase+ExifLength || SubdirStart < OffsetBase){
printf("SubdirStart %p OffsetBase %p ExifLength %d Offset %d",
SubdirStart, OffsetBase, ExifLength, Offset);
if (SubdirStart > OffsetBase && SubdirStart < OffsetBase+ExifLength+20){
if (ShowTags) printf("Thumbnail removed with Jhead 1.3 or earlier\n");
}else{
ErrNonfatal("Illegal subdirectory link",0,0);
}
}else{
if (SubdirStart <= OffsetBase+ExifLength){
if (ShowTags) printf("%s Continued directory ",IndentString);
ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
}
}
if (Offset > ImageInfo.LargestExifOffset){
ImageInfo.LargestExifOffset = Offset;
}
}
}else{
}
}
if (ThumbnailOffset){
ImageInfo.ThumbnailAtEnd = FALSE;
if (DumpExifMap){
printf("Map: %05d-%05d: Thumbnail\n",ThumbnailOffset, ThumbnailOffset+ThumbnailSize);
}
if (ThumbnailOffset <= ExifLength){
if (ThumbnailSize > ExifLength-ThumbnailOffset){
ThumbnailSize = ExifLength-ThumbnailOffset;
if (ShowTags) printf("Thumbnail incorrectly placed in header\n");
}
ImageInfo.ThumbnailOffset = ThumbnailOffset;
ImageInfo.ThumbnailSize = ThumbnailSize;
if (ShowTags){
printf("Thumbnail size: %d bytes\n",ThumbnailSize);
}
}
}
printf("returning from ProcessExifDir");
}
|
CWE-119
| 187,558 | 8,178 |
131638438977564828652261505589989030326
| null | null | null |
Android
|
590d1729883f700ab905cdc9ad850f3ddd7e1f56
| 1 |
u32 h264bsdInitDpb(
dpbStorage_t *dpb,
u32 picSizeInMbs,
u32 dpbSize,
u32 maxRefFrames,
u32 maxFrameNum,
u32 noReordering)
{
/* Variables */
u32 i;
/* Code */
ASSERT(picSizeInMbs);
ASSERT(maxRefFrames <= MAX_NUM_REF_PICS);
ASSERT(maxRefFrames <= dpbSize);
ASSERT(maxFrameNum);
ASSERT(dpbSize);
dpb->maxLongTermFrameIdx = NO_LONG_TERM_FRAME_INDICES;
dpb->maxRefFrames = MAX(maxRefFrames, 1);
if (noReordering)
dpb->dpbSize = dpb->maxRefFrames;
else
dpb->dpbSize = dpbSize;
dpb->maxFrameNum = maxFrameNum;
dpb->noReordering = noReordering;
dpb->fullness = 0;
dpb->numRefFrames = 0;
dpb->prevRefFrameNum = 0;
ALLOCATE(dpb->buffer, MAX_NUM_REF_IDX_L0_ACTIVE + 1, dpbPicture_t);
if (dpb->buffer == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(dpb->buffer, 0,
(MAX_NUM_REF_IDX_L0_ACTIVE + 1)*sizeof(dpbPicture_t));
for (i = 0; i < dpb->dpbSize + 1; i++)
{
/* Allocate needed amount of memory, which is:
* image size + 32 + 15, where 32 cames from the fact that in ARM OpenMax
* DL implementation Functions may read beyond the end of an array,
* by a maximum of 32 bytes. And +15 cames for the need to align memory
* to 16-byte boundary */
ALLOCATE(dpb->buffer[i].pAllocatedData, (picSizeInMbs*384 + 32+15), u8);
if (dpb->buffer[i].pAllocatedData == NULL)
return(MEMORY_ALLOCATION_ERROR);
dpb->buffer[i].data = ALIGN(dpb->buffer[i].pAllocatedData, 16);
}
ALLOCATE(dpb->list, MAX_NUM_REF_IDX_L0_ACTIVE + 1, dpbPicture_t*);
ALLOCATE(dpb->outBuf, dpb->dpbSize+1, dpbOutPicture_t);
if (dpb->list == NULL || dpb->outBuf == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(dpb->list, 0,
((MAX_NUM_REF_IDX_L0_ACTIVE + 1) * sizeof(dpbPicture_t*)) );
dpb->numOut = dpb->outIndex = 0;
return(HANTRO_OK);
}
|
CWE-119
| 187,568 | 8,188 |
223946036477816215968870435417211048643
| null | null | null |
Android
|
d1c775d1d8d2ed117d1e026719b7f9f089716597
| 1 |
INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits)
{
stream_t *ps_stream = (stream_t *)pv_ctxt;
if (ps_stream->u4_offset < ps_stream->u4_max_offset)
{
FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned)
}
return;
}
|
CWE-200
| 187,571 | 8,191 |
248363492286330365487580949990450657822
| null | null | null |
Android
|
daef4327fe0c75b0a90bb8627458feec7a301e1f
| 1 |
sp<IMemory> MetadataRetrieverClient::getFrameAtTime(int64_t timeUs, int option)
{
ALOGV("getFrameAtTime: time(%lld us) option(%d)", timeUs, option);
Mutex::Autolock lock(mLock);
Mutex::Autolock glock(sLock);
mThumbnail.clear();
if (mRetriever == NULL) {
ALOGE("retriever is not initialized");
return NULL;
}
VideoFrame *frame = mRetriever->getFrameAtTime(timeUs, option);
if (frame == NULL) {
ALOGE("failed to capture a video frame");
return NULL;
}
size_t size = sizeof(VideoFrame) + frame->mSize;
sp<MemoryHeapBase> heap = new MemoryHeapBase(size, 0, "MetadataRetrieverClient");
if (heap == NULL) {
ALOGE("failed to create MemoryDealer");
delete frame;
return NULL;
}
mThumbnail = new MemoryBase(heap, 0, size);
if (mThumbnail == NULL) {
ALOGE("not enough memory for VideoFrame size=%u", size);
delete frame;
return NULL;
}
VideoFrame *frameCopy = static_cast<VideoFrame *>(mThumbnail->pointer());
frameCopy->mWidth = frame->mWidth;
frameCopy->mHeight = frame->mHeight;
frameCopy->mDisplayWidth = frame->mDisplayWidth;
frameCopy->mDisplayHeight = frame->mDisplayHeight;
frameCopy->mSize = frame->mSize;
frameCopy->mRotationAngle = frame->mRotationAngle;
ALOGV("rotation: %d", frameCopy->mRotationAngle);
frameCopy->mData = (uint8_t *)frameCopy + sizeof(VideoFrame);
memcpy(frameCopy->mData, frame->mData, frame->mSize);
delete frame; // Fix memory leakage
return mThumbnail;
}
|
CWE-20
| 187,572 | 8,192 |
47687956695025999074859613652565003790
| null | null | null |
Android
|
338aeaf28e9981c15d0673b18487dba61eb5447c
| 1 |
char* dexOptGenerateCacheFileName(const char* fileName, const char* subFileName)
{
char nameBuf[512];
char absoluteFile[sizeof(nameBuf)];
const size_t kBufLen = sizeof(nameBuf) - 1;
const char* dataRoot;
char* cp;
/*
* Get the absolute path of the Jar or DEX file.
*/
absoluteFile[0] = '\0';
if (fileName[0] != '/') {
/*
* Generate the absolute path. This doesn't do everything it
* should, e.g. if filename is "./out/whatever" it doesn't crunch
* the leading "./" out, but it'll do.
*/
if (getcwd(absoluteFile, kBufLen) == NULL) {
ALOGE("Can't get CWD while opening jar file");
return NULL;
}
strncat(absoluteFile, "/", kBufLen);
}
strncat(absoluteFile, fileName, kBufLen);
/*
* Append the name of the Jar file entry, if any. This is not currently
* required, but will be if we start putting more than one DEX file
* in a Jar.
*/
if (subFileName != NULL) {
strncat(absoluteFile, "/", kBufLen);
strncat(absoluteFile, subFileName, kBufLen);
}
/* Turn the path into a flat filename by replacing
* any slashes after the first one with '@' characters.
*/
cp = absoluteFile + 1;
while (*cp != '\0') {
if (*cp == '/') {
*cp = '@';
}
cp++;
}
/* Build the name of the cache directory.
*/
dataRoot = getenv("ANDROID_DATA");
if (dataRoot == NULL)
dataRoot = "/data";
snprintf(nameBuf, kBufLen, "%s/%s", dataRoot, kCacheDirectoryName);
if (strcmp(dataRoot, "/data") != 0) {
int result = dexOptMkdir(nameBuf, 0700);
if (result != 0 && errno != EEXIST) {
ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno));
return NULL;
}
}
snprintf(nameBuf, kBufLen, "%s/%s/%s", dataRoot, kCacheDirectoryName, kInstructionSet);
if (strcmp(dataRoot, "/data") != 0) {
int result = dexOptMkdir(nameBuf, 0700);
if (result != 0 && errno != EEXIST) {
ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno));
return NULL;
}
}
/* Tack on the file name for the actual cache file path.
*/
strncat(nameBuf, absoluteFile, kBufLen);
ALOGV("Cache file for '%s' '%s' is '%s'", fileName, subFileName, nameBuf);
return strdup(nameBuf);
}
|
CWE-119
| 187,581 | 8,200 |
93130013348756198235643531610046840500
| null | null | null |
Android
|
ae18eb014609948a40e22192b87b10efc680daa7
| 1 |
static void print_maps(struct pid_info_t* info)
{
FILE *maps;
size_t offset;
char device[10];
long int inode;
char file[PATH_MAX];
strlcat(info->path, "maps", sizeof(info->path));
maps = fopen(info->path, "r");
if (!maps)
goto out;
while (fscanf(maps, "%*x-%*x %*s %zx %s %ld %s\n", &offset, device, &inode,
file) == 4) {
if (inode == 0 || !strcmp(device, "00:00"))
continue;
printf("%-9s %5d %10s %4s %9s %18s %9zd %10ld %s\n",
info->cmdline, info->pid, info->user, "mem",
"???", device, offset, inode, file);
}
fclose(maps);
out:
info->path[info->parent_length] = '\0';
}
|
CWE-20
| 187,582 | 8,201 |
177103654200417609625356191565722072101
| null | null | null |
Android
|
659030a2e80c38fb8da0a4eb68695349eec6778b
| 1 |
int res_inverse(vorbis_dsp_state *vd,vorbis_info_residue *info,
ogg_int32_t **in,int *nonzero,int ch){
int i,j,k,s,used=0;
codec_setup_info *ci=(codec_setup_info *)vd->vi->codec_setup;
codebook *phrasebook=ci->book_param+info->groupbook;
int samples_per_partition=info->grouping;
int partitions_per_word=phrasebook->dim;
int pcmend=ci->blocksizes[vd->W];
if(info->type<2){
int max=pcmend>>1;
int end=(info->end<max?info->end:max);
int n=end-info->begin;
if(n>0){
int partvals=n/samples_per_partition;
int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
for(i=0;i<ch;i++)
if(nonzero[i])
in[used++]=in[i];
ch=used;
if(used){
char **partword=(char **)alloca(ch*sizeof(*partword));
for(j=0;j<ch;j++)
partword[j]=(char *)alloca(partwords*partitions_per_word*
sizeof(*partword[j]));
for(s=0;s<info->stages;s++){
for(i=0;i<partvals;){
if(s==0){
/* fetch the partition word for each channel */
partword[0][i+partitions_per_word-1]=1;
for(k=partitions_per_word-2;k>=0;k--)
partword[0][i+k]=partword[0][i+k+1]*info->partitions;
for(j=1;j<ch;j++)
for(k=partitions_per_word-1;k>=0;k--)
partword[j][i+k]=partword[j-1][i+k];
for(j=0;j<ch;j++){
int temp=vorbis_book_decode(phrasebook,&vd->opb);
if(temp==-1)goto eopbreak;
/* this can be done quickly in assembly due to the quotient
always being at most six bits */
for(k=0;k<partitions_per_word;k++){
ogg_uint32_t div=partword[j][i+k];
partword[j][i+k]=temp/div;
temp-=partword[j][i+k]*div;
}
}
}
/* now we decode residual values for the partitions */
for(k=0;k<partitions_per_word && i<partvals;k++,i++)
for(j=0;j<ch;j++){
long offset=info->begin+i*samples_per_partition;
if(info->stagemasks[(int)partword[j][i]]&(1<<s)){
codebook *stagebook=ci->book_param+
info->stagebooks[(partword[j][i]<<3)+s];
if(info->type){
if(vorbis_book_decodev_add(stagebook,in[j]+offset,&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}else{
if(vorbis_book_decodevs_add(stagebook,in[j]+offset,&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}
}
}
}
}
}
}
}else{
int max=(pcmend*ch)>>1;
int end=(info->end<max?info->end:max);
int n=end-info->begin;
if(n>0){
int partvals=n/samples_per_partition;
int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
char *partword=
(char *)alloca(partwords*partitions_per_word*sizeof(*partword));
int beginoff=info->begin/ch;
for(i=0;i<ch;i++)if(nonzero[i])break;
if(i==ch)return(0); /* no nonzero vectors */
samples_per_partition/=ch;
for(s=0;s<info->stages;s++){
for(i=0;i<partvals;){
if(s==0){
int temp;
partword[i+partitions_per_word-1]=1;
for(k=partitions_per_word-2;k>=0;k--)
partword[i+k]=partword[i+k+1]*info->partitions;
/* fetch the partition word */
temp=vorbis_book_decode(phrasebook,&vd->opb);
if(temp==-1)goto eopbreak;
/* this can be done quickly in assembly due to the quotient
always being at most six bits */
for(k=0;k<partitions_per_word;k++){
ogg_uint32_t div=partword[i+k];
partword[i+k]=temp/div;
temp-=partword[i+k]*div;
}
}
/* now we decode residual values for the partitions */
for(k=0;k<partitions_per_word && i<partvals;k++,i++)
if(info->stagemasks[(int)partword[i]]&(1<<s)){
codebook *stagebook=ci->book_param+
info->stagebooks[(partword[i]<<3)+s];
if(vorbis_book_decodevv_add(stagebook,in,
i*samples_per_partition+beginoff,ch,
&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}
}
}
}
}
eopbreak:
return 0;
}
|
CWE-20
| 187,583 | 8,202 |
183647412667613024558396972090517418998
| null | null | null |
Android
|
d4841f1161bdb5e13cb19e81af42437a634dd6ef
| 1 |
WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec,
WORD32 num_mb_skip,
UWORD8 u1_is_idr_slice,
UWORD16 u2_frame_num,
pocstruct_t *ps_cur_poc,
WORD32 prev_slice_err)
{
WORD32 i2_cur_mb_addr;
UWORD32 u1_num_mbs, u1_num_mbsNby2;
UWORD32 u1_mb_idx = ps_dec->u1_mb_idx;
UWORD32 i2_mb_skip_run;
UWORD32 u1_num_mbs_next, u1_end_of_row;
const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
UWORD32 u1_slice_end;
UWORD32 u1_tfr_n_mb;
UWORD32 u1_decode_nmb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
deblk_mb_t *ps_cur_deblk_mb;
dec_mb_info_t *ps_cur_mb_info;
parse_pmbarams_t *ps_parse_mb_data;
UWORD32 u1_inter_mb_type;
UWORD32 u1_deblk_mb_type;
UWORD16 u2_total_mbs_coded;
UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag;
parse_part_params_t *ps_part_info;
WORD32 ret;
if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return 0;
}
if(prev_slice_err == 1)
{
/* first slice - missing/header corruption */
ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num;
if(!ps_dec->u1_first_slice_in_stream)
{
ih264d_end_of_pic(ps_dec, u1_is_idr_slice,
ps_dec->ps_cur_slice->u2_frame_num);
ps_dec->s_cur_pic_poc.u2_frame_num =
ps_dec->ps_cur_slice->u2_frame_num;
}
{
WORD32 i, j, poc = 0;
ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0;
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff;
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_bp;
if(ps_dec->ps_cur_pic != NULL)
poc = ps_dec->ps_cur_pic->i4_poc + 2;
j = 0;
for(i = 0; i < MAX_NUM_PIC_PARAMS; i++)
if(ps_dec->ps_pps[i].u1_is_valid == TRUE)
j = i;
{
ps_dec->ps_cur_slice->u1_bottom_field_flag = 0;
ps_dec->ps_cur_slice->u1_field_pic_flag = 0;
ps_dec->ps_cur_slice->u1_slice_type = P_SLICE;
ps_dec->ps_cur_slice->u1_nal_ref_idc = 1;
ps_dec->ps_cur_slice->u1_nal_unit_type = 1;
ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc,
ps_dec->ps_cur_slice->u2_frame_num,
&ps_dec->ps_pps[j]);
if(ret != OK)
{
return ret;
}
}
ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0;
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;
}
}
}
}
else
{
dec_slice_struct_t *ps_parse_cur_slice;
ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num;
if(ps_dec->u1_slice_header_done
&& ps_parse_cur_slice == ps_dec->ps_parse_cur_slice)
{
u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb;
if(u1_num_mbs)
{
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1;
}
else
{
if(ps_dec->u1_separate_parse)
{
ps_cur_mb_info = ps_dec->ps_nmb_info - 1;
}
else
{
ps_cur_mb_info = ps_dec->ps_nmb_info
+ ps_dec->u4_num_mbs_prev_nmb - 1;
}
}
ps_dec->u2_mby = ps_cur_mb_info->u2_mby;
ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx;
ps_dec->u1_mb_ngbr_availablity =
ps_cur_mb_info->u1_mb_ngbr_availablity;
ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data;
ps_dec->u2_cur_mb_addr--;
ps_dec->i4_submb_ofst -= SUB_BLK_SIZE;
if(u1_num_mbs)
{
if (ps_dec->u1_pr_sl_type == P_SLICE
|| ps_dec->u1_pr_sl_type == B_SLICE)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
ps_dec->ps_part = ps_dec->ps_parse_part_params;
}
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next)
&& (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = 1;
u1_tfr_n_mb = 1;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
ps_dec->u1_mb_idx = 0;
ps_dec->u4_num_mbs_cur_nmb = 0;
}
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
ps_dec->u1_pic_decode_done = 1;
return 0;
}
ps_dec->u2_cur_slice_num++;
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
ps_dec->ps_parse_cur_slice++;
}
else
{
ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf
+ ps_dec->u2_cur_slice_num;
}
}
/******************************************************/
/* Initializations to new slice */
/******************************************************/
{
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 = (volatile void **)pu1_buf;
}
ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff;
ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0;
ps_dec->ps_cur_slice->i1_slice_beta_offset = 0;
if(ps_dec->ps_cur_slice->u1_field_pic_flag)
ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num;
ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff;
ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd;
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;
}
/******************************************************/
/* Initializations specific to P slice */
/******************************************************/
u1_inter_mb_type = P_MB;
u1_deblk_mb_type = D_INTER_MB;
ps_dec->ps_cur_slice->u1_slice_type = P_SLICE;
ps_dec->ps_parse_cur_slice->slice_type = P_SLICE;
ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
/******************************************************/
/* Parsing / decoding the slice */
/******************************************************/
ps_dec->u1_slice_header_done = 2;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mb_idx = ps_dec->u1_mb_idx;
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
u1_num_mbs = u1_mb_idx;
u1_slice_end = 0;
u1_tfr_n_mb = 0;
u1_decode_nmb = 0;
u1_num_mbsNby2 = 0;
i2_cur_mb_addr = ps_dec->u2_total_mbs_coded;
i2_mb_skip_run = num_mb_skip;
while(!u1_slice_end)
{
UWORD8 u1_mb_type;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
break;
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_cur_mb_info->u1_Mux = 0;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
ps_cur_mb_info->u1_end_of_slice = 0;
/* Storing Default partition info */
ps_parse_mb_data->u1_num_part = 1;
ps_parse_mb_data->u1_isI_mb = 0;
/**************************************************************/
/* Get the required information for decoding of MB */
/**************************************************************/
/* mb_x, mb_y, neighbor availablity, */
if (u1_mbaff)
ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run);
else
ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run);
/* Set the deblocking parameters for this MB */
if(ps_dec->u4_app_disable_deblk_frm == 0)
{
ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
}
/* Set appropriate flags in ps_cur_mb_info and ps_dec */
ps_dec->i1_prev_mb_qp_delta = 0;
ps_dec->u1_sub_mb_num = 0;
ps_cur_mb_info->u1_mb_type = MB_SKIP;
ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16;
ps_cur_mb_info->u1_cbp = 0;
/* Storing Skip partition info */
ps_part_info = ps_dec->ps_part;
ps_part_info->u1_is_direct = PART_DIRECT_16x16;
ps_part_info->u1_sub_mb_num = 0;
ps_dec->ps_part++;
/* Update Nnzs */
ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC);
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
i2_mb_skip_run--;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
if (u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/**************************************************************/
/* Get next Macroblock address */
/**************************************************************/
i2_cur_mb_addr++;
u1_num_mbs++;
u1_num_mbsNby2++;
ps_parse_mb_data++;
/****************************************************************/
/* Check for End Of Row and other flags that determine when to */
/* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */
/* N-Mb */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = !i2_mb_skip_run;
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| u1_slice_end;
u1_decode_nmb = u1_tfr_n_mb || u1_slice_end;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
if(u1_decode_nmb)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
u1_num_mbsNby2 = 0;
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next,
u1_tfr_n_mb, u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice;
H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice);
ps_dec->u2_cur_slice_num++;
/* incremented here only if first slice is inserted */
if(ps_dec->u4_first_slice_in_pic != 0)
ps_dec->ps_parse_cur_slice++;
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
ps_dec->u1_pic_decode_done = 1;
}
return 0;
}
|
CWE-20
| 187,585 | 8,204 |
272222286368369147141000541292178562551
| null | null | null |
Android
|
6fdee2a83432b3b150d6a34f231c4e2f7353c01e
| 1 |
int main(int argc __unused, char** argv)
{
signal(SIGPIPE, SIG_IGN);
char value[PROPERTY_VALUE_MAX];
bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1);
pid_t childPid;
if (doLog && (childPid = fork()) != 0) {
strcpy(argv[0], "media.log");
sp<ProcessState> proc(ProcessState::self());
MediaLogService::instantiate();
ProcessState::self()->startThreadPool();
for (;;) {
siginfo_t info;
int ret = waitid(P_PID, childPid, &info, WEXITED | WSTOPPED | WCONTINUED);
if (ret == EINTR) {
continue;
}
if (ret < 0) {
break;
}
char buffer[32];
const char *code;
switch (info.si_code) {
case CLD_EXITED:
code = "CLD_EXITED";
break;
case CLD_KILLED:
code = "CLD_KILLED";
break;
case CLD_DUMPED:
code = "CLD_DUMPED";
break;
case CLD_STOPPED:
code = "CLD_STOPPED";
break;
case CLD_TRAPPED:
code = "CLD_TRAPPED";
break;
case CLD_CONTINUED:
code = "CLD_CONTINUED";
break;
default:
snprintf(buffer, sizeof(buffer), "unknown (%d)", info.si_code);
code = buffer;
break;
}
struct rusage usage;
getrusage(RUSAGE_CHILDREN, &usage);
ALOG(LOG_ERROR, "media.log", "pid %d status %d code %s user %ld.%03lds sys %ld.%03lds",
info.si_pid, info.si_status, code,
usage.ru_utime.tv_sec, usage.ru_utime.tv_usec / 1000,
usage.ru_stime.tv_sec, usage.ru_stime.tv_usec / 1000);
sp<IServiceManager> sm = defaultServiceManager();
sp<IBinder> binder = sm->getService(String16("media.log"));
if (binder != 0) {
Vector<String16> args;
binder->dump(-1, args);
}
switch (info.si_code) {
case CLD_EXITED:
case CLD_KILLED:
case CLD_DUMPED: {
ALOG(LOG_INFO, "media.log", "exiting");
_exit(0);
}
default:
break;
}
}
} else {
if (doLog) {
prctl(PR_SET_PDEATHSIG, SIGKILL); // if parent media.log dies before me, kill me also
setpgid(0, 0); // but if I die first, don't kill my parent
}
InitializeIcuOrDie();
sp<ProcessState> proc(ProcessState::self());
sp<IServiceManager> sm = defaultServiceManager();
ALOGI("ServiceManager: %p", sm.get());
AudioFlinger::instantiate();
MediaPlayerService::instantiate();
ResourceManagerService::instantiate();
CameraService::instantiate();
AudioPolicyService::instantiate();
SoundTriggerHwService::instantiate();
RadioService::instantiate();
registerExtensions();
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
}
}
|
CWE-399
| 187,586 | 8,205 |
153447124376763754536164659791191536105
| null | null | null |
Android
|
54cb02ad733fb71b1bdf78590428817fb780aff8
| 1 |
native_handle* Parcel::readNativeHandle() const
{
int numFds, numInts;
status_t err;
err = readInt32(&numFds);
if (err != NO_ERROR) return 0;
err = readInt32(&numInts);
if (err != NO_ERROR) return 0;
native_handle* h = native_handle_create(numFds, numInts);
if (!h) {
return 0;
}
for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
h->data[i] = dup(readFileDescriptor());
if (h->data[i] < 0) err = BAD_VALUE;
}
err = read(h->data + numFds, sizeof(int)*numInts);
if (err != NO_ERROR) {
native_handle_close(h);
native_handle_delete(h);
h = 0;
}
return h;
}
|
CWE-20
| 187,766 | 8,361 |
49962414184976978255480525959099029025
| null | null | null |
Android
|
514139f4b40cbb035bb92f3e24d5a389d75db9e6
| 1 |
static BT_HDR *create_pbuf(UINT16 len, UINT8 *data)
{
BT_HDR* p_buf = GKI_getbuf((UINT16) (len + BTA_HH_MIN_OFFSET + sizeof(BT_HDR)));
if (p_buf) {
UINT8* pbuf_data;
p_buf->len = len;
p_buf->offset = BTA_HH_MIN_OFFSET;
pbuf_data = (UINT8*) (p_buf + 1) + p_buf->offset;
memcpy(pbuf_data, data, len);
}
return p_buf;
}
|
CWE-119
| 187,779 | 8,374 |
30281110686918549390867175650138607160
| null | null | null |
Android
|
ecf6c7ce6d5a22d52160698aab44fc234c63291a
| 1 |
void ih264d_init_decoder(void * ps_dec_params)
{
dec_struct_t * ps_dec = (dec_struct_t *)ps_dec_params;
dec_slice_params_t *ps_cur_slice;
pocstruct_t *ps_prev_poc, *ps_cur_poc;
/* Free any dynamic buffers that are allocated */
ih264d_free_dynamic_bufs(ps_dec);
ps_cur_slice = ps_dec->ps_cur_slice;
ps_dec->init_done = 0;
ps_dec->u4_num_cores = 1;
ps_dec->u2_pic_ht = ps_dec->u2_pic_wd = 0;
ps_dec->u1_separate_parse = DEFAULT_SEPARATE_PARSE;
ps_dec->u4_app_disable_deblk_frm = 0;
ps_dec->i4_degrade_type = 0;
ps_dec->i4_degrade_pics = 0;
ps_dec->i4_app_skip_mode = IVD_SKIP_NONE;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
memset(ps_dec->ps_pps, 0,
((sizeof(dec_pic_params_t)) * MAX_NUM_PIC_PARAMS));
memset(ps_dec->ps_sps, 0,
((sizeof(dec_seq_params_t)) * MAX_NUM_SEQ_PARAMS));
/* Initialization of function pointers ih264d_deblock_picture function*/
ps_dec->p_DeblockPicture[0] = ih264d_deblock_picture_non_mbaff;
ps_dec->p_DeblockPicture[1] = ih264d_deblock_picture_mbaff;
ps_dec->s_cab_dec_env.pv_codec_handle = ps_dec;
ps_dec->u4_num_fld_in_frm = 0;
ps_dec->ps_dpb_mgr->pv_codec_handle = ps_dec;
/* Initialize the sei validity u4_flag with zero indiacting sei is not valid*/
ps_dec->ps_sei->u1_is_valid = 0;
/* decParams Initializations */
ps_dec->ps_cur_pps = NULL;
ps_dec->ps_cur_sps = NULL;
ps_dec->u1_init_dec_flag = 0;
ps_dec->u1_first_slice_in_stream = 1;
ps_dec->u1_first_pb_nal_in_pic = 1;
ps_dec->u1_last_pic_not_decoded = 0;
ps_dec->u4_app_disp_width = 0;
ps_dec->i4_header_decoded = 0;
ps_dec->u4_total_frames_decoded = 0;
ps_dec->i4_error_code = 0;
ps_dec->i4_content_type = -1;
ps_dec->ps_cur_slice->u1_mbaff_frame_flag = 0;
ps_dec->ps_dec_err_status->u1_err_flag = ACCEPT_ALL_PICS; //REJECT_PB_PICS;
ps_dec->ps_dec_err_status->u1_cur_pic_type = PIC_TYPE_UNKNOWN;
ps_dec->ps_dec_err_status->u4_frm_sei_sync = SYNC_FRM_DEFAULT;
ps_dec->ps_dec_err_status->u4_cur_frm = INIT_FRAME;
ps_dec->ps_dec_err_status->u1_pic_aud_i = PIC_TYPE_UNKNOWN;
ps_dec->u1_pr_sl_type = 0xFF;
ps_dec->u2_mbx = 0xffff;
ps_dec->u2_mby = 0;
ps_dec->u2_total_mbs_coded = 0;
/* POC initializations */
ps_prev_poc = &ps_dec->s_prev_pic_poc;
ps_cur_poc = &ps_dec->s_cur_pic_poc;
ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb = 0;
ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb = 0;
ps_prev_poc->i4_delta_pic_order_cnt_bottom =
ps_cur_poc->i4_delta_pic_order_cnt_bottom = 0;
ps_prev_poc->i4_delta_pic_order_cnt[0] =
ps_cur_poc->i4_delta_pic_order_cnt[0] = 0;
ps_prev_poc->i4_delta_pic_order_cnt[1] =
ps_cur_poc->i4_delta_pic_order_cnt[1] = 0;
ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0;
ps_prev_poc->i4_top_field_order_count = ps_cur_poc->i4_top_field_order_count =
0;
ps_prev_poc->i4_bottom_field_order_count =
ps_cur_poc->i4_bottom_field_order_count = 0;
ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field = 0;
ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0;
ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst = 0;
ps_cur_slice->u1_mmco_equalto5 = 0;
ps_cur_slice->u2_frame_num = 0;
ps_dec->i4_max_poc = 0;
ps_dec->i4_prev_max_display_seq = 0;
ps_dec->u1_recon_mb_grp = 4;
/* Field PIC initializations */
ps_dec->u1_second_field = 0;
ps_dec->s_prev_seq_params.u1_eoseq_pending = 0;
/* Set the cropping parameters as zero */
ps_dec->u2_crop_offset_y = 0;
ps_dec->u2_crop_offset_uv = 0;
/* The Initial Frame Rate Info is not Present */
ps_dec->i4_vui_frame_rate = -1;
ps_dec->i4_pic_type = -1;
ps_dec->i4_frametype = -1;
ps_dec->i4_content_type = -1;
ps_dec->u1_res_changed = 0;
ps_dec->u1_frame_decoded_flag = 0;
/* Set the default frame seek mask mode */
ps_dec->u4_skip_frm_mask = SKIP_NONE;
/********************************************************/
/* Initialize CAVLC residual decoding function pointers */
/********************************************************/
ps_dec->pf_cavlc_4x4res_block[0] = ih264d_cavlc_4x4res_block_totalcoeff_1;
ps_dec->pf_cavlc_4x4res_block[1] =
ih264d_cavlc_4x4res_block_totalcoeff_2to10;
ps_dec->pf_cavlc_4x4res_block[2] =
ih264d_cavlc_4x4res_block_totalcoeff_11to16;
ps_dec->pf_cavlc_parse4x4coeff[0] = ih264d_cavlc_parse4x4coeff_n0to7;
ps_dec->pf_cavlc_parse4x4coeff[1] = ih264d_cavlc_parse4x4coeff_n8;
ps_dec->pf_cavlc_parse_8x8block[0] =
ih264d_cavlc_parse_8x8block_none_available;
ps_dec->pf_cavlc_parse_8x8block[1] =
ih264d_cavlc_parse_8x8block_left_available;
ps_dec->pf_cavlc_parse_8x8block[2] =
ih264d_cavlc_parse_8x8block_top_available;
ps_dec->pf_cavlc_parse_8x8block[3] =
ih264d_cavlc_parse_8x8block_both_available;
/***************************************************************************/
/* Initialize Bs calculation function pointers for P and B, 16x16/non16x16 */
/***************************************************************************/
ps_dec->pf_fill_bs1[0][0] = ih264d_fill_bs1_16x16mb_pslice;
ps_dec->pf_fill_bs1[0][1] = ih264d_fill_bs1_non16x16mb_pslice;
ps_dec->pf_fill_bs1[1][0] = ih264d_fill_bs1_16x16mb_bslice;
ps_dec->pf_fill_bs1[1][1] = ih264d_fill_bs1_non16x16mb_bslice;
ps_dec->pf_fill_bs_xtra_left_edge[0] =
ih264d_fill_bs_xtra_left_edge_cur_frm;
ps_dec->pf_fill_bs_xtra_left_edge[1] =
ih264d_fill_bs_xtra_left_edge_cur_fld;
/* Initialize Reference Pic Buffers */
ih264d_init_ref_bufs(ps_dec->ps_dpb_mgr);
ps_dec->u2_prv_frame_num = 0;
ps_dec->u1_top_bottom_decoded = 0;
ps_dec->u1_dangling_field = 0;
ps_dec->s_cab_dec_env.cabac_table = gau4_ih264d_cabac_table;
ps_dec->pu1_left_mv_ctxt_inc = ps_dec->u1_left_mv_ctxt_inc_arr[0];
ps_dec->pi1_left_ref_idx_ctxt_inc =
&ps_dec->i1_left_ref_idx_ctx_inc_arr[0][0];
ps_dec->pu1_left_yuv_dc_csbp = &ps_dec->u1_yuv_dc_csbp_topmb;
/* ! */
/* Initializing flush frame u4_flag */
ps_dec->u1_flushfrm = 0;
{
ps_dec->s_cab_dec_env.pv_codec_handle = (void*)ps_dec;
ps_dec->ps_bitstrm->pv_codec_handle = (void*)ps_dec;
ps_dec->ps_cur_slice->pv_codec_handle = (void*)ps_dec;
ps_dec->ps_dpb_mgr->pv_codec_handle = (void*)ps_dec;
}
memset(ps_dec->disp_bufs, 0, (MAX_DISP_BUFS_NEW) * sizeof(disp_buf_t));
memset(ps_dec->u4_disp_buf_mapping, 0,
(MAX_DISP_BUFS_NEW) * sizeof(UWORD32));
memset(ps_dec->u4_disp_buf_to_be_freed, 0,
(MAX_DISP_BUFS_NEW) * sizeof(UWORD32));
ih264d_init_arch(ps_dec);
ih264d_init_function_ptr(ps_dec);
ps_dec->e_frm_out_mode = IVD_DISPLAY_FRAME_OUT;
ps_dec->init_done = 1;
}
|
CWE-20
| 187,780 | 8,375 |
158351370982025760108008914121172142938
| null | null | null |
Android
|
60547808ca4e9cfac50028c00c58a6ceb2319301
| 1 |
u32 h264bsdActivateParamSets(storage_t *pStorage, u32 ppsId, u32 isIdr)
{
/* Variables */
u32 tmp;
u32 flag;
/* Code */
ASSERT(pStorage);
ASSERT(ppsId < MAX_NUM_PIC_PARAM_SETS);
/* check that pps and corresponding sps exist */
if ( (pStorage->pps[ppsId] == NULL) ||
(pStorage->sps[pStorage->pps[ppsId]->seqParameterSetId] == NULL) )
{
return(HANTRO_NOK);
}
/* check that pps parameters do not violate picture size constraints */
tmp = CheckPps(pStorage->pps[ppsId],
pStorage->sps[pStorage->pps[ppsId]->seqParameterSetId]);
if (tmp != HANTRO_OK)
return(tmp);
/* first activation part1 */
if (pStorage->activePpsId == MAX_NUM_PIC_PARAM_SETS)
{
pStorage->activePpsId = ppsId;
pStorage->activePps = pStorage->pps[ppsId];
pStorage->activeSpsId = pStorage->activePps->seqParameterSetId;
pStorage->activeSps = pStorage->sps[pStorage->activeSpsId];
pStorage->picSizeInMbs =
pStorage->activeSps->picWidthInMbs *
pStorage->activeSps->picHeightInMbs;
pStorage->currImage->width = pStorage->activeSps->picWidthInMbs;
pStorage->currImage->height = pStorage->activeSps->picHeightInMbs;
pStorage->pendingActivation = HANTRO_TRUE;
}
/* first activation part2 */
else if (pStorage->pendingActivation)
{
pStorage->pendingActivation = HANTRO_FALSE;
FREE(pStorage->mb);
FREE(pStorage->sliceGroupMap);
ALLOCATE(pStorage->mb, pStorage->picSizeInMbs, mbStorage_t);
ALLOCATE(pStorage->sliceGroupMap, pStorage->picSizeInMbs, u32);
if (pStorage->mb == NULL || pStorage->sliceGroupMap == NULL)
return(MEMORY_ALLOCATION_ERROR);
H264SwDecMemset(pStorage->mb, 0,
pStorage->picSizeInMbs * sizeof(mbStorage_t));
h264bsdInitMbNeighbours(pStorage->mb,
pStorage->activeSps->picWidthInMbs,
pStorage->picSizeInMbs);
/* dpb output reordering disabled if
* 1) application set noReordering flag
* 2) POC type equal to 2
* 3) num_reorder_frames in vui equal to 0 */
if ( pStorage->noReordering ||
pStorage->activeSps->picOrderCntType == 2 ||
(pStorage->activeSps->vuiParametersPresentFlag &&
pStorage->activeSps->vuiParameters->bitstreamRestrictionFlag &&
!pStorage->activeSps->vuiParameters->numReorderFrames) )
flag = HANTRO_TRUE;
else
flag = HANTRO_FALSE;
tmp = h264bsdResetDpb(pStorage->dpb,
pStorage->activeSps->picWidthInMbs *
pStorage->activeSps->picHeightInMbs,
pStorage->activeSps->maxDpbSize,
pStorage->activeSps->numRefFrames,
pStorage->activeSps->maxFrameNum,
flag);
if (tmp != HANTRO_OK)
return(tmp);
}
else if (ppsId != pStorage->activePpsId)
{
/* sequence parameter set shall not change but before an IDR picture */
if (pStorage->pps[ppsId]->seqParameterSetId != pStorage->activeSpsId)
{
DEBUG(("SEQ PARAM SET CHANGING...\n"));
if (isIdr)
{
pStorage->activePpsId = ppsId;
pStorage->activePps = pStorage->pps[ppsId];
pStorage->activeSpsId = pStorage->activePps->seqParameterSetId;
pStorage->activeSps = pStorage->sps[pStorage->activeSpsId];
pStorage->picSizeInMbs =
pStorage->activeSps->picWidthInMbs *
pStorage->activeSps->picHeightInMbs;
pStorage->currImage->width = pStorage->activeSps->picWidthInMbs;
pStorage->currImage->height =
pStorage->activeSps->picHeightInMbs;
pStorage->pendingActivation = HANTRO_TRUE;
}
else
{
DEBUG(("TRYING TO CHANGE SPS IN NON-IDR SLICE\n"));
return(HANTRO_NOK);
}
}
else
{
pStorage->activePpsId = ppsId;
pStorage->activePps = pStorage->pps[ppsId];
}
}
return(HANTRO_OK);
}
|
CWE-119
| 187,789 | 8,383 |
227750239788619637294452536795517206121
| null | null | null |
Android
|
4f236c532039a61f0cf681d2e3c6e022911bbb5c
| 1 |
bool ATSParser::PSISection::isCRCOkay() const {
if (!isComplete()) {
return false;
}
uint8_t* data = mBuffer->data();
if ((data[1] & 0x80) == 0) {
return true;
}
unsigned sectionLength = U16_AT(data + 1) & 0xfff;
ALOGV("sectionLength %u, skip %u", sectionLength, mSkipBytes);
sectionLength -= mSkipBytes;
uint32_t crc = 0xffffffff;
for(unsigned i = 0; i < sectionLength + 4 /* crc */; i++) {
uint8_t b = data[i];
int index = ((crc >> 24) ^ (b & 0xff)) & 0xff;
crc = CRC_TABLE[index] ^ (crc << 8);
}
ALOGV("crc: %08x\n", crc);
return (crc == 0);
}
|
CWE-119
| 187,791 | 8,384 |
180480682085530259924434880842541558636
| null | null | null |
Android
|
dd3546765710ce8dd49eb23901d90345dec8282f
| 1 |
AudioSource::AudioSource(
audio_source_t inputSource, const String16 &opPackageName,
uint32_t sampleRate, uint32_t channelCount, uint32_t outSampleRate)
: mStarted(false),
mSampleRate(sampleRate),
mOutSampleRate(outSampleRate > 0 ? outSampleRate : sampleRate),
mPrevSampleTimeUs(0),
mFirstSampleTimeUs(-1ll),
mNumFramesReceived(0),
mNumClientOwnedBuffers(0) {
ALOGV("sampleRate: %u, outSampleRate: %u, channelCount: %u",
sampleRate, outSampleRate, channelCount);
CHECK(channelCount == 1 || channelCount == 2);
CHECK(sampleRate > 0);
size_t minFrameCount;
status_t status = AudioRecord::getMinFrameCount(&minFrameCount,
sampleRate,
AUDIO_FORMAT_PCM_16_BIT,
audio_channel_in_mask_from_count(channelCount));
if (status == OK) {
uint32_t frameCount = kMaxBufferSize / sizeof(int16_t) / channelCount;
size_t bufCount = 2;
while ((bufCount * frameCount) < minFrameCount) {
bufCount++;
}
mRecord = new AudioRecord(
inputSource, sampleRate, AUDIO_FORMAT_PCM_16_BIT,
audio_channel_in_mask_from_count(channelCount),
opPackageName,
(size_t) (bufCount * frameCount),
AudioRecordCallbackFunction,
this,
frameCount /*notificationFrames*/);
mInitCheck = mRecord->initCheck();
if (mInitCheck != OK) {
mRecord.clear();
}
} else {
mInitCheck = status;
}
}
|
CWE-200
| 187,792 | 8,385 |
310123578239874978996920249676873872018
| null | null | null |
Android
|
864e2e22fcd0cba3f5e67680ccabd0302dfda45d
| 1 |
static ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize) {
const char* name;
size_t namelen;
if (node->graft_path) {
name = node->graft_path;
namelen = node->graft_pathlen;
} else if (node->actual_name) {
name = node->actual_name;
namelen = node->namelen;
} else {
name = node->name;
namelen = node->namelen;
}
if (bufsize < namelen + 1) {
return -1;
}
ssize_t pathlen = 0;
if (node->parent && node->graft_path == NULL) {
pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 2);
if (pathlen < 0) {
return -1;
}
buf[pathlen++] = '/';
}
memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
return pathlen + namelen;
}
|
CWE-264
| 187,796 | 8,388 |
270563786775080326701359378478558715901
| null | null | null |
Android
|
ad40e57890f81a3cf436c5f06da66396010bd9e5
| 1 |
void SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) {
BufferInfo *inInfo = NULL;
OMX_BUFFERHEADERTYPE *inHeader = NULL;
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
if (inHeader) {
if (inHeader->nOffset == 0 && inHeader->nFilledLen) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEos = true;
}
mConfig->pInputBuffer =
inHeader->pBuffer + inHeader->nOffset;
mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
} else {
mConfig->pInputBuffer = NULL;
mConfig->inputBufferCurrentLength = 0;
}
mConfig->inputBufferMaxLength = 0;
mConfig->inputBufferUsedLength = 0;
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
mConfig->pOutputBuffer =
reinterpret_cast<int16_t *>(outHeader->pBuffer);
ERROR_CODE decoderErr;
if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
!= NO_DECODING_ERROR) {
ALOGV("mp3 decoder returned error %d", decoderErr);
if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
&& decoderErr != SIDE_INFO_ERROR) {
ALOGE("mp3 decoder returned error %d", decoderErr);
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
mSignalledError = true;
return;
}
if (mConfig->outputFrameSize == 0) {
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
}
if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) {
if (!mIsFirst) {
outHeader->nOffset = 0;
outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
memset(outHeader->pBuffer, 0, outHeader->nFilledLen);
}
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mSignalledOutputEos = true;
} else {
ALOGV_IF(mIsFirst, "insufficient data for first frame, sending silence");
memset(outHeader->pBuffer,
0,
mConfig->outputFrameSize * sizeof(int16_t));
if (inHeader) {
mConfig->inputBufferUsedLength = inHeader->nFilledLen;
}
}
} else if (mConfig->samplingRate != mSamplingRate
|| mConfig->num_channels != mNumChannels) {
mSamplingRate = mConfig->samplingRate;
mNumChannels = mConfig->num_channels;
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
return;
}
if (mIsFirst) {
mIsFirst = false;
outHeader->nOffset =
kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
outHeader->nFilledLen =
mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
} else if (!mSignalledOutputEos) {
outHeader->nOffset = 0;
outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
}
outHeader->nTimeStamp =
mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
if (inHeader) {
CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
inHeader->nOffset += mConfig->inputBufferUsedLength;
inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
|
CWE-20
| 187,799 | 8,390 |
230108350087941020803506107822067323637
| null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.