// IsRegistered determines if the provided key handle is usable by this token. nsresult U2FSoftTokenManager::IsRegistered(nsTArray<uint8_t>& aKeyHandle, nsTArray<uint8_t>& aAppParam, bool& aResult) { nsNSSShutDownPreventionLock locker; if (NS_WARN_IF(isAlreadyShutDown())) { return NS_ERROR_FAILURE; } if (!mInitialized) { nsresult rv = Init(); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } UniquePK11SlotInfo slot(PK11_GetInternalSlot()); MOZ_ASSERT(slot.get()); // Decode the key handle UniqueSECKEYPrivateKey privKey = PrivateKeyFromKeyHandle(slot, mWrappingKey, aKeyHandle.Elements(), aKeyHandle.Length(), aAppParam.Elements(), aAppParam.Length(), locker); aResult = privKey.get() != nullptr; return NS_OK; }
void WebRenderAPI::GenerateFrame(const nsTArray<WrOpacityProperty>& aOpacityArray, const nsTArray<WrTransformProperty>& aTransformArray) { wr_api_generate_frame_with_properties(mWrApi, aOpacityArray.IsEmpty() ? nullptr : aOpacityArray.Elements(), aOpacityArray.Length(), aTransformArray.IsEmpty() ? nullptr : aTransformArray.Elements(), aTransformArray.Length()); }
bool nsBaseWidget::StoreWindowClipRegion(const nsTArray<nsIntRect>& aRects) { if (mClipRects && mClipRectCount == aRects.Length() && memcmp(mClipRects, aRects.Elements(), sizeof(nsIntRect)*mClipRectCount) == 0) return false; mClipRectCount = aRects.Length(); mClipRects = new nsIntRect[mClipRectCount]; if (mClipRects) { memcpy(mClipRects, aRects.Elements(), sizeof(nsIntRect)*mClipRectCount); } return true; }
bool DWriteFontFileStream::Initialize(uint8_t* aData, uint32_t aSize) { if (!mData.SetLength(aSize, fallible)) { return false; } memcpy(mData.Elements(), aData, aSize); return true; }
nsresult GDIFontEntry::CopyFontTable(uint32_t aTableTag, nsTArray<uint8_t>& aBuffer) { if (!IsTrueType()) { return NS_ERROR_FAILURE; } AutoDC dc; AutoSelectFont font(dc.GetDC(), &mLogFont); if (font.IsValid()) { uint32_t tableSize = ::GetFontData(dc.GetDC(), NativeEndian::swapToBigEndian(aTableTag), 0, nullptr, 0); if (tableSize != GDI_ERROR) { if (aBuffer.SetLength(tableSize, fallible)) { ::GetFontData(dc.GetDC(), NativeEndian::swapToBigEndian(aTableTag), 0, aBuffer.Elements(), tableSize); return NS_OK; } return NS_ERROR_OUT_OF_MEMORY; } } return NS_ERROR_FAILURE; }
void CDMProxy::gmp_Decrypted(uint32_t aId, GMPErr aResult, const nsTArray<uint8_t>& aDecryptedData) { MOZ_ASSERT(IsOnGMPThread()); for (size_t i = 0; i < mDecryptionJobs.Length(); i++) { DecryptJob* job = mDecryptionJobs[i]; if (job->mId == aId) { if (aDecryptedData.Length() != job->mSample->size) { NS_WARNING("CDM returned incorrect number of decrypted bytes"); } if (GMP_SUCCEEDED(aResult)) { PodCopy(job->mSample->data, aDecryptedData.Elements(), std::min<size_t>(aDecryptedData.Length(), job->mSample->size)); job->mClient->Decrypted(GMPNoErr, job->mSample.forget()); } else if (aResult == GMPNoKeyErr) { NS_WARNING("CDM returned GMPNoKeyErr"); // We still have the encrypted sample, so we can re-enqueue it to be // decrypted again once the key is usable again. job->mClient->Decrypted(GMPNoKeyErr, job->mSample.forget()); } else { nsAutoCString str("CDM returned decode failure GMPErr="); str.AppendInt(aResult); NS_WARNING(str.get()); job->mClient->Decrypted(aResult, nullptr); } mDecryptionJobs.RemoveElementAt(i); return; } } NS_WARNING("GMPDecryptorChild returned incorrect job ID"); }
void BluetoothGattClientHALInterface::WriteCharacteristic( int aConnId, const BluetoothGattServiceId& aServiceId, const BluetoothGattId& aCharId, BluetoothGattWriteType aWriteType, BluetoothGattAuthReq aAuthReq, const nsTArray<uint8_t>& aValue, BluetoothGattClientResultHandler* aRes) { bt_status_t status; #if ANDROID_VERSION >= 19 btgatt_srvc_id_t serviceId; btgatt_gatt_id_t charId; int writeType; int authReq; if (NS_SUCCEEDED(Convert(aServiceId, serviceId)) && NS_SUCCEEDED(Convert(aCharId, charId)) && NS_SUCCEEDED(Convert(aWriteType, writeType)) && NS_SUCCEEDED(Convert(aAuthReq, authReq))) { status = mInterface->write_characteristic( aConnId, &serviceId, &charId, writeType, aValue.Length() * sizeof(uint8_t), authReq, reinterpret_cast<char*>(const_cast<uint8_t*>(aValue.Elements()))); } else { status = BT_STATUS_PARM_INVALID; } #else status = BT_STATUS_UNSUPPORTED; #endif if (aRes) { DispatchBluetoothGattClientHALResult( aRes, &BluetoothGattClientResultHandler::WriteCharacteristic, ConvertDefault(status, STATUS_FAIL)); } }
bool ReadIntoArray(nsIFile* aFile, nsTArray<uint8_t>& aOutDst, size_t aMaxLength) { if (!FileExists(aFile)) { return false; } PRFileDesc* fd = nullptr; nsresult rv = aFile->OpenNSPRFileDesc(PR_RDONLY, 0, &fd); if (NS_FAILED(rv)) { return false; } int32_t length = PR_Seek(fd, 0, PR_SEEK_END); PR_Seek(fd, 0, PR_SEEK_SET); if (length < 0 || (size_t)length > aMaxLength) { NS_WARNING("EME file is longer than maximum allowed length"); PR_Close(fd); return false; } aOutDst.SetLength(length); int32_t bytesRead = PR_Read(fd, aOutDst.Elements(), length); PR_Close(fd); return (bytesRead == length); }
static void ReportToConsole(nsIDocument* aDocument, const char* aConsoleStringId, nsTArray<const char16_t*>& aParams) { MOZ_ASSERT(NS_IsMainThread()); MOZ_ASSERT(aDocument); DD_DEBUG("DecoderDoctorDiagnostics.cpp:ReportToConsole(doc=%p) ReportToConsole" " - aMsg='%s' params={%s%s%s%s}", aDocument, aConsoleStringId, aParams.IsEmpty() ? "<no params>" : NS_ConvertUTF16toUTF8(aParams[0]).get(), (aParams.Length() < 1 || !aParams[1]) ? "" : ", ", (aParams.Length() < 1 || !aParams[1]) ? "" : NS_ConvertUTF16toUTF8(aParams[1]).get(), aParams.Length() < 2 ? "" : ", ..."); nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Media"), aDocument, nsContentUtils::eDOM_PROPERTIES, aConsoleStringId, aParams.IsEmpty() ? nullptr : aParams.Elements(), aParams.Length()); }
void InitInputBuffer(const GMPEncryptedBufferMetadata* aCrypto, int64_t aTimestamp, const uint8_t* aData, size_t aDataSize, cdm::InputBuffer &aInputBuffer, nsTArray<cdm::SubsampleEntry> &aSubsamples) { if (aCrypto) { aInputBuffer.key_id = aCrypto->KeyId(); aInputBuffer.key_id_size = aCrypto->KeyIdSize(); aInputBuffer.iv = aCrypto->IV(); aInputBuffer.iv_size = aCrypto->IVSize(); aInputBuffer.num_subsamples = aCrypto->NumSubsamples(); aSubsamples.SetCapacity(aInputBuffer.num_subsamples); const uint16_t* clear = aCrypto->ClearBytes(); const uint32_t* cipher = aCrypto->CipherBytes(); for (size_t i = 0; i < aCrypto->NumSubsamples(); i++) { aSubsamples.AppendElement(cdm::SubsampleEntry(clear[i], cipher[i])); } } aInputBuffer.data = aData; aInputBuffer.data_size = aDataSize; aInputBuffer.subsamples = aSubsamples.Elements(); aInputBuffer.timestamp = aTimestamp; }
// Synchronously consume the given input stream and validate the resulting data // against the given array of expected values. void ConsumeAndValidateStream(nsIInputStream* aStream, const nsTArray<char>& aExpectedData) { nsDependentCSubstring data(aExpectedData.Elements(), aExpectedData.Length()); ConsumeAndValidateStream(aStream, data); }
void DBusThread::EventLoop() { dbus_connection_set_watch_functions(mConnection, AddWatch, RemoveWatch, ToggleWatch, this, NULL); dbus_connection_set_wakeup_main_function(mConnection, DBusWakeup, this, NULL); #ifdef DEBUG LOG("DBus Event Loop Starting\n"); #endif while (1) { poll(mPollData.Elements(), mPollData.Length(), -1); for (uint32_t i = 0; i < mPollData.Length(); i++) { if (!mPollData[i].revents) { continue; } if (mPollData[i].fd == mControlFdR.get()) { char data; while (recv(mControlFdR.get(), &data, sizeof(char), MSG_DONTWAIT) != -1) { switch (data) { case DBUS_EVENT_LOOP_EXIT: #ifdef DEBUG LOG("DBus Event Loop Exiting\n"); #endif dbus_connection_set_watch_functions(mConnection, NULL, NULL, NULL, NULL, NULL); return; case DBUS_EVENT_LOOP_ADD: HandleWatchAdd(this); break; case DBUS_EVENT_LOOP_REMOVE: HandleWatchRemove(this); break; case DBUS_EVENT_LOOP_WAKEUP: // noop break; } } } else { short events = mPollData[i].revents; unsigned int flags = UnixEventsToDBusFlags(events); dbus_watch_handle(mWatchData[i], flags); mPollData[i].revents = 0; // Break at this point since we don't know if the operation // was destructive break; } } while (dbus_connection_dispatch(mConnection) == DBUS_DISPATCH_DATA_REMAINS) {} } }
bool GMPVideoEncoderChild::RecvEncode(const GMPVideoi420FrameData& aInputFrame, const nsTArray<uint8_t>& aCodecSpecificInfo, const nsTArray<GMPVideoFrameType>& aFrameTypes) { if (!mVideoEncoder) { return false; } auto f = new GMPVideoi420FrameImpl(aInputFrame, &mVideoHost); // Ignore any return code. It is OK for this to fail without killing the process. mVideoEncoder->Encode(f, aCodecSpecificInfo.Elements(), aCodecSpecificInfo.Length(), aFrameTypes.Elements(), aFrameTypes.Length()); return true; }
bool GetPreparsedData(HANDLE handle, nsTArray<uint8_t>& data) { UINT size; if (GetRawInputDeviceInfo(handle, RIDI_PREPARSEDDATA, nullptr, &size) == kRawInputError) { return false; } data.SetLength(size); return GetRawInputDeviceInfo(handle, RIDI_PREPARSEDDATA, data.Elements(), &size) > 0; }
WrClipRegionToken DisplayListBuilder::PushClipRegion(const WrRect& aMain, const nsTArray<WrComplexClipRegion>& aComplex, const WrImageMask* aMask) { WRDL_LOG("PushClipRegion r=%s cl=%d m=%p\n", Stringify(aMain).c_str(), (int)aComplex.Length(), aMask); return wr_dp_push_clip_region(mWrState, aMain, aComplex.Elements(), aComplex.Length(), aMask); }
nsCString ToBase64(const nsTArray<uint8_t>& aBytes) { nsAutoCString base64; nsDependentCSubstring raw(reinterpret_cast<const char*>(aBytes.Elements()), aBytes.Length()); nsresult rv = Base64Encode(raw, base64); if (NS_WARN_IF(NS_FAILED(rv))) { return NS_LITERAL_CSTRING("[Base64EncodeFailed]"); } return base64; }
already_AddRefed<GradientStops> gfxGradientCache::GetOrCreateGradientStops(const DrawTarget *aDT, nsTArray<GradientStop>& aStops, ExtendMode aExtend) { if (aDT->IsRecording()) { return aDT->CreateGradientStops(aStops.Elements(), aStops.Length(), aExtend); } RefPtr<GradientStops> gs = GetGradientStops(aDT, aStops, aExtend); if (!gs) { gs = aDT->CreateGradientStops(aStops.Elements(), aStops.Length(), aExtend); if (!gs) { return nullptr; } GradientCacheData *cached = new GradientCacheData(gs, GradientCacheKey(aStops, aExtend, aDT->GetBackendType())); if (!gGradientCache->RegisterEntry(cached)) { delete cached; } } return gs.forget(); }
// The user agent MUST thoroughly validate the Initialization Data before // passing it to the CDM. This includes verifying that the length and // values of fields are reasonable, verifying that values are within // reasonable limits, and stripping irrelevant, unsupported, or unknown // data or fields. It is RECOMMENDED that user agents pre-parse, sanitize, // and/or generate a fully sanitized version of the Initialization Data. // If the Initialization Data format specified by initDataType supports // multiple entries, the user agent SHOULD remove entries that are not // needed by the CDM. The user agent MUST NOT re-order entries within // the Initialization Data. static bool ValidateInitData(const nsTArray<uint8_t>& aInitData, const nsAString& aInitDataType) { if (aInitDataType.LowerCaseEqualsLiteral("webm")) { // WebM initData consists of a single keyId. Ensure it's of reasonable length. return aInitData.Length() <= MAX_KEY_ID_LENGTH; } else if (aInitDataType.LowerCaseEqualsLiteral("cenc")) { // Limit initData to less than 64KB. if (aInitData.Length() > MAX_CENC_INIT_DATA_LENGTH) { return false; } std::vector<std::vector<uint8_t>> keyIds; return ParseCENCInitData(aInitData.Elements(), aInitData.Length(), keyIds); } else if (aInitDataType.LowerCaseEqualsLiteral("keyids")) { if (aInitData.Length() > MAX_KEY_ID_LENGTH) { return false; } // Ensure that init data matches the expected JSON format. mozilla::dom::KeyIdsInitData keyIds; nsString json; nsDependentCSubstring raw(reinterpret_cast<const char*>(aInitData.Elements()), aInitData.Length()); if (NS_FAILED(nsContentUtils::ConvertStringFromEncoding(NS_LITERAL_CSTRING("UTF-8"), raw, json))) { return false; } if (!keyIds.Init(json)) { return false; } if (keyIds.mKids.Length() == 0) { return false; } for (const auto& kid : keyIds.mKids) { if (kid.IsEmpty()) { return false; } } } return true; }
bool GMPDecryptorChild::RecvSetServerCertificate(const uint32_t& aPromiseId, const nsTArray<uint8_t>& aServerCert) { if (!mSession) { return false; } mSession->SetServerCertificate(aPromiseId, aServerCert.Elements(), aServerCert.Length()); return true; }
void MediaDrmProxySupport::UpdateSession(uint32_t aPromiseId, const nsCString& aSessionId, const nsTArray<uint8_t>& aResponse) { MOZ_ASSERT(mBridgeProxy); auto response = mozilla::jni::ByteArray::New(reinterpret_cast<const int8_t*>(aResponse.Elements()), aResponse.Length()); mBridgeProxy->UpdateSession(aPromiseId, NS_ConvertUTF8toUTF16(aSessionId), response); }
void DisplayListBuilder::PushBorderRadialGradient(const WrRect& aBounds, const WrClipRegionToken aClip, const WrBorderWidths& aWidths, const WrPoint& aCenter, const WrSize& aRadius, const nsTArray<WrGradientStop>& aStops, wr::GradientExtendMode aExtendMode, const WrSideOffsets2Df32& aOutset) { wr_dp_push_border_radial_gradient( mWrState, aBounds, aClip, aWidths, aCenter, aRadius, aStops.Elements(), aStops.Length(), aExtendMode, aOutset); }
void SessionMessage(const nsACString& aSessionId, uint32_t aMessageType, const nsTArray<uint8_t>& aMessage) { MonitorAutoLock mon(mMonitor); nsCString msg((const char*)aMessage.Elements(), aMessage.Length()); EXPECT_TRUE(mExpected.Length() > 0); bool matches = mExpected[0].mMessage.Equals(msg); EXPECT_STREQ(mExpected[0].mMessage.get(), msg.get()); if (mExpected.Length() > 0 && matches) { nsCOMPtr<nsIRunnable> continuation = mExpected[0].mContinuation; mExpected.RemoveElementAt(0); if (continuation) { NS_DispatchToCurrentThread(continuation); } } }
void AudioChannelsDownMix(const nsTArray<const void*>& aChannelArray, float** aOutputChannels, uint32_t aOutputChannelCount, uint32_t aDuration) { uint32_t inputChannelCount = aChannelArray.Length(); const void* const* inputChannels = aChannelArray.Elements(); NS_ASSERTION(inputChannelCount > aOutputChannelCount, "Nothing to do"); if (inputChannelCount > 6) { // Just drop the unknown channels. for (uint32_t o = 0; o < aOutputChannelCount; ++o) { memcpy(aOutputChannels[o], inputChannels[o], aDuration*sizeof(float)); } return; } // Ignore unknown channels, they're just dropped. inputChannelCount = std::min<uint32_t>(6, inputChannelCount); const DownMixMatrix& m = gDownMixMatrices[ gMixingMatrixIndexByChannels[aOutputChannelCount - 1] + inputChannelCount - aOutputChannelCount - 1]; // This is slow, but general. We can define custom code for special // cases later. for (uint32_t s = 0; s < aDuration; ++s) { // Reserve an extra junk channel at the end for the cases where we // want an input channel to contribute to nothing float outputChannels[CUSTOM_CHANNEL_LAYOUTS]; memset(outputChannels, 0, sizeof(float)*(CUSTOM_CHANNEL_LAYOUTS - 1)); for (uint32_t c = 0; c < inputChannelCount; ++c) { outputChannels[m.mInputDestination[c]] += m.mInputCoefficient[c]*(static_cast<const float*>(inputChannels[c]))[s]; } // Utilize the fact that in every layout, C is the third channel. if (m.mCExtraDestination != IGNORE) { outputChannels[m.mCExtraDestination] += m.mInputCoefficient[SURROUND_C]*(static_cast<const float*>(inputChannels[SURROUND_C]))[s]; } for (uint32_t c = 0; c < aOutputChannelCount; ++c) { aOutputChannels[c][s] = outputChannels[c]; } } }
void DisplayListBuilder::PushRadialGradient(const WrRect& aBounds, const WrClipRegionToken aClip, const WrPoint& aCenter, const WrSize& aRadius, const nsTArray<WrGradientStop>& aStops, wr::GradientExtendMode aExtendMode, const WrSize aTileSize, const WrSize aTileSpacing) { wr_dp_push_radial_gradient(mWrState, aBounds, aClip, aCenter, aRadius, aStops.Elements(), aStops.Length(), aExtendMode, aTileSize, aTileSpacing); }
bool GMPDecryptorChild::RecvUpdateSession(const uint32_t& aPromiseId, const nsCString& aSessionId, const nsTArray<uint8_t>& aResponse) { if (!mSession) { return false; } mSession->UpdateSession(aPromiseId, aSessionId.get(), aSessionId.Length(), aResponse.Elements(), aResponse.Length()); return true; }
void DisplayListBuilder::PushLinearGradient(const WrRect& aBounds, const WrClipRegionToken aClip, const WrPoint& aStartPoint, const WrPoint& aEndPoint, const nsTArray<WrGradientStop>& aStops, wr::GradientExtendMode aExtendMode, const WrSize aTileSize, const WrSize aTileSpacing) { wr_dp_push_linear_gradient(mWrState, aBounds, aClip, aStartPoint, aEndPoint, aStops.Elements(), aStops.Length(), aExtendMode, aTileSize, aTileSpacing); }
GMPErr Read(const nsCString& aRecordName, nsTArray<uint8_t>& aOutBytes) override { if (!IsOpen(aRecordName)) { return GMPClosedErr; } Record* record = nullptr; mRecords.Get(aRecordName, &record); MOZ_ASSERT(record && !!record->mFileDesc); // IsOpen() guarantees this. // Our error strategy is to report records with invalid contents as // containing 0 bytes. Zero length records are considered "deleted" by // the GMPStorage API. aOutBytes.SetLength(0); int32_t recordLength = 0; nsCString recordName; nsresult err = ReadRecordMetadata(record->mFileDesc, recordLength, recordName); if (NS_FAILED(err) || recordLength == 0) { // We failed to read the record metadata. Or the record is 0 length. // Treat damaged records as empty. // ReadRecordMetadata() could fail if the GMP opened a new record and // tried to read it before anything was written to it.. return GMPNoErr; } if (!aRecordName.Equals(recordName)) { NS_WARNING("Record file contains some other record's contents!"); return GMPRecordCorrupted; } // After calling ReadRecordMetadata, we should be ready to read the // record data. if (PR_Available(record->mFileDesc) != recordLength) { NS_WARNING("Record file length mismatch!"); return GMPRecordCorrupted; } aOutBytes.SetLength(recordLength); int32_t bytesRead = PR_Read(record->mFileDesc, aOutBytes.Elements(), recordLength); return (bytesRead == recordLength) ? GMPNoErr : GMPRecordCorrupted; }
bool GMPVideoEncoderParent::RecvEncoded(const GMPVideoEncodedFrameData& aEncodedFrame, const nsTArray<uint8_t>& aCodecSpecificInfo) { if (!mCallback) { return false; } auto f = new GMPVideoEncodedFrameImpl(aEncodedFrame, &mVideoHost); nsTArray<uint8_t> *codecSpecificInfo = new nsTArray<uint8_t>; codecSpecificInfo->AppendElements((uint8_t*)aCodecSpecificInfo.Elements(), aCodecSpecificInfo.Length()); nsCOMPtr<nsIThread> thread = NS_GetCurrentThread(); mEncodedThread->Dispatch(WrapRunnableNM(&EncodedCallback, mCallback, f, codecSpecificInfo, thread), NS_DISPATCH_NORMAL); return true; }
bool GMPDecryptorChild::RecvCreateSession(const uint32_t& aPromiseId, const nsCString& aInitDataType, const nsTArray<uint8_t>& aInitData, const GMPSessionType& aSessionType) { if (!mSession) { return false; } mSession->CreateSession(aPromiseId, aInitDataType.get(), aInitDataType.Length(), aInitData.Elements(), aInitData.Length(), aSessionType); return true; }
// Write the given number of bytes out to the stream. Loop until expected // bytes count is reached or an error occurs. void Write(nsIOutputStream* aStream, const nsTArray<char>& aData, uint32_t aOffset, uint32_t aNumBytes) { uint32_t remaining = std::min(aNumBytes, static_cast<uint32_t>(aData.Length() - aOffset)); while (remaining > 0) { uint32_t numWritten; nsresult rv = aStream->Write(aData.Elements() + aOffset, remaining, &numWritten); ASSERT_TRUE(NS_SUCCEEDED(rv)); if (numWritten < 1) { break; } aOffset += numWritten; remaining -= numWritten; } }