コード例 #1
0
void
GetFilesTaskChild::SetSuccessRequestResult(const FileSystemResponseValue& aValue,
                                           ErrorResult& aRv)
{
  mFileSystem->AssertIsOnOwningThread();
  MOZ_ASSERT(aValue.type() ==
               FileSystemResponseValue::TFileSystemFilesResponse);

  FileSystemFilesResponse r = aValue;

  if (!mTargetData.SetLength(r.data().Length(), mozilla::fallible_t())) {
    aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
    return;
  }

  for (uint32_t i = 0; i < r.data().Length(); ++i) {
    const FileSystemFileResponse& data = r.data()[i];
    RefPtr<BlobImpl> blobImpl =
      static_cast<BlobChild*>(data.blobChild())->GetBlobImpl();
    MOZ_ASSERT(blobImpl);

    mTargetData[i] = File::Create(mFileSystem->GetParentObject(), blobImpl);
  }
}
コード例 #2
0
ファイル: HttpServer.cpp プロジェクト: cstipkovic/gecko-dev
already_AddRefed<nsITransportProvider>
HttpServer::AcceptWebSocket(InternalRequest* aConnectRequest,
                            const Optional<nsAString>& aProtocol,
                            ErrorResult& aRv)
{
  for (Connection* conn : mConnections) {
    if (!conn->HasPendingWebSocketRequest(aConnectRequest)) {
      continue;
    }
    nsCOMPtr<nsITransportProvider> provider =
      conn->HandleAcceptWebSocket(aProtocol, aRv);
    if (aRv.Failed()) {
      conn->Close();
    }
    // This connection is now owned by the websocket, or we just closed it
    mConnections.RemoveElement(conn);
    return provider.forget();
  }

  aRv.Throw(NS_ERROR_UNEXPECTED);
  MOZ_ASSERT(false, "Unknown request");

  return nullptr;
}
コード例 #3
0
already_AddRefed<Promise>
ServiceWorkerRegistrationMainThread::Update(ErrorResult& aRv)
{
  AssertIsOnMainThread();
  nsCOMPtr<nsIGlobalObject> go = do_QueryInterface(GetOwner());
  if (!go) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  RefPtr<Promise> promise = Promise::Create(go, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  nsCOMPtr<nsIDocument> doc = GetOwner()->GetExtantDoc();
  MOZ_ASSERT(doc);

  RefPtr<MainThreadUpdateCallback> cb =
    new MainThreadUpdateCallback(promise);
  UpdateInternal(doc->NodePrincipal(), mScope, cb);

  return promise.forget();
}
コード例 #4
0
ファイル: Cache.cpp プロジェクト: Jar-win/Waterfox
already_AddRefed<Promise>
Cache::PutAll(const nsTArray<nsRefPtr<Request>>& aRequestList,
              const nsTArray<nsRefPtr<Response>>& aResponseList,
              ErrorResult& aRv)
{
  MOZ_ASSERT(aRequestList.Length() == aResponseList.Length());

  if (NS_WARN_IF(!mActor)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  AutoChildOpArgs args(this, CachePutAllArgs());

  for (uint32_t i = 0; i < aRequestList.Length(); ++i) {
    nsRefPtr<InternalRequest> ir = aRequestList[i]->GetInternalRequest();
    args.Add(ir, ReadBody, TypeErrorOnInvalidScheme, *aResponseList[i], aRv);
    if (NS_WARN_IF(aRv.Failed())) {
      return nullptr;
    }
  }

  return ExecuteOp(args, aRv);
}
コード例 #5
0
// static
already_AddRefed<HTMLImageElement>
HTMLImageElement::Image(const GlobalObject& aGlobal,
                        const Optional<uint32_t>& aWidth,
                        const Optional<uint32_t>& aHeight,
                        ErrorResult& aError)
{
  nsCOMPtr<nsPIDOMWindowInner> win = do_QueryInterface(aGlobal.GetAsSupports());
  nsIDocument* doc;
  if (!win || !(doc = win->GetExtantDoc())) {
    aError.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  already_AddRefed<mozilla::dom::NodeInfo> nodeInfo =
    doc->NodeInfoManager()->GetNodeInfo(nsGkAtoms::img, nullptr,
                                        kNameSpaceID_XHTML,
                                        nsIDOMNode::ELEMENT_NODE);

  RefPtr<HTMLImageElement> img = new HTMLImageElement(nodeInfo);

  if (aWidth.WasPassed()) {
    img->SetWidth(aWidth.Value(), aError);
    if (aError.Failed()) {
      return nullptr;
    }

    if (aHeight.WasPassed()) {
      img->SetHeight(aHeight.Value(), aError);
      if (aError.Failed()) {
        return nullptr;
      }
    }
  }

  return img.forget();
}
コード例 #6
0
// static
already_AddRefed<CacheStorage>
CacheStorage::Constructor(const GlobalObject& aGlobal,
                          CacheStorageNamespace aNamespace,
                          nsIPrincipal* aPrincipal, ErrorResult& aRv)
{
  if (NS_WARN_IF(!NS_IsMainThread())) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  // TODO: remove Namespace in favor of CacheStorageNamespace
  static_assert(DEFAULT_NAMESPACE == (uint32_t)CacheStorageNamespace::Content,
                "Default namespace should match webidl Content enum");
  static_assert(CHROME_ONLY_NAMESPACE == (uint32_t)CacheStorageNamespace::Chrome,
                "Chrome namespace should match webidl Chrome enum");
  static_assert(NUMBER_OF_NAMESPACES == (uint32_t)CacheStorageNamespace::EndGuard_,
                "Number of namespace should match webidl endguard enum");

  Namespace ns = static_cast<Namespace>(aNamespace);
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());

  bool privateBrowsing = false;
  nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(global);
  if (window) {
    nsCOMPtr<nsIDocument> doc = window->GetExtantDoc();
    if (doc) {
      nsCOMPtr<nsILoadContext> loadContext = doc->GetLoadContext();
      privateBrowsing = loadContext && loadContext->UsePrivateBrowsing();
    }
  }

  // Create a CacheStorage object bypassing the trusted origin checks
  // since this is a chrome-only constructor.
  return CreateOnMainThread(ns, global, aPrincipal, privateBrowsing,
                            true /* force trusted origin */, aRv);
}
コード例 #7
0
ファイル: CacheStorage.cpp プロジェクト: LordJZ/gecko-dev
already_AddRefed<Promise>
CacheStorage::Delete(const nsAString& aKey, ErrorResult& aRv)
{
  NS_ASSERT_OWNINGTHREAD(CacheStorage);

  if (NS_WARN_IF(mFailedActor)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  nsRefPtr<Promise> promise = Promise::Create(mGlobal, aRv);
  if (NS_WARN_IF(!promise)) {
    return nullptr;
  }

  nsAutoPtr<Entry> entry(new Entry());
  entry->mPromise = promise;
  entry->mArgs = StorageDeleteArgs(nsString(aKey));

  mPendingRequests.AppendElement(entry.forget());
  MaybeRunPendingRequests();

  return promise.forget();
}
コード例 #8
0
already_AddRefed<DOMSVGPathSeg> DOMSVGPathSegList::Initialize(
    DOMSVGPathSeg& aNewItem, ErrorResult& aError) {
  if (IsAnimValList()) {
    aError.Throw(NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR);
    return nullptr;
  }

  // If aNewItem is already in a list we should insert a clone of aNewItem,
  // and for consistency, this should happen even if *this* is the list that
  // aNewItem is currently in. Note that in the case of aNewItem being in this
  // list, the Clear() call before the InsertItemBefore() call would remove it
  // from this list, and so the InsertItemBefore() call would not insert a
  // clone of aNewItem, it would actually insert aNewItem. To prevent that
  // from happening we have to do the clone here, if necessary.

  RefPtr<DOMSVGPathSeg> domItem = &aNewItem;
  if (aNewItem.HasOwner()) {
    domItem = aNewItem.Clone();
  }

  Clear(aError);
  MOZ_ASSERT(!aError.Failed(), "How could this fail?");
  return InsertItemBefore(*domItem, 0, aError);
}
コード例 #9
0
void
CryptoKey::GetAlgorithm(JSContext* cx, JS::MutableHandle<JSObject*> aRetVal,
                        ErrorResult& aRv) const
{
  bool converted = false;
  JS::RootedValue val(cx);
  switch (mAlgorithm.mType) {
    case KeyAlgorithmProxy::AES:
      converted = ToJSValue(cx, mAlgorithm.mAes, &val);
      break;
    case KeyAlgorithmProxy::HMAC:
      converted = ToJSValue(cx, mAlgorithm.mHmac, &val);
      break;
    case KeyAlgorithmProxy::RSA: {
      RootedDictionary<RsaHashedKeyAlgorithm> rsa(cx);
      mAlgorithm.mRsa.ToKeyAlgorithm(cx, rsa);
      converted = ToJSValue(cx, rsa, &val);
      break;
    }
    case KeyAlgorithmProxy::EC:
      converted = ToJSValue(cx, mAlgorithm.mEc, &val);
      break;
    case KeyAlgorithmProxy::DH: {
      RootedDictionary<DhKeyAlgorithm> dh(cx);
      mAlgorithm.mDh.ToKeyAlgorithm(cx, dh);
      converted = ToJSValue(cx, dh, &val);
      break;
    }
  }
  if (!converted) {
    aRv.Throw(NS_ERROR_DOM_OPERATION_ERR);
    return;
  }

  aRetVal.set(&val.toObject());
}
コード例 #10
0
void
HTMLTextAreaElement::SetSelectionDirection(const nsAString& aDirection,
                                           ErrorResult& aError)
{
  if (mState.IsSelectionCached()) {
    nsITextControlFrame::SelectionDirection dir = nsITextControlFrame::eNone;
    if (aDirection.EqualsLiteral("forward")) {
      dir = nsITextControlFrame::eForward;
    } else if (aDirection.EqualsLiteral("backward")) {
      dir = nsITextControlFrame::eBackward;
    }
    mState.GetSelectionProperties().SetDirection(dir);
    return;
  }

  int32_t start, end;
  nsresult rv = GetSelectionRange(&start, &end);
  if (NS_SUCCEEDED(rv)) {
    rv = SetSelectionRange(start, end, aDirection);
  }
  if (NS_FAILED(rv)) {
    aError.Throw(rv);
  }
}
コード例 #11
0
ファイル: URL.cpp プロジェクト: carriercomm/gecko-dev
/* static */ void
URLMainThread::RevokeObjectURL(const GlobalObject& aGlobal,
                               const nsAString& aURL, ErrorResult& aRv)
{
  MOZ_ASSERT(NS_IsMainThread());
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
  if (!global) {
    aRv.Throw(NS_ERROR_FAILURE);
    return;
  }

  nsIPrincipal* principal = nsContentUtils::ObjectPrincipal(aGlobal.Get());

  NS_LossyConvertUTF16toASCII asciiurl(aURL);

  nsIPrincipal* urlPrincipal =
    nsHostObjectProtocolHandler::GetDataEntryPrincipal(asciiurl);

  if (urlPrincipal && principal->Subsumes(urlPrincipal)) {
    nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
    global->UnregisterHostObjectURI(asciiurl);
    nsHostObjectProtocolHandler::RemoveDataEntry(asciiurl);
  }
}
コード例 #12
0
ファイル: VRDisplay.cpp プロジェクト: bgrins/gecko-dev
already_AddRefed<Promise>
VRDisplay::ExitPresent(ErrorResult& aRv)
{
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
  if (!global) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }


  RefPtr<Promise> promise = Promise::Create(global, aRv);
  NS_ENSURE_TRUE(!aRv.Failed(), nullptr);

  if (!IsPresenting()) {
    // We can not exit a presentation outside of the context that
    // started the presentation.
    promise->MaybeRejectWithUndefined();
  } else {
    promise->MaybeResolve(JS::UndefinedHandleValue);
    ExitPresentInternal();
  }

  return promise.forget();
}
コード例 #13
0
ファイル: AudioBuffer.cpp プロジェクト: luke-chang/gecko-1
AudioBuffer::AudioBuffer(nsPIDOMWindowInner* aWindow,
                         uint32_t aNumberOfChannels,
                         uint32_t aLength,
                         float aSampleRate,
                         ErrorResult& aRv)
  : mOwnerWindow(do_GetWeakReference(aWindow)),
    mSampleRate(aSampleRate)
{
  // Note that a buffer with zero channels is permitted here for the sake of
  // AudioProcessingEvent, where channel counts must match parameters passed
  // to createScriptProcessor(), one of which may be zero.
  if (aSampleRate < WebAudioUtils::MinSampleRate ||
      aSampleRate > WebAudioUtils::MaxSampleRate ||
      aNumberOfChannels > WebAudioUtils::MaxChannelCount ||
      !aLength || aLength > INT32_MAX) {
    aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
    return;
  }

  mSharedChannels.mDuration = aLength;
  mJSChannels.SetLength(aNumberOfChannels);
  mozilla::HoldJSObjects(this);
  AudioBufferMemoryTracker::RegisterAudioBuffer(this);
}
コード例 #14
0
ファイル: FileCreatorHelper.cpp プロジェクト: jld/gecko-dev
/* static */
already_AddRefed<Promise> FileCreatorHelper::CreateFile(
    nsIGlobalObject* aGlobalObject, nsIFile* aFile,
    const ChromeFilePropertyBag& aBag, bool aIsFromNsIFile, ErrorResult& aRv) {
  MOZ_DIAGNOSTIC_ASSERT(NS_IsMainThread());

  RefPtr<Promise> promise = Promise::Create(aGlobalObject, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  nsAutoString path;
  aRv = aFile->GetPath(path);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  // Register this component to PBackground.
  mozilla::ipc::PBackgroundChild* actorChild =
      mozilla::ipc::BackgroundChild::GetOrCreateForCurrentThread();
  if (NS_WARN_IF(!actorChild)) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  Maybe<int64_t> lastModified;
  if (aBag.mLastModified.WasPassed()) {
    lastModified.emplace(aBag.mLastModified.Value());
  }

  PFileCreatorChild* actor = actorChild->SendPFileCreatorConstructor(
      path, aBag.mType, aBag.mName, lastModified, aBag.mExistenceCheck,
      aIsFromNsIFile);

  static_cast<FileCreatorChild*>(actor)->SetPromise(promise);
  return promise.forget();
}
コード例 #15
0
ファイル: AudioBuffer.cpp プロジェクト: MekliCZ/positron
/* static */ already_AddRefed<AudioBuffer>
AudioBuffer::Create(AudioContext* aContext, uint32_t aNumberOfChannels,
                    uint32_t aLength, float aSampleRate,
                    already_AddRefed<ThreadSharedFloatArrayBufferList>
                      aInitialContents,
                    ErrorResult& aRv)
{
  // Note that a buffer with zero channels is permitted here for the sake of
  // AudioProcessingEvent, where channel counts must match parameters passed
  // to createScriptProcessor(), one of which may be zero.
  if (aSampleRate < WebAudioUtils::MinSampleRate ||
      aSampleRate > WebAudioUtils::MaxSampleRate ||
      aNumberOfChannels > WebAudioUtils::MaxChannelCount ||
      !aLength || aLength > INT32_MAX) {
    aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
    return nullptr;
  }

  RefPtr<AudioBuffer> buffer =
    new AudioBuffer(aContext, aNumberOfChannels, aLength, aSampleRate,
                    Move(aInitialContents));

  return buffer.forget();
}
コード例 #16
0
bool ScreenOrientation::LockDeviceOrientation(
    hal::ScreenOrientation aOrientation, bool aIsFullscreen, ErrorResult& aRv) {
  if (!GetOwner()) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return false;
  }

  nsCOMPtr<EventTarget> target = GetOwner()->GetDoc();
  // We need to register a listener so we learn when we leave fullscreen
  // and when we will have to unlock the screen.
  // This needs to be done before LockScreenOrientation call to make sure
  // the locking can be unlocked.
  if (aIsFullscreen && !target) {
    return false;
  }

  if (NS_WARN_IF(!hal::LockScreenOrientation(aOrientation))) {
    return false;
  }

  // We are fullscreen and lock has been accepted.
  if (aIsFullscreen) {
    if (!mFullscreenListener) {
      mFullscreenListener = new FullscreenEventListener();
    }

    aRv = target->AddSystemEventListener(NS_LITERAL_STRING("fullscreenchange"),
                                         mFullscreenListener,
                                         /* useCapture = */ true);
    if (NS_WARN_IF(aRv.Failed())) {
      return false;
    }
  }

  return true;
}
コード例 #17
0
already_AddRefed<Promise>
CacheStorage::Keys(ErrorResult& aRv)
{
  NS_ASSERT_OWNINGTHREAD(CacheStorage);

  if (NS_WARN_IF(NS_FAILED(mStatus))) {
    aRv.Throw(mStatus);
    return nullptr;
  }

  RefPtr<Promise> promise = Promise::Create(mGlobal, aRv);
  if (NS_WARN_IF(!promise)) {
    return nullptr;
  }

  nsAutoPtr<Entry> entry(new Entry());
  entry->mPromise = promise;
  entry->mArgs = StorageKeysArgs();

  mPendingRequests.AppendElement(entry.forget());
  MaybeRunPendingRequests();

  return promise.forget();
}
コード例 #18
0
void
nsDOMTokenList::Replace(const nsAString& aToken,
                        const nsAString& aNewToken,
                        ErrorResult& aError)
{
  // Doing this here instead of using `CheckToken` because if aToken had invalid
  // characters, and aNewToken is empty, the returned error should be a
  // SyntaxError, not an InvalidCharacterError.
  if (aNewToken.IsEmpty()) {
    aError.Throw(NS_ERROR_DOM_SYNTAX_ERR);
    return;
  }

  aError = CheckToken(aToken);
  if (aError.Failed()) {
    return;
  }

  aError = CheckToken(aNewToken);
  if (aError.Failed()) {
    return;
  }

  const nsAttrValue* attr = GetParsedAttr();
  if (!attr || !attr->Contains(aToken)) {
    return;
  }

  AutoTArray<nsString, 1> tokens;

  tokens.AppendElement(aToken);
  RemoveInternal(attr, tokens);

  tokens[0] = aNewToken;
  AddInternal(attr, tokens);
}
コード例 #19
0
already_AddRefed<PeriodicWave>
AudioContext::CreatePeriodicWave(const Float32Array& aRealData,
                                 const Float32Array& aImagData,
                                 const PeriodicWaveConstraints& aConstraints,
                                 ErrorResult& aRv)
{
  aRealData.ComputeLengthAndData();
  aImagData.ComputeLengthAndData();

  if (aRealData.Length() != aImagData.Length() ||
      aRealData.Length() == 0) {
    aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
    return nullptr;
  }

  RefPtr<PeriodicWave> periodicWave =
    new PeriodicWave(this, aRealData.Data(), aImagData.Data(),
                     aImagData.Length(), aConstraints.mDisableNormalization,
                     aRv);
  if (aRv.Failed()) {
    return nullptr;
  }
  return periodicWave.forget();
}
コード例 #20
0
void AnonymousContent::SetCutoutRectsForElement(
    const nsAString& aElementId, const Sequence<OwningNonNull<DOMRect>>& aRects,
    ErrorResult& aRv) {
  Element* element = GetElementById(aElementId);

  if (!element) {
    aRv.Throw(NS_ERROR_NOT_AVAILABLE);
    return;
  }

  nsRegion cutOutRegion;
  for (const auto& r : aRects) {
    CSSRect rect(r->X(), r->Y(), r->Width(), r->Height());
    cutOutRegion.OrWith(CSSRect::ToAppUnits(rect));
  }

  element->SetProperty(nsGkAtoms::cutoutregion, new nsRegion(cutOutRegion),
                       nsINode::DeleteProperty<nsRegion>);

  nsIFrame* frame = element->GetPrimaryFrame();
  if (frame) {
    frame->SchedulePaint();
  }
}
コード例 #21
0
/* static */ void
URLMainThread::CreateObjectURL(const GlobalObject& aGlobal, Blob& aBlob,
                               nsAString& aResult, ErrorResult& aRv)
{
  MOZ_ASSERT(NS_IsMainThread());

  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
  if (NS_WARN_IF(!global)) {
    aRv.Throw(NS_ERROR_FAILURE);
    return;
  }

  nsCOMPtr<nsIPrincipal> principal =
    nsContentUtils::ObjectPrincipal(aGlobal.Get());

  nsAutoCString url;
  aRv = BlobURLProtocolHandler::AddDataEntry(aBlob.Impl(), principal, url);
  if (NS_WARN_IF(aRv.Failed())) {
    return;
  }

  global->RegisterHostObjectURI(url);
  CopyASCIItoUTF16(url, aResult);
}
コード例 #22
0
ファイル: Icc.cpp プロジェクト: MichaelKohler/gecko-dev
void
Icc::SendStkTimerExpiration(const JSContext* aCx, JS::Handle<JS::Value> aTimer,
                            ErrorResult& aRv)
{
  if (!mHandler) {
    aRv.Throw(NS_ERROR_FAILURE);
    return;
  }

  nsCOMPtr<nsIStkCmdFactory> cmdFactory =
    do_GetService(ICC_STK_CMD_FACTORY_CONTRACTID);
  if (!cmdFactory) {
    aRv.Throw(NS_ERROR_FAILURE);
    return;
  }

  nsCOMPtr<nsIStkTimer> timer;
  cmdFactory->CreateTimer(aTimer, getter_AddRefs(timer));
  if (!timer) {
    aRv.Throw(NS_ERROR_FAILURE);
    return;
  }

  uint16_t timerId;
  nsresult rv = timer->GetTimerId(&timerId);
  if (NS_FAILED(rv)) {
    aRv.Throw(rv);
  }

  uint32_t timerValue;
  rv = timer->GetTimerValue(&timerValue);
  if (NS_FAILED(rv)) {
    aRv.Throw(rv);
  }

  rv = mHandler->SendStkTimerExpiration(timerId, timerValue);
  if (NS_FAILED(rv)) {
    aRv.Throw(rv);
  }
}
コード例 #23
0
ファイル: IDBDatabase.cpp プロジェクト: 70599/Waterfox
void
IDBDatabase::DeleteObjectStore(const nsAString& aName, ErrorResult& aRv)
{
  AssertIsOnOwningThread();

  IDBTransaction* transaction = IDBTransaction::GetCurrent();
  if (!transaction ||
      transaction->Database() != this ||
      transaction->GetMode() != IDBTransaction::VERSION_CHANGE) {
    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
    return;
  }

  if (!transaction->IsOpen()) {
    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
    return;
  }

  nsTArray<ObjectStoreSpec>& specArray = mSpec->objectStores();

  int64_t objectStoreId = 0;

  for (uint32_t specCount = specArray.Length(), specIndex = 0;
       specIndex < specCount;
       specIndex++) {
    const ObjectStoreMetadata& metadata = specArray[specIndex].metadata();
    MOZ_ASSERT(metadata.id());

    if (aName == metadata.name()) {
      objectStoreId = metadata.id();

      // Must do this before altering the metadata array!
      transaction->DeleteObjectStore(objectStoreId);

      specArray.RemoveElementAt(specIndex);

      RefreshSpec(/* aMayDelete */ false);
      break;
    }
  }

  if (!objectStoreId) {
    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR);
    return;
  }

  // Don't do this in the macro because we always need to increment the serial
  // number to keep in sync with the parent.
  const uint64_t requestSerialNumber = IDBRequest::NextSerialNumber();

  IDB_LOG_MARK("IndexedDB %s: Child  Transaction[%lld] Request[%llu]: "
                 "database(%s).transaction(%s).deleteObjectStore(\"%s\")",
               "IndexedDB %s: C T[%lld] R[%llu]: "
                 "IDBDatabase.deleteObjectStore()",
               IDB_LOG_ID_STRING(),
               transaction->LoggingSerialNumber(),
               requestSerialNumber,
               IDB_LOG_STRINGIFY(this),
               IDB_LOG_STRINGIFY(transaction),
               NS_ConvertUTF16toUTF8(aName).get());
}
コード例 #24
0
ファイル: IDBDatabase.cpp プロジェクト: 70599/Waterfox
already_AddRefed<IDBObjectStore>
IDBDatabase::CreateObjectStore(
                            const nsAString& aName,
                            const IDBObjectStoreParameters& aOptionalParameters,
                            ErrorResult& aRv)
{
  AssertIsOnOwningThread();

  IDBTransaction* transaction = IDBTransaction::GetCurrent();
  if (!transaction ||
      transaction->Database() != this ||
      transaction->GetMode() != IDBTransaction::VERSION_CHANGE) {
    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
    return nullptr;
  }

  if (!transaction->IsOpen()) {
    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
    return nullptr;
  }

  KeyPath keyPath(0);
  if (NS_FAILED(KeyPath::Parse(aOptionalParameters.mKeyPath, &keyPath))) {
    aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
    return nullptr;
  }

  nsTArray<ObjectStoreSpec>& objectStores = mSpec->objectStores();
  for (uint32_t count = objectStores.Length(), index = 0;
       index < count;
       index++) {
    if (aName == objectStores[index].metadata().name()) {
      aRv.Throw(NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR);
      return nullptr;
    }
  }

  if (!keyPath.IsAllowedForObjectStore(aOptionalParameters.mAutoIncrement)) {
    aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_ERR);
    return nullptr;
  }

  const ObjectStoreSpec* oldSpecElements =
    objectStores.IsEmpty() ? nullptr : objectStores.Elements();

  ObjectStoreSpec* newSpec = objectStores.AppendElement();
  newSpec->metadata() =
    ObjectStoreMetadata(transaction->NextObjectStoreId(), nsString(aName),
                        keyPath, aOptionalParameters.mAutoIncrement);

  if (oldSpecElements &&
      oldSpecElements != objectStores.Elements()) {
    MOZ_ASSERT(objectStores.Length() > 1);

    // Array got moved, update the spec pointers for all live objectStores and
    // indexes.
    RefreshSpec(/* aMayDelete */ false);
  }

  RefPtr<IDBObjectStore> objectStore =
    transaction->CreateObjectStore(*newSpec);
  MOZ_ASSERT(objectStore);

  // Don't do this in the macro because we always need to increment the serial
  // number to keep in sync with the parent.
  const uint64_t requestSerialNumber = IDBRequest::NextSerialNumber();

  IDB_LOG_MARK("IndexedDB %s: Child  Transaction[%lld] Request[%llu]: "
                 "database(%s).transaction(%s).createObjectStore(%s)",
               "IndexedDB %s: C T[%lld] R[%llu]: "
                 "IDBDatabase.createObjectStore()",
               IDB_LOG_ID_STRING(),
               transaction->LoggingSerialNumber(),
               requestSerialNumber,
               IDB_LOG_STRINGIFY(this),
               IDB_LOG_STRINGIFY(transaction),
               IDB_LOG_STRINGIFY(objectStore));

  return objectStore.forget();
}
コード例 #25
0
void
nsGenericHTMLFrameElement::SwapFrameLoaders(nsXULElement& aOtherOwner,
                                            ErrorResult& aError)
{
  aError.Throw(NS_ERROR_NOT_IMPLEMENTED);
}
コード例 #26
0
ファイル: XPathExpression.cpp プロジェクト: bgrins/gecko-dev
already_AddRefed<XPathResult>
XPathExpression::EvaluateWithContext(nsINode& aContextNode,
                                     uint32_t aContextPosition,
                                     uint32_t aContextSize,
                                     uint16_t aType,
                                     XPathResult* aInResult,
                                     ErrorResult& aRv)
{
    if (aContextPosition > aContextSize) {
        aRv.Throw(NS_ERROR_FAILURE);
        return nullptr;
    }

    if (!nsContentUtils::LegacyIsCallerNativeCode() &&
        !nsContentUtils::CanCallerAccess(&aContextNode))
    {
        aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
        return nullptr;
    }

    if (mCheckDocument) {
        nsCOMPtr<nsIDocument> doc = do_QueryReferent(mDocument);
        if (doc != aContextNode.OwnerDoc()) {
            aRv.Throw(NS_ERROR_DOM_WRONG_DOCUMENT_ERR);
            return nullptr;
        }
    }

    uint16_t nodeType = aContextNode.NodeType();

    if (nodeType == nsIDOMNode::TEXT_NODE ||
        nodeType == nsIDOMNode::CDATA_SECTION_NODE) {
        nsCOMPtr<nsIDOMCharacterData> textNode =
            do_QueryInterface(&aContextNode);
        if (!textNode) {
            aRv.Throw(NS_ERROR_FAILURE);
            return nullptr;
        }

        uint32_t textLength;
        textNode->GetLength(&textLength);
        if (textLength == 0) {
            aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
            return nullptr;
        }

        // XXX Need to get logical XPath text node for CDATASection
        //     and Text nodes.
    }
    else if (nodeType != nsIDOMNode::DOCUMENT_NODE &&
             nodeType != nsIDOMNode::ELEMENT_NODE &&
             nodeType != nsIDOMNode::ATTRIBUTE_NODE &&
             nodeType != nsIDOMNode::COMMENT_NODE &&
             nodeType != nsIDOMNode::PROCESSING_INSTRUCTION_NODE) {
        aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
        return nullptr;
    }

    nsAutoPtr<txXPathNode> contextNode(txXPathNativeNode::createXPathNode(&aContextNode));
    if (!contextNode) {
      aRv.Throw(NS_ERROR_FAILURE);
      return nullptr;
    }

    EvalContextImpl eContext(*contextNode, aContextPosition, aContextSize,
                             mRecycler);
    RefPtr<txAExprResult> exprResult;
    aRv = mExpression->evaluate(&eContext, getter_AddRefs(exprResult));
    if (aRv.Failed()) {
        return nullptr;
    }

    uint16_t resultType = aType;
    if (aType == XPathResult::ANY_TYPE) {
        short exprResultType = exprResult->getResultType();
        switch (exprResultType) {
            case txAExprResult::NUMBER:
                resultType = XPathResult::NUMBER_TYPE;
                break;
            case txAExprResult::STRING:
                resultType = XPathResult::STRING_TYPE;
                break;
            case txAExprResult::BOOLEAN:
                resultType = XPathResult::BOOLEAN_TYPE;
                break;
            case txAExprResult::NODESET:
                resultType = XPathResult::UNORDERED_NODE_ITERATOR_TYPE;
                break;
            case txAExprResult::RESULT_TREE_FRAGMENT:
                aRv.Throw(NS_ERROR_FAILURE);
                return nullptr;
        }
    }

    RefPtr<XPathResult> xpathResult = aInResult;
    if (!xpathResult) {
        xpathResult = new XPathResult(&aContextNode);
    }

    aRv = xpathResult->SetExprResult(exprResult, resultType, &aContextNode);

    return xpathResult.forget();
}
コード例 #27
0
ファイル: BroadcastChannel.cpp プロジェクト: heiher/gecko-dev
/* static */ already_AddRefed<BroadcastChannel>
BroadcastChannel::Constructor(const GlobalObject& aGlobal,
                              const nsAString& aChannel,
                              ErrorResult& aRv)
{
  nsCOMPtr<nsPIDOMWindowInner> window =
    do_QueryInterface(aGlobal.GetAsSupports());
  // Window is null in workers.

  RefPtr<BroadcastChannel> bc = new BroadcastChannel(window, aChannel);

  nsAutoCString origin;
  PrincipalInfo principalInfo;

  if (NS_IsMainThread()) {
    nsCOMPtr<nsIGlobalObject> incumbent = mozilla::dom::GetIncumbentGlobal();

    if (!incumbent) {
      aRv.Throw(NS_ERROR_FAILURE);
      return nullptr;
    }

    nsIPrincipal* principal = incumbent->PrincipalOrNull();
    if (!principal) {
      aRv.Throw(NS_ERROR_UNEXPECTED);
      return nullptr;
    }

    aRv = principal->GetOrigin(origin);
    if (NS_WARN_IF(aRv.Failed())) {
      return nullptr;
    }

    aRv = PrincipalToPrincipalInfo(principal, &principalInfo);
    if (NS_WARN_IF(aRv.Failed())) {
      return nullptr;
    }
  } else {
    JSContext* cx = aGlobal.Context();

    WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(cx);
    MOZ_ASSERT(workerPrivate);

    RefPtr<StrongWorkerRef> workerRef =
      StrongWorkerRef::Create(workerPrivate, "BroadcastChannel",
                              [bc] () { bc->Shutdown(); });
    // We are already shutting down the worker. Let's return a non-active
    // object.
    if (NS_WARN_IF(!workerRef)) {
      aRv.Throw(NS_ERROR_FAILURE);
      return nullptr;
    }

    RefPtr<ThreadSafeWorkerRef> tsr = new ThreadSafeWorkerRef(workerRef);

    RefPtr<InitializeRunnable> runnable =
      new InitializeRunnable(tsr, origin, principalInfo, aRv);
    runnable->Dispatch(Canceling, aRv);
    if (aRv.Failed()) {
      return nullptr;
    }

    bc->mWorkerRef = Move(workerRef);
  }

  // Register this component to PBackground.
  PBackgroundChild* actorChild = BackgroundChild::GetOrCreateForCurrentThread();
  if (NS_WARN_IF(!actorChild)) {
    // Firefox is probably shutting down. Let's return a 'generic' error.
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  PBroadcastChannelChild* actor =
    actorChild->SendPBroadcastChannelConstructor(principalInfo, origin,
                                                 nsString(aChannel));

  bc->mActor = static_cast<BroadcastChannelChild*>(actor);
  MOZ_ASSERT(bc->mActor);

  bc->mActor->SetParent(bc);

  return bc.forget();
}
コード例 #28
0
already_AddRefed<Promise>
MobileMessageManager::SetSmscAddress(const SmscAddress& aSmscAddress,
                                     const Optional<uint32_t>& aServiceId,
                                     ErrorResult& aRv)
{
  nsCOMPtr<nsISmsService> smsService = do_GetService(SMS_SERVICE_CONTRACTID);
  if (!smsService) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  // Use the default one unless |serviceId| is available.
  uint32_t serviceId;
  nsresult rv;
  if (aServiceId.WasPassed()) {
    serviceId = aServiceId.Value();
  } else {
    rv = smsService->GetSmsDefaultServiceId(&serviceId);
    if (NS_FAILED(rv)) {
      aRv.Throw(rv);
      return nullptr;
    }
  }

  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
  if (!window) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(window);
  if (!global) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  RefPtr<Promise> promise = Promise::Create(global, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  if (!aSmscAddress.mAddress.WasPassed()) {
    NS_WARNING("SmscAddress.address is a mandatory field and can not be omitted.");
    promise->MaybeReject(NS_ERROR_DOM_INVALID_ACCESS_ERR);
    return promise.forget();
  }

  nsString address = aSmscAddress.mAddress.Value();
  TypeOfNumber ton = aSmscAddress.mTypeOfAddress.mTypeOfNumber;
  NumberPlanIdentification npi =
    aSmscAddress.mTypeOfAddress.mNumberPlanIdentification;

  // If the address begins with +, set TON to international no matter what has
  // passed in.
  if (!address.IsEmpty() && address[0] == '+') {
    ton = TypeOfNumber::International;
  }

  nsCOMPtr<nsIMobileMessageCallback> msgCallback =
    new MobileMessageCallback(promise);

  rv = smsService->SetSmscAddress(serviceId, address,
    static_cast<uint32_t>(ton), static_cast<uint32_t>(npi), msgCallback);
  if (NS_FAILED(rv)) {
    promise->MaybeReject(rv);
    return promise.forget();
  }

  return promise.forget();
}
コード例 #29
0
already_AddRefed<DOMCursor>
MobileMessageManager::GetMessages(const MobileMessageFilter& aFilter,
                                  bool aReverse,
                                  ErrorResult& aRv)
{
  nsCOMPtr<nsIMobileMessageDatabaseService> dbService =
    do_GetService(MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
  if (!dbService) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  bool hasStartDate = !aFilter.mStartDate.IsNull();
  uint64_t startDate = 0;
  if (hasStartDate) {
    startDate = aFilter.mStartDate.Value();
  }

  bool hasEndDate = !aFilter.mEndDate.IsNull();
  uint64_t endDate = 0;
  if (hasEndDate) {
    endDate = aFilter.mEndDate.Value();
  }

  UniquePtr<const char16_t*[]> ptrNumbers;
  uint32_t numbersCount = 0;
  if (!aFilter.mNumbers.IsNull() &&
      aFilter.mNumbers.Value().Length()) {
    const FallibleTArray<nsString>& numbers = aFilter.mNumbers.Value();
    uint32_t index;

    numbersCount = numbers.Length();
    ptrNumbers = MakeUnique<const char16_t*[]>(numbersCount);
    for (index = 0; index < numbersCount; index++) {
      ptrNumbers[index] = numbers[index].get();
    }
  }

  nsString delivery;
  delivery.SetIsVoid(true);
  if (!aFilter.mDelivery.IsNull()) {
    const uint32_t index = static_cast<uint32_t>(aFilter.mDelivery.Value());
    const EnumEntry& entry =
      MobileMessageFilterDeliveryValues::strings[index];
    delivery.AssignASCII(entry.value, entry.length);
  }

  bool hasRead = !aFilter.mRead.IsNull();
  bool read = false;
  if (hasRead) {
    read = aFilter.mRead.Value();
  }

  bool hasThreadId = !aFilter.mThreadId.IsNull();
  uint64_t threadId = 0;
  if (hasThreadId) {
    threadId = aFilter.mThreadId.Value();
  }

  RefPtr<MobileMessageCursorCallback> cursorCallback =
    new MobileMessageCursorCallback();
  nsCOMPtr<nsICursorContinueCallback> continueCallback;
  nsresult rv = dbService->CreateMessageCursor(hasStartDate, startDate,
                                               hasEndDate, endDate,
                                               ptrNumbers.get(), numbersCount,
                                               delivery,
                                               hasRead, read,
                                               hasThreadId, threadId,
                                               aReverse, cursorCallback,
                                               getter_AddRefs(continueCallback));
  if (NS_FAILED(rv)) {
    aRv.Throw(rv);
    return nullptr;
  }

  nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
  if (!window) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  cursorCallback->mDOMCursor =
    new MobileMessageCursor(window, continueCallback);

  RefPtr<DOMCursor> cursor(cursorCallback->mDOMCursor);
  return cursor.forget();
}
コード例 #30
0
ファイル: IDBFactory.cpp プロジェクト: leplatrem/gecko-dev
already_AddRefed<IDBOpenDBRequest>
IDBFactory::OpenInternal(JSContext* aCx,
                         nsIPrincipal* aPrincipal,
                         const nsAString& aName,
                         const Optional<uint64_t>& aVersion,
                         const Optional<StorageType>& aStorageType,
                         bool aDeleting,
                         ErrorResult& aRv)
{
    MOZ_ASSERT(mWindow || mOwningObject);
    MOZ_ASSERT_IF(!mWindow, !mPrivateBrowsingMode);

    CommonFactoryRequestParams commonParams;
    commonParams.privateBrowsingMode() = mPrivateBrowsingMode;

    PrincipalInfo& principalInfo = commonParams.principalInfo();

    if (aPrincipal) {
        if (!NS_IsMainThread()) {
            MOZ_CRASH("Figure out security checks for workers!");
        }
        MOZ_ASSERT(nsContentUtils::IsCallerChrome());

        if (NS_WARN_IF(NS_FAILED(PrincipalToPrincipalInfo(aPrincipal,
                                 &principalInfo)))) {
            IDB_REPORT_INTERNAL_ERR();
            aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
            return nullptr;
        }

        if (principalInfo.type() != PrincipalInfo::TContentPrincipalInfo &&
                principalInfo.type() != PrincipalInfo::TSystemPrincipalInfo) {
            IDB_REPORT_INTERNAL_ERR();
            aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
            return nullptr;
        }
    } else {
        principalInfo = *mPrincipalInfo;
    }

    uint64_t version = 0;
    if (!aDeleting && aVersion.WasPassed()) {
        if (aVersion.Value() < 1) {
            aRv.ThrowTypeError<MSG_INVALID_VERSION>();
            return nullptr;
        }
        version = aVersion.Value();
    }

    // Nothing can be done here if we have previously failed to create a
    // background actor.
    if (mBackgroundActorFailed) {
        IDB_REPORT_INTERNAL_ERR();
        aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
        return nullptr;
    }

    PersistenceType persistenceType;

    if (principalInfo.type() == PrincipalInfo::TSystemPrincipalInfo) {
        // Chrome privilege always gets persistent storage.
        persistenceType = PERSISTENCE_TYPE_PERSISTENT;
    } else {
        persistenceType = PersistenceTypeFromStorage(aStorageType);
    }

    DatabaseMetadata& metadata = commonParams.metadata();
    metadata.name() = aName;
    metadata.persistenceType() = persistenceType;

    FactoryRequestParams params;
    if (aDeleting) {
        metadata.version() = 0;
        params = DeleteDatabaseRequestParams(commonParams);
    } else {
        metadata.version() = version;
        params = OpenDatabaseRequestParams(commonParams);
    }

    if (!mBackgroundActor && mPendingRequests.IsEmpty()) {
        BackgroundChildImpl::ThreadLocal* threadLocal =
            BackgroundChildImpl::GetThreadLocalForCurrentThread();

        nsAutoPtr<ThreadLocal> newIDBThreadLocal;
        ThreadLocal* idbThreadLocal;

        if (threadLocal && threadLocal->mIndexedDBThreadLocal) {
            idbThreadLocal = threadLocal->mIndexedDBThreadLocal;
        } else {
            nsCOMPtr<nsIUUIDGenerator> uuidGen =
                do_GetService("@mozilla.org/uuid-generator;1");
            MOZ_ASSERT(uuidGen);

            nsID id;
            MOZ_ALWAYS_SUCCEEDS(uuidGen->GenerateUUIDInPlace(&id));

            newIDBThreadLocal = idbThreadLocal = new ThreadLocal(id);
        }

        if (PBackgroundChild* actor = BackgroundChild::GetForCurrentThread()) {
            BackgroundActorCreated(actor, idbThreadLocal->GetLoggingInfo());
        } else {
            // We need to start the sequence to create a background actor for this
            // thread.
            RefPtr<BackgroundCreateCallback> cb =
                new BackgroundCreateCallback(this, idbThreadLocal->GetLoggingInfo());
            if (NS_WARN_IF(!BackgroundChild::GetOrCreateForCurrentThread(cb))) {
                IDB_REPORT_INTERNAL_ERR();
                aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
                return nullptr;
            }
        }

        if (newIDBThreadLocal) {
            if (!threadLocal) {
                threadLocal = BackgroundChildImpl::GetThreadLocalForCurrentThread();
            }
            MOZ_ASSERT(threadLocal);
            MOZ_ASSERT(!threadLocal->mIndexedDBThreadLocal);

            threadLocal->mIndexedDBThreadLocal = newIDBThreadLocal.forget();
        }
    }

    RefPtr<IDBOpenDBRequest> request;

    if (mWindow) {
        JS::Rooted<JSObject*> scriptOwner(aCx,
                                          nsGlobalWindow::Cast(mWindow.get())->FastGetGlobalJSObject());
        MOZ_ASSERT(scriptOwner);

        request = IDBOpenDBRequest::CreateForWindow(aCx, this, mWindow, scriptOwner);
    } else {
        JS::Rooted<JSObject*> scriptOwner(aCx, mOwningObject);

        request = IDBOpenDBRequest::CreateForJS(aCx, this, scriptOwner);
        if (!request) {
            MOZ_ASSERT(!NS_IsMainThread());
            aRv.ThrowUncatchableException();
            return nullptr;
        }
    }

    MOZ_ASSERT(request);

    if (aDeleting) {
        IDB_LOG_MARK("IndexedDB %s: Child  Request[%llu]: "
                     "indexedDB.deleteDatabase(\"%s\")",
                     "IndexedDB %s: C R[%llu]: IDBFactory.deleteDatabase()",
                     IDB_LOG_ID_STRING(),
                     request->LoggingSerialNumber(),
                     NS_ConvertUTF16toUTF8(aName).get());
    } else {
        IDB_LOG_MARK("IndexedDB %s: Child  Request[%llu]: "
                     "indexedDB.open(\"%s\", %s)",
                     "IndexedDB %s: C R[%llu]: IDBFactory.open()",
                     IDB_LOG_ID_STRING(),
                     request->LoggingSerialNumber(),
                     NS_ConvertUTF16toUTF8(aName).get(),
                     IDB_LOG_STRINGIFY(aVersion));
    }

    // If we already have a background actor then we can start this request now.
    if (mBackgroundActor) {
        nsresult rv = InitiateRequest(request, params);
        if (NS_WARN_IF(NS_FAILED(rv))) {
            IDB_REPORT_INTERNAL_ERR();
            aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
            return nullptr;
        }
    } else {
        mPendingRequests.AppendElement(new PendingRequestInfo(request, params));
    }

    return request.forget();
}