Bug 910412 - Implement |getRoot|, |createDirectory| and |get| for Directory. r=dhylands, r=smaug
authorYuan Xulei <xyuan@mozilla.com>
Wed, 05 Mar 2014 11:25:40 +0800
changeset 191839 7e61acb41c3f60f4f220072a0be40d6323b6dde5
parent 191838 ed100a12c75fa1d06b87c431d32a9579173881a4
child 191840 b1886a252ed6914c8d2c1887242d9b0ae6589a3d
push id474
push userasasaki@mozilla.com
push dateMon, 02 Jun 2014 21:01:02 +0000
treeherdermozilla-release@967f4cf1b31c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersdhylands, smaug
bugs910412
milestone30.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 910412 - Implement |getRoot|, |createDirectory| and |get| for Directory. r=dhylands, r=smaug
dom/base/domerr.msg
dom/devicestorage/DeviceStorage.h
dom/devicestorage/nsDeviceStorage.cpp
dom/filesystem/CreateDirectoryTask.cpp
dom/filesystem/CreateDirectoryTask.h
dom/filesystem/DeviceStorageFileSystem.cpp
dom/filesystem/DeviceStorageFileSystem.h
dom/filesystem/Directory.cpp
dom/filesystem/Directory.h
dom/filesystem/FileSystemBase.cpp
dom/filesystem/FileSystemBase.h
dom/filesystem/FileSystemRequestParent.cpp
dom/filesystem/FileSystemRequestParent.h
dom/filesystem/FileSystemTaskBase.cpp
dom/filesystem/FileSystemTaskBase.h
dom/filesystem/FileSystemUtils.cpp
dom/filesystem/FileSystemUtils.h
dom/filesystem/GetFileOrDirectoryTask.cpp
dom/filesystem/GetFileOrDirectoryTask.h
dom/filesystem/PFileSystemRequest.ipdl
dom/filesystem/moz.build
dom/ipc/ContentChild.cpp
dom/ipc/ContentChild.h
dom/ipc/ContentParent.cpp
dom/ipc/ContentParent.h
dom/ipc/PContent.ipdl
dom/ipc/moz.build
dom/promise/Promise.h
xpcom/base/ErrorList.h
xpcom/base/nsError.h
--- a/dom/base/domerr.msg
+++ b/dom/base/domerr.msg
@@ -64,16 +64,24 @@ DOM4_MSG_DEF(InvalidStateError, "A mutat
 DOM4_MSG_DEF(AbortError, "A request was aborted, for example through a call to IDBTransaction.abort.", NS_ERROR_DOM_INDEXEDDB_ABORT_ERR)
 DOM4_MSG_DEF(TimeoutError, "A lock for the transaction could not be obtained in a reasonable time.", NS_ERROR_DOM_INDEXEDDB_TIMEOUT_ERR)
 DOM4_MSG_DEF(QuotaExceededError, "The current transaction exceeded its quota limitations.", NS_ERROR_DOM_INDEXEDDB_QUOTA_ERR)
 
 /* A Non-standard IndexedDB error */
 
 DOM_MSG_DEF(NS_ERROR_DOM_INDEXEDDB_RECOVERABLE_ERR, "The operation failed because the database was prevented from taking an action. The operation might be able to succeed if the application performs some recovery steps and retries the entire transaction. For example, there was not enough remaining storage space, or the storage quota was reached and the user declined to give more space to the database.")
 
+/* FileSystem DOM errors. */
+DOM4_MSG_DEF(InvalidAccessError, "Invalid file system path.", NS_ERROR_DOM_FILESYSTEM_INVALID_PATH_ERR)
+DOM4_MSG_DEF(InvalidModificationError, "Failed to modify the file.", NS_ERROR_DOM_FILESYSTEM_INVALID_MODIFICATION_ERR)
+DOM4_MSG_DEF(NoModificationAllowedError, "Modifications are not allowed for this file", NS_ERROR_DOM_FILESYSTEM_NO_MODIFICATION_ALLOWED_ERR)
+DOM4_MSG_DEF(AbortError, "File already exists.", NS_ERROR_DOM_FILESYSTEM_PATH_EXISTS_ERR)
+DOM4_MSG_DEF(TypeMismatchError, "The type of the file is incompatible with the expected type.", NS_ERROR_DOM_FILESYSTEM_TYPE_MISMATCH_ERR)
+DOM4_MSG_DEF(UnknownError, "The operation failed for reasons unrelated to the file system itself and not covered by any other error code.", NS_ERROR_DOM_FILESYSTEM_UNKNOWN_ERR)
+
 /* DOM error codes defined by us */
 
 /* XXX string should be specified by norris */
 DOM_MSG_DEF(NS_ERROR_DOM_SECMAN_ERR, "Unable to obtain security manager")
 DOM_MSG_DEF(NS_ERROR_DOM_WRONG_TYPE_ERR, "Object is of wrong type")
 DOM_MSG_DEF(NS_ERROR_DOM_NOT_OBJECT_ERR, "Parameter is not an object")
 DOM_MSG_DEF(NS_ERROR_DOM_NOT_XPC_OBJECT_ERR, "Parameter is not a XPConnect object")
 DOM_MSG_DEF(NS_ERROR_DOM_NOT_NUMBER_ERR, "Parameter is not a number")
--- a/dom/devicestorage/DeviceStorage.h
+++ b/dom/devicestorage/DeviceStorage.h
@@ -27,16 +27,17 @@ class DeviceStorageFile;
 class nsIInputStream;
 
 namespace mozilla {
 namespace dom {
 class DeviceStorageEnumerationParameters;
 class DOMCursor;
 class DOMRequest;
 class Promise;
+class DeviceStorageFileSystem;
 } // namespace dom
 namespace ipc {
 class FileDescriptor;
 }
 } // namespace mozilla
 
 class DeviceStorageFile MOZ_FINAL
   : public nsISupports {
@@ -154,16 +155,17 @@ class nsDOMDeviceStorage MOZ_FINAL
   , public nsIObserver
 {
   typedef mozilla::ErrorResult ErrorResult;
   typedef mozilla::dom::DeviceStorageEnumerationParameters
     EnumerationParameters;
   typedef mozilla::dom::DOMCursor DOMCursor;
   typedef mozilla::dom::DOMRequest DOMRequest;
   typedef mozilla::dom::Promise Promise;
+  typedef mozilla::dom::DeviceStorageFileSystem DeviceStorageFileSystem;
 public:
   typedef nsTArray<nsString> VolumeNameArray;
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_NSIDOMDEVICESTORAGE
 
   NS_DECL_NSIOBSERVER
   NS_DECL_NSIDOMEVENTTARGET
@@ -332,11 +334,13 @@ private:
 #endif
 
   // nsIDOMDeviceStorage.type
   enum {
       DEVICE_STORAGE_TYPE_DEFAULT = 0,
       DEVICE_STORAGE_TYPE_SHARED,
       DEVICE_STORAGE_TYPE_EXTERNAL
   };
+
+  nsRefPtr<DeviceStorageFileSystem> mFileSystem;
 };
 
 #endif
--- a/dom/devicestorage/nsDeviceStorage.cpp
+++ b/dom/devicestorage/nsDeviceStorage.cpp
@@ -6,18 +6,20 @@
 
 #include "nsDeviceStorage.h"
 
 #include "mozilla/Attributes.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/dom/DeviceStorageBinding.h"
+#include "mozilla/dom/DeviceStorageFileSystem.h"
 #include "mozilla/dom/devicestorage/PDeviceStorageRequestChild.h"
 #include "mozilla/dom/Directory.h"
+#include "mozilla/dom/FileSystemUtils.h"
 #include "mozilla/dom/ipc/Blob.h"
 #include "mozilla/dom/PBrowserChild.h"
 #include "mozilla/dom/PContentPermissionRequestChild.h"
 #include "mozilla/dom/PermissionMessageUtils.h"
 #include "mozilla/dom/Promise.h"
 #include "mozilla/LazyIdleThread.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Scoped.h"
@@ -994,24 +996,17 @@ DeviceStorageFile::IsSafePath(const nsAS
       return false;
     }
   }
   return true;
 }
 
 void
 DeviceStorageFile::NormalizeFilePath() {
-#if defined(XP_WIN)
-  char16_t* cur = mPath.BeginWriting();
-  char16_t* end = mPath.EndWriting();
-  for (; cur < end; ++cur) {
-    if (char16_t('\\') == *cur)
-      *cur = char16_t('/');
-  }
-#endif
+  FileSystemUtils::LocalPathToNormalizedPath(mPath, mPath);
 }
 
 void
 DeviceStorageFile::AppendRelativePath(const nsAString& aPath) {
   if (!mFile) {
     return;
   }
   if (!IsSafePath(aPath)) {
@@ -1019,33 +1014,19 @@ DeviceStorageFile::AppendRelativePath(co
     // valid and return PERMISSION_DENIED if a non-safe path is entered.
     // This check is done in the parent and prevents a compromised
     // child from bypassing the check. It shouldn't be possible for this
     // code path to be taken with a non-compromised child.
     NS_WARNING("Unsafe path detected - ignoring");
     NS_WARNING(NS_LossyConvertUTF16toASCII(aPath).get());
     return;
   }
-#if defined(XP_WIN)
-  // replace forward slashes with backslashes,
-  // since nsLocalFileWin chokes on them
-  nsString temp;
-  temp.Assign(aPath);
-
-  char16_t* cur = temp.BeginWriting();
-  char16_t* end = temp.EndWriting();
-
-  for (; cur < end; ++cur) {
-    if (char16_t('/') == *cur)
-      *cur = char16_t('\\');
-  }
-  mFile->AppendRelativePath(temp);
-#else
-  mFile->AppendRelativePath(aPath);
-#endif
+  nsString localPath;
+  FileSystemUtils::NormalizedPathToLocalPath(aPath, localPath);
+  mFile->AppendRelativePath(localPath);
 }
 
 nsresult
 DeviceStorageFile::CreateFileDescriptor(FileDescriptor& aFileDescriptor)
 {
   ScopedPRFileDesc fd;
   nsresult rv = mFile->OpenNSPRFileDesc(PR_RDWR | PR_CREATE_FILE,
                                         0660, &fd.rwget());
@@ -3176,16 +3157,21 @@ nsDOMDeviceStorage::~nsDOMDeviceStorage(
 {
 }
 
 void
 nsDOMDeviceStorage::Shutdown()
 {
   MOZ_ASSERT(NS_IsMainThread());
 
+  if (mFileSystem) {
+    mFileSystem->Shutdown();
+    mFileSystem = nullptr;
+  }
+
   if (!mStorageName.IsEmpty()) {
     UnregisterForSDCardChanges(this);
   }
 
   nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
   obs->RemoveObserver(this, "file-watcher-update");
   obs->RemoveObserver(this, "disk-space-watcher");
 }
@@ -3917,18 +3903,21 @@ nsDOMDeviceStorage::Default()
   nsString defaultStorageName;
   GetDefaultStorageName(mStorageType, defaultStorageName);
   return mStorageName.Equals(defaultStorageName);
 }
 
 already_AddRefed<Promise>
 nsDOMDeviceStorage::GetRoot()
 {
-  // TODO
-  return nullptr;
+  if (!mFileSystem) {
+    mFileSystem = new DeviceStorageFileSystem(mStorageType, mStorageName);
+    mFileSystem->Init(this);
+  }
+  return mozilla::dom::Directory::GetRoot(mFileSystem);
 }
 
 NS_IMETHODIMP
 nsDOMDeviceStorage::GetDefault(bool* aDefault)
 {
   *aDefault = Default();
   return NS_OK;
 }
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/CreateDirectoryTask.cpp
@@ -0,0 +1,135 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "CreateDirectoryTask.h"
+
+#include "DOMError.h"
+#include "mozilla/dom/Directory.h"
+#include "mozilla/dom/FileSystemBase.h"
+#include "mozilla/dom/FileSystemUtils.h"
+#include "mozilla/dom/Promise.h"
+#include "nsIFile.h"
+#include "nsStringGlue.h"
+
+namespace mozilla {
+namespace dom {
+
+CreateDirectoryTask::CreateDirectoryTask(FileSystemBase* aFileSystem,
+                                         const nsAString& aPath)
+  : FileSystemTaskBase(aFileSystem)
+  , mTargetRealPath(aPath)
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  MOZ_ASSERT(aFileSystem);
+  nsCOMPtr<nsIGlobalObject> globalObject =
+    do_QueryInterface(aFileSystem->GetWindow());
+  if (!globalObject) {
+    return;
+  }
+  mPromise = new Promise(globalObject);
+}
+
+CreateDirectoryTask::CreateDirectoryTask(
+  FileSystemBase* aFileSystem,
+  const FileSystemCreateDirectoryParams& aParam,
+  FileSystemRequestParent* aParent)
+  : FileSystemTaskBase(aFileSystem, aParam, aParent)
+{
+  MOZ_ASSERT(FileSystemUtils::IsParentProcess(),
+             "Only call from parent process!");
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  MOZ_ASSERT(aFileSystem);
+  mTargetRealPath = aParam.realPath();
+}
+
+CreateDirectoryTask::~CreateDirectoryTask()
+{
+  MOZ_ASSERT(!mPromise || NS_IsMainThread(),
+             "mPromise should be released on main thread!");
+}
+
+already_AddRefed<Promise>
+CreateDirectoryTask::GetPromise()
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  return nsRefPtr<Promise>(mPromise).forget();
+}
+
+FileSystemParams
+CreateDirectoryTask::GetRequestParams(const nsString& aFileSystem) const
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  return FileSystemCreateDirectoryParams(aFileSystem, mTargetRealPath);
+}
+
+FileSystemResponseValue
+CreateDirectoryTask::GetSuccessRequestResult() const
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  return FileSystemDirectoryResponse(mTargetRealPath);
+}
+
+void
+CreateDirectoryTask::SetSuccessRequestResult(const FileSystemResponseValue& aValue)
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  FileSystemDirectoryResponse r = aValue;
+  mTargetRealPath = r.realPath();
+}
+
+nsresult
+CreateDirectoryTask::Work()
+{
+  MOZ_ASSERT(FileSystemUtils::IsParentProcess(),
+             "Only call from parent process!");
+  MOZ_ASSERT(!NS_IsMainThread(), "Only call on worker thread!");
+
+  if (mFileSystem->IsShutdown()) {
+    return NS_ERROR_FAILURE;
+  }
+
+  nsCOMPtr<nsIFile> file = mFileSystem->GetLocalFile(mTargetRealPath);
+  if (!file) {
+    return NS_ERROR_DOM_FILESYSTEM_INVALID_PATH_ERR;
+  }
+
+  bool fileExists;
+  nsresult rv = file->Exists(&fileExists);
+  if (NS_WARN_IF(NS_FAILED(rv))) {
+    return rv;
+  }
+
+  if (fileExists) {
+    return NS_ERROR_DOM_FILESYSTEM_PATH_EXISTS_ERR;
+  }
+
+  rv = file->Create(nsIFile::DIRECTORY_TYPE, 0770);
+  return rv;
+}
+
+void
+CreateDirectoryTask::HandlerCallback()
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  if (mFileSystem->IsShutdown()) {
+    mPromise = nullptr;
+    return;
+  }
+
+  if (HasError()) {
+    nsRefPtr<DOMError> domError = new DOMError(mFileSystem->GetWindow(),
+      mErrorValue);
+    mPromise->MaybeReject(domError);
+    mPromise = nullptr;
+    return;
+  }
+  nsRefPtr<Directory> dir = new Directory(mFileSystem, mTargetRealPath);
+  mPromise->MaybeResolve(dir);
+  mPromise = nullptr;
+}
+
+} // namespace dom
+} // namespace mozilla
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/CreateDirectoryTask.h
@@ -0,0 +1,58 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_dom_CreateDirectoryTask_h
+#define mozilla_dom_CreateDirectoryTask_h
+
+#include "mozilla/dom/FileSystemTaskBase.h"
+#include "nsAutoPtr.h"
+
+namespace mozilla {
+namespace dom {
+
+class Promise;
+
+class CreateDirectoryTask MOZ_FINAL
+  : public FileSystemTaskBase
+{
+public:
+  CreateDirectoryTask(FileSystemBase* aFileSystem,
+                      const nsAString& aPath);
+  CreateDirectoryTask(FileSystemBase* aFileSystem,
+                      const FileSystemCreateDirectoryParams& aParam,
+                      FileSystemRequestParent* aParent);
+
+  virtual
+  ~CreateDirectoryTask();
+
+  already_AddRefed<Promise>
+  GetPromise();
+
+protected:
+  virtual FileSystemParams
+  GetRequestParams(const nsString& aFileSystem) const MOZ_OVERRIDE;
+
+  virtual FileSystemResponseValue
+  GetSuccessRequestResult() const MOZ_OVERRIDE;
+
+  virtual void
+  SetSuccessRequestResult(const FileSystemResponseValue& aValue) MOZ_OVERRIDE;
+
+  virtual nsresult
+  Work() MOZ_OVERRIDE;
+
+  virtual void
+  HandlerCallback() MOZ_OVERRIDE;
+
+private:
+  nsRefPtr<Promise> mPromise;
+  nsString mTargetRealPath;
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_CreateDirectoryTask_h
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/DeviceStorageFileSystem.cpp
@@ -0,0 +1,100 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/dom/DeviceStorageFileSystem.h"
+
+#include "DeviceStorage.h"
+#include "mozilla/dom/FileSystemUtils.h"
+#include "nsCOMPtr.h"
+#include "nsDebug.h"
+#include "nsIFile.h"
+#include "nsPIDOMWindow.h"
+
+namespace mozilla {
+namespace dom {
+
+DeviceStorageFileSystem::DeviceStorageFileSystem(
+  const nsAString& aStorageType,
+  const nsAString& aStorageName)
+  : mDeviceStorage(nullptr)
+{
+  mStorageType = aStorageType;
+  mStorageName = aStorageName;
+
+  // Generate the string representation of the file system.
+  mString.AppendLiteral("devicestorage-");
+  mString.Append(mStorageType);
+  mString.AppendLiteral("-");
+  mString.Append(mStorageName);
+
+  // Get the local path of the file system root.
+  // Since the child process is not allowed to access the file system, we only
+  // do this from the parent process.
+  if (!FileSystemUtils::IsParentProcess()) {
+    return;
+  }
+  nsCOMPtr<nsIFile> rootFile;
+  DeviceStorageFile::GetRootDirectoryForType(aStorageType,
+                                             aStorageName,
+                                             getter_AddRefs(rootFile));
+
+  NS_WARN_IF(!rootFile || NS_FAILED(rootFile->GetPath(mLocalRootPath)));
+}
+
+DeviceStorageFileSystem::~DeviceStorageFileSystem()
+{
+}
+
+void
+DeviceStorageFileSystem::Init(nsDOMDeviceStorage* aDeviceStorage)
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  MOZ_ASSERT(aDeviceStorage);
+  mDeviceStorage = aDeviceStorage;
+}
+
+void
+DeviceStorageFileSystem::Shutdown()
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  mDeviceStorage = nullptr;
+  mShutdown = true;
+}
+
+nsPIDOMWindow*
+DeviceStorageFileSystem::GetWindow() const
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  if (!mDeviceStorage) {
+    return nullptr;
+  }
+  return mDeviceStorage->GetOwner();
+}
+
+already_AddRefed<nsIFile>
+DeviceStorageFileSystem::GetLocalFile(const nsAString& aRealPath) const
+{
+  MOZ_ASSERT(FileSystemUtils::IsParentProcess(),
+             "Should be on parent process!");
+  nsAutoString localPath;
+  FileSystemUtils::NormalizedPathToLocalPath(aRealPath, localPath);
+  localPath = mLocalRootPath + localPath;
+  nsCOMPtr<nsIFile> file;
+  nsresult rv = NS_NewLocalFile(localPath, false, getter_AddRefs(file));
+  if (NS_WARN_IF(NS_FAILED(rv))) {
+    return nullptr;
+  }
+  return file.forget();
+}
+
+const nsAString&
+DeviceStorageFileSystem::GetRootName() const
+{
+  return mStorageName;
+}
+
+} // namespace dom
+} // namespace mozilla
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/DeviceStorageFileSystem.h
@@ -0,0 +1,57 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_dom_DeviceStorageFileSystem_h
+#define mozilla_dom_DeviceStorageFileSystem_h
+
+#include "mozilla/dom/FileSystemBase.h"
+#include "nsString.h"
+
+class nsDOMDeviceStorage;
+
+namespace mozilla {
+namespace dom {
+
+class DeviceStorageFileSystem
+  : public FileSystemBase
+{
+public:
+  DeviceStorageFileSystem(const nsAString& aStorageType,
+                          const nsAString& aStorageName);
+
+  void
+  Init(nsDOMDeviceStorage* aDeviceStorage);
+
+  // Overrides FileSystemBase
+
+  virtual void
+  Shutdown() MOZ_OVERRIDE;
+
+  virtual nsPIDOMWindow*
+  GetWindow() const MOZ_OVERRIDE;
+
+  virtual already_AddRefed<nsIFile>
+  GetLocalFile(const nsAString& aRealPath) const MOZ_OVERRIDE;
+
+  virtual const nsAString&
+  GetRootName() const MOZ_OVERRIDE;
+private:
+  virtual
+  ~DeviceStorageFileSystem();
+
+  nsString mStorageType;
+  nsString mStorageName;
+
+  // The local path of the root. Only available in the parent process.
+  // In the child process, we don't use it and its value should be empty.
+  nsString mLocalRootPath;
+  nsDOMDeviceStorage* mDeviceStorage;
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_DeviceStorageFileSystem_h
--- a/dom/filesystem/Directory.cpp
+++ b/dom/filesystem/Directory.cpp
@@ -1,18 +1,24 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/dom/Directory.h"
 
+#include "CreateDirectoryTask.h"
+#include "GetFileOrDirectoryTask.h"
+
+#include "nsCharSeparatedTokenizer.h"
 #include "nsString.h"
 #include "mozilla/dom/DirectoryBinding.h"
+#include "mozilla/dom/FileSystemBase.h"
+#include "mozilla/dom/FileSystemUtils.h"
 
 // Resolve the name collision of Microsoft's API name with macros defined in
 // Windows header files. Undefine the macro of CreateDirectory to avoid
 // Directory#CreateDirectory being replaced by Directory#CreateDirectoryW.
 #ifdef CreateDirectory
 #undef CreateDirectory
 #endif
 
@@ -22,53 +28,149 @@ namespace dom {
 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_0(Directory)
 NS_IMPL_CYCLE_COLLECTING_ADDREF(Directory)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(Directory)
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Directory)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
-Directory::Directory()
+// static
+already_AddRefed<Promise>
+Directory::GetRoot(FileSystemBase* aFileSystem)
 {
+  nsRefPtr<GetFileOrDirectoryTask> task = new GetFileOrDirectoryTask(
+    aFileSystem, EmptyString(), true);
+  task->Start();
+  return task->GetPromise();
+}
+
+Directory::Directory(FileSystemBase* aFileSystem,
+                     const nsAString& aPath)
+  : mFileSystem(aFileSystem)
+  , mPath(aPath)
+{
+  MOZ_ASSERT(aFileSystem, "aFileSystem should not be null.");
+  // Remove the trailing "/".
+  mPath.Trim(FILESYSTEM_DOM_PATH_SEPARATOR, false, true);
+
   SetIsDOMBinding();
 }
 
 Directory::~Directory()
 {
 }
 
 nsPIDOMWindow*
 Directory::GetParentObject() const
 {
-  // TODO
-  return nullptr;
+  return mFileSystem->GetWindow();
 }
 
 JSObject*
 Directory::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
   return DirectoryBinding::Wrap(aCx, aScope, this);
 }
 
 void
 Directory::GetName(nsString& aRetval) const
 {
   aRetval.Truncate();
-  // TODO
+
+  if (mPath.IsEmpty()) {
+    aRetval = mFileSystem->GetRootName();
+    return;
+  }
+
+  aRetval = Substring(mPath,
+                      mPath.RFindChar(FileSystemUtils::kSeparatorChar) + 1);
 }
 
 already_AddRefed<Promise>
 Directory::CreateDirectory(const nsAString& aPath)
 {
-  // TODO
-  return nullptr;
+  nsresult error = NS_OK;
+  nsString realPath;
+  if (!DOMPathToRealPath(aPath, realPath)) {
+    error = NS_ERROR_DOM_FILESYSTEM_INVALID_PATH_ERR;
+  }
+  nsRefPtr<CreateDirectoryTask> task = new CreateDirectoryTask(
+    mFileSystem, realPath);
+  task->SetError(error);
+  task->Start();
+  return task->GetPromise();
 }
 
 already_AddRefed<Promise>
 Directory::Get(const nsAString& aPath)
 {
-  // TODO
-  return nullptr;
+  nsresult error = NS_OK;
+  nsString realPath;
+  if (!DOMPathToRealPath(aPath, realPath)) {
+    error = NS_ERROR_DOM_FILESYSTEM_INVALID_PATH_ERR;
+  }
+  nsRefPtr<GetFileOrDirectoryTask> task = new GetFileOrDirectoryTask(
+    mFileSystem, realPath, false);
+  task->SetError(error);
+  task->Start();
+  return task->GetPromise();
+}
+
+bool
+Directory::DOMPathToRealPath(const nsAString& aPath, nsAString& aRealPath) const
+{
+  aRealPath.Truncate();
+
+  nsString relativePath;
+  relativePath = aPath;
+
+  // Trim white spaces.
+  static const char kWhitespace[] = "\b\t\r\n ";
+  relativePath.Trim(kWhitespace);
+
+  if (!IsValidRelativePath(relativePath)) {
+    return false;
+  }
+
+  aRealPath = mPath + NS_LITERAL_STRING(FILESYSTEM_DOM_PATH_SEPARATOR) +
+    relativePath;
+
+  return true;
+}
+
+// static
+bool
+Directory::IsValidRelativePath(const nsString& aPath)
+{
+  // We don't allow empty relative path to access the root.
+  if (aPath.IsEmpty()) {
+    return false;
+  }
+
+  // Leading and trailing "/" are not allowed.
+  if (aPath.First() == FileSystemUtils::kSeparatorChar ||
+      aPath.Last() == FileSystemUtils::kSeparatorChar) {
+    return false;
+  }
+
+  NS_NAMED_LITERAL_STRING(kCurrentDir, ".");
+  NS_NAMED_LITERAL_STRING(kParentDir, "..");
+
+  // Split path and check each path component.
+  nsCharSeparatedTokenizer tokenizer(aPath, FileSystemUtils::kSeparatorChar);
+  while (tokenizer.hasMoreTokens()) {
+    nsDependentSubstring pathComponent = tokenizer.nextToken();
+    // The path containing empty components, such as "foo//bar", is invalid.
+    // We don't allow paths, such as "../foo", "foo/./bar" and "foo/../bar",
+    // to walk up the directory.
+    if (pathComponent.IsEmpty() ||
+        pathComponent.Equals(kCurrentDir) ||
+        pathComponent.Equals(kParentDir)) {
+      return false;
+    }
+  }
+
+  return true;
 }
 
 } // namespace dom
 } // namespace mozilla
--- a/dom/filesystem/Directory.h
+++ b/dom/filesystem/Directory.h
@@ -19,28 +19,32 @@
 // Directory#CreateDirectory being replaced by Directory#CreateDirectoryW.
 #ifdef CreateDirectory
 #undef CreateDirectory
 #endif
 
 namespace mozilla {
 namespace dom {
 
+class FileSystemBase;
 class Promise;
 
 class Directory MOZ_FINAL
   : public nsISupports
   , public nsWrapperCache
 {
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(Directory)
 
 public:
-  Directory();
+  static already_AddRefed<Promise>
+  GetRoot(FileSystemBase* aFileSystem);
+
+  Directory(FileSystemBase* aFileSystem, const nsAString& aPath);
   ~Directory();
 
   // ========= Begin WebIDL bindings. ===========
 
   nsPIDOMWindow*
   GetParentObject() const;
 
   virtual JSObject*
@@ -51,14 +55,27 @@ public:
 
   already_AddRefed<Promise>
   CreateDirectory(const nsAString& aPath);
 
   already_AddRefed<Promise>
   Get(const nsAString& aPath);
 
   // =========== End WebIDL bindings.============
+private:
+  static bool
+  IsValidRelativePath(const nsString& aPath);
+
+  /*
+   * Convert relative DOM path to the absolute real path.
+   * @return true if succeed. false if the DOM path is invalid.
+   */
+  bool
+  DOMPathToRealPath(const nsAString& aPath, nsAString& aRealPath) const;
+
+  nsRefPtr<FileSystemBase> mFileSystem;
+  nsString mPath;
 };
 
 } // namespace dom
 } // namespace mozilla
 
 #endif // mozilla_dom_Directory_h
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/FileSystemBase.cpp
@@ -0,0 +1,65 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/dom/FileSystemBase.h"
+
+#include "DeviceStorageFileSystem.h"
+#include "nsCharSeparatedTokenizer.h"
+
+namespace mozilla {
+namespace dom {
+
+// static
+already_AddRefed<FileSystemBase>
+FileSystemBase::FromString(const nsAString& aString)
+{
+  if (StringBeginsWith(aString, NS_LITERAL_STRING("devicestorage-"))) {
+    // The string representation of devicestorage file system is of the format:
+    // devicestorage-StorageType-StorageName
+
+    nsCharSeparatedTokenizer tokenizer(aString, char16_t('-'));
+    tokenizer.nextToken();
+
+    nsString storageType;
+    if (tokenizer.hasMoreTokens()) {
+      storageType = tokenizer.nextToken();
+    }
+
+    nsString storageName;
+    if (tokenizer.hasMoreTokens()) {
+      storageName = tokenizer.nextToken();
+    }
+
+    nsRefPtr<DeviceStorageFileSystem> f =
+      new DeviceStorageFileSystem(storageType, storageName);
+    return f.forget();
+  }
+  return nullptr;
+}
+
+FileSystemBase::FileSystemBase()
+  : mShutdown(false)
+{
+}
+
+FileSystemBase::~FileSystemBase()
+{
+}
+
+void
+FileSystemBase::Shutdown()
+{
+  mShutdown = true;
+}
+
+nsPIDOMWindow*
+FileSystemBase::GetWindow() const
+{
+  return nullptr;
+}
+
+} // namespace dom
+} // namespace mozilla
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/FileSystemBase.h
@@ -0,0 +1,72 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_dom_FileSystemBase_h
+#define mozilla_dom_FileSystemBase_h
+
+#include "nsAutoPtr.h"
+#include "nsString.h"
+
+class nsPIDOMWindow;
+
+namespace mozilla {
+namespace dom {
+
+class FileSystemBase
+{
+  NS_INLINE_DECL_THREADSAFE_REFCOUNTING(FileSystemBase)
+public:
+
+  // Create file system object from its string representation.
+  static already_AddRefed<FileSystemBase>
+  FromString(const nsAString& aString);
+
+  FileSystemBase();
+
+  virtual void
+  Shutdown();
+
+  // Get the string representation of the file system.
+  const nsString&
+  ToString() const
+  {
+    return mString;
+  }
+
+  virtual nsPIDOMWindow*
+  GetWindow() const;
+
+  /*
+   * Create nsIFile object with the given real path (absolute DOM path).
+   */
+  virtual already_AddRefed<nsIFile>
+  GetLocalFile(const nsAString& aRealPath) const = 0;
+
+  /*
+   * Get the virtual name of the root directory. This name will be exposed to
+   * the content page.
+   */
+  virtual const nsAString&
+  GetRootName() const = 0;
+
+  bool
+  IsShutdown() const
+  {
+    return mShutdown;
+  }
+protected:
+  virtual ~FileSystemBase();
+
+  // The string representation of the file system.
+  nsString mString;
+
+  bool mShutdown;
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_FileSystemBase_h
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/FileSystemRequestParent.cpp
@@ -0,0 +1,69 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et cindent: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "mozilla/dom/FileSystemRequestParent.h"
+
+#include "CreateDirectoryTask.h"
+#include "GetFileOrDirectoryTask.h"
+
+#include "mozilla/dom/FileSystemBase.h"
+
+namespace mozilla {
+namespace dom {
+
+FileSystemRequestParent::FileSystemRequestParent()
+{
+}
+
+FileSystemRequestParent::~FileSystemRequestParent()
+{
+}
+
+#define FILESYSTEM_REQUEST_PARENT_DISPATCH_ENTRY(name)                         \
+    case FileSystemParams::TFileSystem##name##Params: {                        \
+      const FileSystem##name##Params& p = aParams;                             \
+      mFileSystem = FileSystemBase::FromString(p.filesystem());                \
+      task = new name##Task(mFileSystem, p, this);                             \
+      break;                                                                   \
+    }
+
+bool
+FileSystemRequestParent::Dispatch(ContentParent* aParent,
+                                  const FileSystemParams& aParams)
+{
+  MOZ_ASSERT(aParent, "aParent should not be null.");
+  nsRefPtr<FileSystemTaskBase> task;
+  switch (aParams.type()) {
+
+    FILESYSTEM_REQUEST_PARENT_DISPATCH_ENTRY(CreateDirectory)
+    FILESYSTEM_REQUEST_PARENT_DISPATCH_ENTRY(GetFileOrDirectory)
+
+    default: {
+      NS_RUNTIMEABORT("not reached");
+      break;
+    }
+  }
+
+  if (NS_WARN_IF(!task || !mFileSystem)) {
+    // Should never reach here.
+    return false;
+  }
+
+  task->Start();
+  return true;
+}
+
+void
+FileSystemRequestParent::ActorDestroy(ActorDestroyReason why)
+{
+  if (!mFileSystem) {
+    return;
+  }
+  mFileSystem->Shutdown();
+  mFileSystem = nullptr;
+}
+
+} // namespace dom
+} // namespace mozilla
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/FileSystemRequestParent.h
@@ -0,0 +1,47 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et cindent: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_dom_FileSystemRequestParent_h
+#define mozilla_dom_FileSystemRequestParent_h
+
+#include "mozilla/dom/PFileSystemRequestParent.h"
+#include "mozilla/dom/ContentChild.h"
+#include "mozilla/dom/ContentParent.h"
+
+namespace mozilla {
+namespace dom {
+
+class FileSystemBase;
+
+class FileSystemRequestParent
+  : public PFileSystemRequestParent
+{
+  NS_INLINE_DECL_THREADSAFE_REFCOUNTING(FileSystemRequestParent)
+public:
+  FileSystemRequestParent();
+
+  virtual
+  ~FileSystemRequestParent();
+
+  bool
+  IsRunning()
+  {
+    return state() == PFileSystemRequest::__Start;
+  }
+
+  bool
+  Dispatch(ContentParent* aParent, const FileSystemParams& aParams);
+
+  virtual void
+  ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE;
+private:
+  nsRefPtr<FileSystemBase> mFileSystem;
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_FileSystemRequestParent_h
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/FileSystemTaskBase.cpp
@@ -0,0 +1,219 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/dom/FileSystemTaskBase.h"
+
+#include "nsNetUtil.h" // Stream transport service.
+#include "mozilla/dom/ContentChild.h"
+#include "mozilla/dom/FileSystemBase.h"
+#include "mozilla/dom/FileSystemRequestParent.h"
+#include "mozilla/dom/FileSystemUtils.h"
+#include "mozilla/dom/Promise.h"
+#include "mozilla/dom/PContent.h"
+#include "mozilla/unused.h"
+#include "nsDOMFile.h"
+
+namespace mozilla {
+namespace dom {
+
+FileSystemTaskBase::FileSystemTaskBase(FileSystemBase* aFileSystem)
+  : mErrorValue(NS_OK)
+  , mFileSystem(aFileSystem)
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  MOZ_ASSERT(aFileSystem, "aFileSystem should not be null.");
+}
+
+FileSystemTaskBase::FileSystemTaskBase(FileSystemBase* aFileSystem,
+                                       const FileSystemParams& aParam,
+                                       FileSystemRequestParent* aParent)
+  : mErrorValue(NS_OK)
+  , mFileSystem(aFileSystem)
+  , mRequestParent(aParent)
+{
+  MOZ_ASSERT(FileSystemUtils::IsParentProcess(),
+             "Only call from parent process!");
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  MOZ_ASSERT(aFileSystem, "aFileSystem should not be null.");
+}
+
+FileSystemTaskBase::~FileSystemTaskBase()
+{
+}
+
+void
+FileSystemTaskBase::Start()
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+
+  if (HasError()) {
+    NS_DispatchToMainThread(this);
+    return;
+  }
+
+  if (FileSystemUtils::IsParentProcess()) {
+    // Run in parent process.
+    // Start worker thread.
+    nsCOMPtr<nsIEventTarget> target
+      = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
+    NS_ASSERTION(target, "Must have stream transport service.");
+    target->Dispatch(this, NS_DISPATCH_NORMAL);
+    return;
+  }
+
+  // Run in child process.
+  if (mFileSystem->IsShutdown()) {
+    return;
+  }
+
+  // Retain a reference so the task object isn't deleted without IPDL's
+  // knowledge. The reference will be released by
+  // mozilla::dom::ContentChild::DeallocPFileSystemRequestChild.
+  NS_ADDREF_THIS();
+  ContentChild::GetSingleton()->SendPFileSystemRequestConstructor(this,
+    GetRequestParams(mFileSystem->ToString()));
+}
+
+NS_IMETHODIMP
+FileSystemTaskBase::Run()
+{
+  if (!NS_IsMainThread()) {
+    // Run worker thread tasks
+    nsresult rv = Work();
+    if (NS_FAILED(rv)) {
+      SetError(rv);
+    }
+    // Dispatch itself to main thread
+    NS_DispatchToMainThread(this);
+    return NS_OK;
+  }
+
+  // Run main thread tasks
+  HandleResult();
+  return NS_OK;
+}
+
+void
+FileSystemTaskBase::HandleResult()
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  if (mFileSystem->IsShutdown()) {
+    return;
+  }
+  if (mRequestParent && mRequestParent->IsRunning()) {
+    unused << mRequestParent->Send__delete__(mRequestParent,
+      GetRequestResult());
+  } else {
+    HandlerCallback();
+  }
+}
+
+FileSystemResponseValue
+FileSystemTaskBase::GetRequestResult() const
+{
+  MOZ_ASSERT(FileSystemUtils::IsParentProcess(),
+             "Only call from parent process!");
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  if (HasError()) {
+    return FileSystemErrorResponse(mErrorValue);
+  } else {
+    return GetSuccessRequestResult();
+  }
+}
+
+void
+FileSystemTaskBase::SetRequestResult(const FileSystemResponseValue& aValue)
+{
+  MOZ_ASSERT(!FileSystemUtils::IsParentProcess(),
+             "Only call from child process!");
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  if (aValue.type() == FileSystemResponseValue::TFileSystemErrorResponse) {
+    FileSystemErrorResponse r = aValue;
+    mErrorValue = r.error();
+  } else {
+    SetSuccessRequestResult(aValue);
+  }
+}
+
+bool
+FileSystemTaskBase::Recv__delete__(const FileSystemResponseValue& aValue)
+{
+  SetRequestResult(aValue);
+  HandlerCallback();
+  return true;
+}
+
+BlobParent*
+FileSystemTaskBase::GetBlobParent(nsIDOMFile* aFile) const
+{
+  MOZ_ASSERT(FileSystemUtils::IsParentProcess(),
+             "Only call from parent process!");
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  MOZ_ASSERT(aFile);
+
+  // Load the lazy dom file data from the parent before sending to the child.
+  nsString mimeType;
+  aFile->GetType(mimeType);
+  uint64_t fileSize;
+  aFile->GetSize(&fileSize);
+  uint64_t lastModifiedDate;
+  aFile->GetMozLastModifiedDate(&lastModifiedDate);
+
+  ContentParent* cp = static_cast<ContentParent*>(mRequestParent->Manager());
+  return cp->GetOrCreateActorForBlob(aFile);
+}
+
+void
+FileSystemTaskBase::SetError(const nsresult& aErrorValue)
+{
+  uint16_t module = NS_ERROR_GET_MODULE(aErrorValue);
+  if (module == NS_ERROR_MODULE_DOM_FILESYSTEM ||
+      module == NS_ERROR_MODULE_DOM_FILE) {
+    mErrorValue = aErrorValue;
+    return;
+  }
+
+  switch (aErrorValue) {
+    case NS_OK:
+      mErrorValue = NS_OK;
+      return;
+
+    case NS_ERROR_FILE_INVALID_PATH:
+    case NS_ERROR_FILE_UNRECOGNIZED_PATH:
+      mErrorValue = NS_ERROR_DOM_FILESYSTEM_INVALID_PATH_ERR;
+      return;
+
+    case NS_ERROR_FILE_DESTINATION_NOT_DIR:
+      mErrorValue = NS_ERROR_DOM_FILESYSTEM_INVALID_MODIFICATION_ERR;
+      return;
+
+    case NS_ERROR_FILE_ACCESS_DENIED:
+    case NS_ERROR_FILE_DIR_NOT_EMPTY:
+      mErrorValue = NS_ERROR_DOM_FILESYSTEM_NO_MODIFICATION_ALLOWED_ERR;
+      return;
+
+    case NS_ERROR_FILE_TARGET_DOES_NOT_EXIST:
+    case NS_ERROR_NOT_AVAILABLE:
+      mErrorValue = NS_ERROR_DOM_FILE_NOT_FOUND_ERR;
+      return;
+
+    case NS_ERROR_FILE_ALREADY_EXISTS:
+      mErrorValue = NS_ERROR_DOM_FILESYSTEM_PATH_EXISTS_ERR;
+      return;
+
+    case NS_ERROR_FILE_NOT_DIRECTORY:
+      mErrorValue = NS_ERROR_DOM_FILESYSTEM_TYPE_MISMATCH_ERR;
+      return;
+
+    case NS_ERROR_UNEXPECTED:
+    default:
+      mErrorValue = NS_ERROR_DOM_FILESYSTEM_UNKNOWN_ERR;
+      return;
+  }
+}
+
+} // namespace dom
+} // namespace mozilla
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/FileSystemTaskBase.h
@@ -0,0 +1,236 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_dom_FileSystemTaskBase_h
+#define mozilla_dom_FileSystemTaskBase_h
+
+#include "mozilla/ErrorResult.h"
+#include "mozilla/dom/FileSystemRequestParent.h"
+#include "mozilla/dom/PFileSystemRequestChild.h"
+#include "mozilla/dom/ipc/Blob.h"
+
+class nsIDOMFile;
+
+namespace mozilla {
+namespace dom {
+
+class FileSystemBase;
+class FileSystemParams;
+class Promise;
+
+/*
+ * The base class to implement a Task class.
+ * The task is used to handle the OOP (out of process) operations.
+ * The file system operations can only be performed in the parent process. When
+ * performing such a parent-process-only operation, a task will delivered the
+ * operation to the parent process if needed.
+ *
+ * The following diagram illustrates the how a API call from the content page
+ * starts a task and gets call back results.
+ *
+ * The left block is the call sequence inside the child process, while the
+ * right block is the call sequence inside the parent process.
+ *
+ * There are two types of API call. One is from the content page of the child
+ * process and we mark the steps as (1) to (8). The other is from the content
+ * page of the parent process and we mark the steps as (1') to (4').
+ *
+ *       Page                                             Page
+ *        |                                                |
+ *        | (1)                                            |  (1')
+ *  ______|________________     |     _____________________|_____________
+ * |      |                |    |    |                     |             |
+ * |      |  Task in       |    |    |  Task in            |             |
+ * |      |  Child Process |    |    |  Parent Process     |             |
+ * |      V                |   IPC   |                     V             |
+ * [new FileSystemTaskBase()]   |    |     [new FileSystemTaskBase()]    |
+ * |         |             |    |    |                         |         |
+ * |         | (2)         |         |                         | (2')    |
+ * |         V             |   (3)   |                         |         |
+ * |    [GetRequestParams]------------->[new FileSystemTaskBase(...)]    |
+ * |                       |         |          |              |         |
+ * |                       |    |    |          | (4)          |         |
+ * |                       |    |    |          |              V         |
+ * |                       |    |    |          -----------> [Work]      |
+ * |                       |   IPC   |                         |         |
+ * |                       |    |    |                     (5) | (3')    |
+ * |                       |    |    |                         V         |
+ * |                       |    |    |          --------[HandleResult]   |
+ * |                       |    |    |          |              |         |
+ * |                       |         |          | (6)          |         |
+ * |                       |   (7)   |          V              |         |
+ * |   [SetRequestResult]<-------------[GetRequestResult]      |         |
+ * |       |               |         |                         | (4')    |
+ * |       | (8)           |    |    |                         |         |
+ * |       V               |    |    |                         V         |
+ * |[HandlerCallback]      |   IPC   |               [HandlerCallback]   |
+ * |_______|_______________|    |    |_________________________|_________|
+ *         |                    |                              |
+ *         V                                                   V
+ *        Page                                                Page
+ *
+ * 1. From child process page
+ * Child:
+ *   (1) Call FileSystem API from content page with JS. Create a task and run.
+ *   The base constructor [FileSystemTaskBase()] of the task should be called.
+ *   (2) Forward the task to the parent process through the IPC and call
+ *   [GetRequestParams] to prepare the parameters of the IPC.
+ * Parent:
+ *   (3) The parent process receives IPC and handle it in
+ *   FileystemRequestParent.
+ *   Get the IPC parameters and create a task to run the IPC task. The base
+ *   constructor [FileSystemTaskBase(aParam, aParent)] of the task should be
+ *   called to set the task as an IPC task.
+ *   (4) The task operation will be performed in the member function of [Work].
+ *   A worker thread will be created to run that function. If error occurs
+ *   during the operation, call [SetError] to record the error and then abort.
+ *   (5) After finishing the task operation, call [HandleResult] to send the
+ *   result back to the child process though the IPC.
+ *   (6) Call [GetRequestResult] request result to prepare the parameters of the
+ *   IPC. Because the formats of the error result for different task are the
+ *   same, FileSystemTaskBase can handle the error message without interfering.
+ *   Each task only needs to implement its specific success result preparation
+ *   function -[GetSuccessRequestResult].
+ * Child:
+ *   (7) The child process receives IPC and calls [SetRequestResult] to get the
+ *   task result. Each task needs to implement its specific success result
+ *   parsing function [SetSuccessRequestResult] to get the success result.
+ *   (8) Call [HandlerCallback] to send the task result to the content page.
+ * 2. From parent process page
+ * We don't need to send the task parameters and result to other process. So
+ * there are less steps, but their functions are the same. The correspondence
+ * between the two types of steps is:
+ *   (1') = (1),
+ *   (2') = (4),
+ *   (3') = (5),
+ *   (4') = (8).
+ */
+class FileSystemTaskBase
+  : public nsRunnable
+  , public PFileSystemRequestChild
+{
+public:
+  /*
+   * Start the task. If the task is running the child process, it will be
+   * forwarded to parent process by IPC, or else, creates a worker thread to
+   * do the task work.
+   */
+  void
+  Start();
+
+  /*
+   * The error codes are defined in xpcom/base/ErrorList.h and their
+   * corresponding error name and message are defined in dom/base/domerr.msg.
+   */
+  void
+  SetError(const nsresult& aErrorCode);
+
+
+  NS_DECL_NSIRUNNABLE
+protected:
+  /*
+   * To create a task to handle the page content request.
+   */
+  FileSystemTaskBase(FileSystemBase* aFileSystem);
+
+  /*
+   * To create a parent process task delivered from the child process through
+   * IPC.
+   */
+  FileSystemTaskBase(FileSystemBase* aFileSystem,
+                     const FileSystemParams& aParam,
+                     FileSystemRequestParent* aParent);
+
+  virtual
+  ~FileSystemTaskBase();
+
+  /*
+   * The function to perform task operation. It will be run on the worker
+   * thread of the parent process.
+   * Overrides this function to define the task operation for individual task.
+   */
+  virtual nsresult
+  Work() = 0;
+
+  /*
+   * After the task is completed, this function will be called to pass the task
+   * result to the content page.
+   * Override this function to handle the call back to the content page.
+   */
+  virtual void
+  HandlerCallback() = 0;
+
+  /*
+   * Wrap the task parameter to FileSystemParams for sending it through IPC.
+   * It will be called when we need to forward a task from the child process to
+   * the prarent process.
+   * @param filesystem The string representation of the file system.
+   */
+  virtual FileSystemParams
+  GetRequestParams(const nsString& aFileSystem) const = 0;
+
+  /*
+   * Wrap the task success result to FileSystemResponseValue for sending it
+   * through IPC.
+   * It will be called when the task is completed successfully and we need to
+   * send the task success result back to the child process.
+   */
+  virtual FileSystemResponseValue
+  GetSuccessRequestResult() const = 0;
+
+  /*
+   * Unwrap the IPC message to get the task success result.
+   * It will be called when the task is completed successfully and an IPC
+   * message is received in the child process and we want to get the task
+   * success result.
+   */
+  virtual void
+  SetSuccessRequestResult(const FileSystemResponseValue& aValue) = 0;
+
+  bool
+  HasError() const { return mErrorValue != NS_OK; }
+
+  // Overrides PFileSystemRequestChild
+  virtual bool
+  Recv__delete__(const FileSystemResponseValue& value) MOZ_OVERRIDE;
+
+  BlobParent*
+  GetBlobParent(nsIDOMFile* aFile) const;
+
+  nsresult mErrorValue;
+
+  nsRefPtr<FileSystemBase> mFileSystem;
+  nsRefPtr<FileSystemRequestParent> mRequestParent;
+private:
+  /*
+   * After finishing the task operation, handle the task result.
+   * If it is an IPC task, send back the IPC result. Or else, send the result
+   * to the content page.
+   */
+  void
+  HandleResult();
+
+  /*
+   * Wrap the task result to FileSystemResponseValue for sending it through IPC.
+   * It will be called when the task is completed and we need to
+   * send the task result back to the child process.
+   */
+  FileSystemResponseValue
+  GetRequestResult() const;
+
+  /*
+   * Unwrap the IPC message to get the task result.
+   * It will be called when the task is completed and an IPC message is received
+   * in the child process and we want to get the task result.
+   */
+  void
+  SetRequestResult(const FileSystemResponseValue& aValue);
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_FileSystemTaskBase_h
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/FileSystemUtils.cpp
@@ -0,0 +1,58 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/dom/FileSystemUtils.h"
+
+#include "nsXULAppAPI.h"
+
+namespace mozilla {
+namespace dom {
+
+// static
+void
+FileSystemUtils::LocalPathToNormalizedPath(const nsAString& aLocal,
+                                           nsAString& aNorm)
+{
+  nsString result;
+  result = aLocal;
+#if defined(XP_WIN)
+  char16_t* cur = result.BeginWriting();
+  char16_t* end = result.EndWriting();
+  for (; cur < end; ++cur) {
+    if (char16_t('\\') == *cur)
+      *cur = char16_t('/');
+  }
+#endif
+  aNorm = result;
+}
+
+// static
+void
+FileSystemUtils::NormalizedPathToLocalPath(const nsAString& aNorm,
+                                           nsAString& aLocal)
+{
+  nsString result;
+  result = aNorm;
+#if defined(XP_WIN)
+  char16_t* cur = result.BeginWriting();
+  char16_t* end = result.EndWriting();
+  for (; cur < end; ++cur) {
+    if (char16_t('/') == *cur)
+      *cur = char16_t('\\');
+  }
+#endif
+  aLocal = result;
+}
+
+// static
+bool
+FileSystemUtils::IsParentProcess()
+{
+  return XRE_GetProcessType() == GeckoProcessType_Default;
+}
+
+} // namespace dom
+} // namespace mozilla
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/FileSystemUtils.h
@@ -0,0 +1,46 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_dom_FileSystemUtils_h
+#define mozilla_dom_FileSystemUtils_h
+
+#include "nsString.h"
+
+namespace mozilla {
+namespace dom {
+
+#define FILESYSTEM_DOM_PATH_SEPARATOR "/"
+
+/*
+ * This class is for error handling.
+ * All methods in this class are static.
+ */
+class FileSystemUtils
+{
+public:
+  /*
+   * Convert the path separator to "/".
+   */
+  static void
+  LocalPathToNormalizedPath(const nsAString& aLocal, nsAString& aNorm);
+
+  /*
+   * Convert the normalized path separator "/" to the system dependent path
+   * separator, which is "/" on Mac and Linux, and "\" on Windows.
+   */
+  static void
+  NormalizedPathToLocalPath(const nsAString& aNorm, nsAString& aLocal);
+
+  static bool
+  IsParentProcess();
+
+  static const char16_t kSeparatorChar = char16_t('/');
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_FileSystemUtils_h
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/GetFileOrDirectoryTask.cpp
@@ -0,0 +1,213 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "GetFileOrDirectoryTask.h"
+
+#include "js/Value.h"
+#include "mozilla/dom/Directory.h"
+#include "mozilla/dom/FileSystemBase.h"
+#include "mozilla/dom/FileSystemUtils.h"
+#include "mozilla/dom/Promise.h"
+#include "nsDOMFile.h"
+#include "nsIFile.h"
+#include "nsStringGlue.h"
+
+namespace mozilla {
+namespace dom {
+
+GetFileOrDirectoryTask::GetFileOrDirectoryTask(
+  FileSystemBase* aFileSystem,
+  const nsAString& aTargetPath,
+  bool aDirectoryOnly)
+  : FileSystemTaskBase(aFileSystem)
+  , mTargetRealPath(aTargetPath)
+  , mIsDirectory(aDirectoryOnly)
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  MOZ_ASSERT(aFileSystem);
+  nsCOMPtr<nsIGlobalObject> globalObject =
+    do_QueryInterface(aFileSystem->GetWindow());
+  if (!globalObject) {
+    return;
+  }
+  mPromise = new Promise(globalObject);
+}
+
+GetFileOrDirectoryTask::GetFileOrDirectoryTask(
+  FileSystemBase* aFileSystem,
+  const FileSystemGetFileOrDirectoryParams& aParam,
+  FileSystemRequestParent* aParent)
+  : FileSystemTaskBase(aFileSystem, aParam, aParent)
+  , mIsDirectory(false)
+{
+  MOZ_ASSERT(FileSystemUtils::IsParentProcess(),
+             "Only call from parent process!");
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  MOZ_ASSERT(aFileSystem);
+  mTargetRealPath = aParam.realPath();
+}
+
+GetFileOrDirectoryTask::~GetFileOrDirectoryTask()
+{
+  MOZ_ASSERT(!mPromise || NS_IsMainThread(),
+             "mPromise should be released on main thread!");
+}
+
+already_AddRefed<Promise>
+GetFileOrDirectoryTask::GetPromise()
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  return nsRefPtr<Promise>(mPromise).forget();
+}
+
+FileSystemParams
+GetFileOrDirectoryTask::GetRequestParams(const nsString& aFileSystem) const
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  return FileSystemGetFileOrDirectoryParams(aFileSystem, mTargetRealPath);
+}
+
+FileSystemResponseValue
+GetFileOrDirectoryTask::GetSuccessRequestResult() const
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  if (mIsDirectory) {
+    return FileSystemDirectoryResponse(mTargetRealPath);
+  }
+  BlobParent* actor = GetBlobParent(mTargetFile);
+  if (!actor) {
+    return FileSystemErrorResponse(NS_ERROR_DOM_FILESYSTEM_UNKNOWN_ERR);
+  }
+  FileSystemFileResponse response;
+  response.blobParent() = actor;
+  return response;
+}
+
+void
+GetFileOrDirectoryTask::SetSuccessRequestResult(const FileSystemResponseValue& aValue)
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  switch (aValue.type()) {
+    case FileSystemResponseValue::TFileSystemFileResponse: {
+      FileSystemFileResponse r = aValue;
+      BlobChild* actor = static_cast<BlobChild*>(r.blobChild());
+      nsCOMPtr<nsIDOMBlob> blob = actor->GetBlob();
+      mTargetFile = do_QueryInterface(blob);
+      mIsDirectory = false;
+      break;
+    }
+    case FileSystemResponseValue::TFileSystemDirectoryResponse: {
+      FileSystemDirectoryResponse r = aValue;
+      mTargetRealPath = r.realPath();
+      mIsDirectory = true;
+      break;
+    }
+    default: {
+      NS_RUNTIMEABORT("not reached");
+      break;
+    }
+  }
+}
+
+nsresult
+GetFileOrDirectoryTask::Work()
+{
+  MOZ_ASSERT(FileSystemUtils::IsParentProcess(),
+             "Only call from parent process!");
+  MOZ_ASSERT(!NS_IsMainThread(), "Only call on worker thread!");
+
+  if (mFileSystem->IsShutdown()) {
+    return NS_ERROR_FAILURE;
+  }
+
+  // Whether we want to get the root directory.
+  bool getRoot = mTargetRealPath.IsEmpty();
+
+  nsCOMPtr<nsIFile> file = mFileSystem->GetLocalFile(mTargetRealPath);
+  if (!file) {
+    return NS_ERROR_DOM_FILESYSTEM_INVALID_PATH_ERR;
+  }
+
+  bool exists;
+  nsresult rv = file->Exists(&exists);
+  if (NS_WARN_IF(NS_FAILED(rv))) {
+    return rv;
+  }
+
+  if (!exists) {
+    if (!getRoot) {
+      return NS_ERROR_DOM_FILE_NOT_FOUND_ERR;
+    }
+
+    // If the root directory doesn't exit, create it.
+    rv = file->Create(nsIFile::DIRECTORY_TYPE, 0777);
+    if (NS_WARN_IF(NS_FAILED(rv))) {
+      return rv;
+    }
+  }
+
+  // Get isDirectory.
+  rv = file->IsDirectory(&mIsDirectory);
+  if (NS_WARN_IF(NS_FAILED(rv))) {
+    return rv;
+  }
+
+  if (mIsDirectory) {
+    return NS_OK;
+  }
+
+  // Check if the root is a directory.
+  if (getRoot) {
+    return NS_ERROR_DOM_FILESYSTEM_TYPE_MISMATCH_ERR;
+  }
+
+  bool isFile;
+  // Get isFile
+  rv = file->IsFile(&isFile);
+  if (NS_WARN_IF(NS_FAILED(rv))) {
+    return rv;
+  }
+
+  if (!isFile) {
+    // Neither directory or file.
+    return NS_ERROR_DOM_FILESYSTEM_TYPE_MISMATCH_ERR;
+  }
+
+  mTargetFile = new nsDOMFileFile(file);
+
+  return NS_OK;
+}
+
+void
+GetFileOrDirectoryTask::HandlerCallback()
+{
+  MOZ_ASSERT(NS_IsMainThread(), "Only call on main thread!");
+  if (mFileSystem->IsShutdown()) {
+    mPromise = nullptr;
+    return;
+  }
+
+  if (HasError()) {
+    nsRefPtr<DOMError> domError = new DOMError(mFileSystem->GetWindow(),
+      mErrorValue);
+    mPromise->MaybeReject(domError);
+    mPromise = nullptr;
+    return;
+  }
+
+  if (mIsDirectory) {
+    nsRefPtr<Directory> dir = new Directory(mFileSystem, mTargetRealPath);
+    mPromise->MaybeResolve(dir);
+    mPromise = nullptr;
+    return;
+  }
+
+  mPromise->MaybeResolve(mTargetFile);
+  mPromise = nullptr;
+}
+
+} // namespace dom
+} // namespace mozilla
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/GetFileOrDirectoryTask.h
@@ -0,0 +1,61 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_dom_GetFileOrDirectory_h
+#define mozilla_dom_GetFileOrDirectory_h
+
+#include "mozilla/dom/FileSystemTaskBase.h"
+#include "nsAutoPtr.h"
+
+namespace mozilla {
+namespace dom {
+
+class GetFileOrDirectoryTask MOZ_FINAL
+  : public FileSystemTaskBase
+{
+public:
+  // If aDirectoryOnly is set, we should ensure that the target is a directory.
+  GetFileOrDirectoryTask(FileSystemBase* aFileSystem,
+                         const nsAString& aTargetPath,
+                         bool aDirectoryOnly);
+  GetFileOrDirectoryTask(FileSystemBase* aFileSystem,
+                         const FileSystemGetFileOrDirectoryParams& aParam,
+                         FileSystemRequestParent* aParent);
+
+  virtual
+  ~GetFileOrDirectoryTask();
+
+  already_AddRefed<Promise>
+  GetPromise();
+
+protected:
+  virtual FileSystemParams
+  GetRequestParams(const nsString& aFileSystem) const MOZ_OVERRIDE;
+
+  virtual FileSystemResponseValue
+  GetSuccessRequestResult() const MOZ_OVERRIDE;
+
+  virtual void
+  SetSuccessRequestResult(const FileSystemResponseValue& aValue) MOZ_OVERRIDE;
+
+  virtual nsresult
+  Work() MOZ_OVERRIDE;
+
+  virtual void
+  HandlerCallback() MOZ_OVERRIDE;
+
+private:
+  nsRefPtr<Promise> mPromise;
+  nsString mTargetRealPath;
+  // Whether we get a directory.
+  bool mIsDirectory;
+  nsCOMPtr<nsIDOMFile> mTargetFile;
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_GetFileOrDirectory_h
new file mode 100644
--- /dev/null
+++ b/dom/filesystem/PFileSystemRequest.ipdl
@@ -0,0 +1,44 @@
+/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include protocol PBlob;
+include protocol PContent;
+
+namespace mozilla {
+namespace dom {
+
+struct FileSystemFileResponse
+{
+  PBlob blob;
+};
+
+struct FileSystemDirectoryResponse
+{
+  nsString realPath;
+};
+
+struct FileSystemErrorResponse
+{
+  nsresult error;
+};
+
+union FileSystemResponseValue
+{
+  FileSystemDirectoryResponse;
+  FileSystemFileResponse;
+  FileSystemErrorResponse;
+};
+
+sync protocol PFileSystemRequest
+{
+  manager PContent;
+
+child:
+  __delete__(FileSystemResponseValue response);
+};
+
+} // namespace dom
+} // namespace mozilla
--- a/dom/filesystem/moz.build
+++ b/dom/filesystem/moz.build
@@ -1,22 +1,38 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 EXPORTS.mozilla.dom += [
+    'DeviceStorageFileSystem.h',
     'Directory.h',
+    'FileSystemBase.h',
+    'FileSystemRequestParent.h',
+    'FileSystemTaskBase.h',
+    'FileSystemUtils.h',
 ]
 
 SOURCES += [
+    'CreateDirectoryTask.cpp',
+    'DeviceStorageFileSystem.cpp',
     'Directory.cpp',
+    'FileSystemBase.cpp',
+    'FileSystemRequestParent.cpp',
+    'FileSystemTaskBase.cpp',
+    'FileSystemUtils.cpp',
+    'GetFileOrDirectoryTask.cpp',
 ]
 
 FINAL_LIBRARY = 'gklayout'
 
+IPDL_SOURCES += [
+    'PFileSystemRequest.ipdl',
+]
+
 include('/ipc/chromium/chromium-config.mozbuild')
 
 LOCAL_INCLUDES += [
     '/dom/base',
 ]
 
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -112,16 +112,18 @@
 #ifdef MOZ_NUWA_PROCESS
 #include <setjmp.h>
 #include "ipc/Nuwa.h"
 #endif
 
 #include "mozilla/dom/indexedDB/PIndexedDBChild.h"
 #include "mozilla/dom/mobilemessage/SmsChild.h"
 #include "mozilla/dom/devicestorage/DeviceStorageRequestChild.h"
+#include "mozilla/dom/PFileSystemRequestChild.h"
+#include "mozilla/dom/FileSystemTaskBase.h"
 #include "mozilla/dom/bluetooth/PBluetoothChild.h"
 #include "mozilla/dom/PFMRadioChild.h"
 #include "mozilla/ipc/InputStreamUtils.h"
 
 #ifdef MOZ_WEBSPEECH
 #include "mozilla/dom/PSpeechSynthesisChild.h"
 #endif
 
@@ -1033,16 +1035,34 @@ ContentChild::AllocPDeviceStorageRequest
 
 bool
 ContentChild::DeallocPDeviceStorageRequestChild(PDeviceStorageRequestChild* aDeviceStorage)
 {
     delete aDeviceStorage;
     return true;
 }
 
+PFileSystemRequestChild*
+ContentChild::AllocPFileSystemRequestChild(const FileSystemParams& aParams)
+{
+    NS_NOTREACHED("Should never get here!");
+    return nullptr;
+}
+
+bool
+ContentChild::DeallocPFileSystemRequestChild(PFileSystemRequestChild* aFileSystem)
+{
+    mozilla::dom::FileSystemTaskBase* child =
+      static_cast<mozilla::dom::FileSystemTaskBase*>(aFileSystem);
+    // The reference is increased in FileSystemTaskBase::Start of
+    // FileSystemTaskBase.cpp. We should decrease it after IPC.
+    NS_RELEASE(child);
+    return true;
+}
+
 PNeckoChild*
 ContentChild::AllocPNeckoChild()
 {
     return new NeckoChild();
 }
 
 bool
 ContentChild::DeallocPNeckoChild(PNeckoChild* necko)
--- a/dom/ipc/ContentChild.h
+++ b/dom/ipc/ContentChild.h
@@ -94,16 +94,19 @@ public:
 
     virtual PBrowserChild* AllocPBrowserChild(const IPCTabContext &aContext,
                                               const uint32_t &chromeFlags);
     virtual bool DeallocPBrowserChild(PBrowserChild*);
 
     virtual PDeviceStorageRequestChild* AllocPDeviceStorageRequestChild(const DeviceStorageParams&);
     virtual bool DeallocPDeviceStorageRequestChild(PDeviceStorageRequestChild*);
 
+    virtual PFileSystemRequestChild* AllocPFileSystemRequestChild(const FileSystemParams&);
+    virtual bool DeallocPFileSystemRequestChild(PFileSystemRequestChild*);
+
     virtual PBlobChild* AllocPBlobChild(const BlobConstructorParams& aParams);
     virtual bool DeallocPBlobChild(PBlobChild*);
 
     virtual PCrashReporterChild*
     AllocPCrashReporterChild(const mozilla::dom::NativeThreadId& id,
                              const uint32_t& processType) MOZ_OVERRIDE;
     virtual bool
     DeallocPCrashReporterChild(PCrashReporterChild*) MOZ_OVERRIDE;
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -30,16 +30,17 @@
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/ExternalHelperAppParent.h"
 #include "mozilla/dom/PMemoryReportRequestParent.h"
 #include "mozilla/dom/power/PowerManagerService.h"
 #include "mozilla/dom/DOMStorageIPC.h"
 #include "mozilla/dom/bluetooth/PBluetoothParent.h"
 #include "mozilla/dom/PFMRadioParent.h"
 #include "mozilla/dom/devicestorage/DeviceStorageRequestParent.h"
+#include "mozilla/dom/FileSystemRequestParent.h"
 #include "mozilla/dom/GeolocationBinding.h"
 #include "mozilla/dom/telephony/TelephonyParent.h"
 #include "mozilla/dom/time/DateCacheCleaner.h"
 #include "SmsParent.h"
 #include "mozilla/hal_sandbox/PHalParent.h"
 #include "mozilla/ipc/BackgroundChild.h"
 #include "mozilla/ipc/BackgroundParent.h"
 #include "mozilla/ipc/TestShellParent.h"
@@ -2223,16 +2224,34 @@ ContentParent::AllocPDeviceStorageReques
 bool
 ContentParent::DeallocPDeviceStorageRequestParent(PDeviceStorageRequestParent* doomed)
 {
   DeviceStorageRequestParent *parent = static_cast<DeviceStorageRequestParent*>(doomed);
   NS_RELEASE(parent);
   return true;
 }
 
+PFileSystemRequestParent*
+ContentParent::AllocPFileSystemRequestParent(const FileSystemParams& aParams)
+{
+  nsRefPtr<FileSystemRequestParent> result = new FileSystemRequestParent();
+  if (!result->Dispatch(this, aParams)) {
+    return nullptr;
+  }
+  return result.forget().get();
+}
+
+bool
+ContentParent::DeallocPFileSystemRequestParent(PFileSystemRequestParent* doomed)
+{
+  FileSystemRequestParent* parent = static_cast<FileSystemRequestParent*>(doomed);
+  NS_RELEASE(parent);
+  return true;
+}
+
 PBlobParent*
 ContentParent::AllocPBlobParent(const BlobConstructorParams& aParams)
 {
   return BlobParent::Create(this, aParams);
 }
 
 bool
 ContentParent::DeallocPBlobParent(PBlobParent* aActor)
--- a/dom/ipc/ContentParent.h
+++ b/dom/ipc/ContentParent.h
@@ -336,16 +336,22 @@ private:
     virtual PBrowserParent* AllocPBrowserParent(const IPCTabContext& aContext,
                                                 const uint32_t& aChromeFlags) MOZ_OVERRIDE;
     virtual bool DeallocPBrowserParent(PBrowserParent* frame) MOZ_OVERRIDE;
 
     virtual PDeviceStorageRequestParent*
     AllocPDeviceStorageRequestParent(const DeviceStorageParams&) MOZ_OVERRIDE;
     virtual bool DeallocPDeviceStorageRequestParent(PDeviceStorageRequestParent*) MOZ_OVERRIDE;
 
+    virtual PFileSystemRequestParent*
+    AllocPFileSystemRequestParent(const FileSystemParams&) MOZ_OVERRIDE;
+
+    virtual bool
+    DeallocPFileSystemRequestParent(PFileSystemRequestParent*) MOZ_OVERRIDE;
+
     virtual PBlobParent* AllocPBlobParent(const BlobConstructorParams& aParams) MOZ_OVERRIDE;
     virtual bool DeallocPBlobParent(PBlobParent*) MOZ_OVERRIDE;
 
     virtual bool DeallocPCrashReporterParent(PCrashReporterParent* crashreporter) MOZ_OVERRIDE;
 
     virtual bool RecvGetRandomValues(const uint32_t& length,
                                      InfallibleTArray<uint8_t>* randomValues) MOZ_OVERRIDE;
 
--- a/dom/ipc/PContent.ipdl
+++ b/dom/ipc/PContent.ipdl
@@ -9,16 +9,17 @@ include protocol PBackground;
 include protocol PBlob;
 include protocol PBluetooth;
 include protocol PBrowser;
 include protocol PCompositor;
 include protocol PCrashReporter;
 include protocol PExternalHelperApp;
 include protocol PDeviceStorageRequest;
 include protocol PFMRadio;
+include protocol PFileSystemRequest;
 include protocol PHal;
 include protocol PImageBridge;
 include protocol PIndexedDB;
 include protocol PMemoryReportRequest;
 include protocol PNecko;
 include protocol PSms;
 include protocol PSpeechSynthesis;
 include protocol PStorage;
@@ -188,16 +189,34 @@ union FMRadioRequestParams
 {
   FMRadioRequestEnableParams;
   FMRadioRequestDisableParams;
   FMRadioRequestSetFrequencyParams;
   FMRadioRequestSeekParams;
   FMRadioRequestCancelSeekParams;
 };
 
+struct FileSystemCreateDirectoryParams
+{
+  nsString filesystem;
+  nsString realPath;
+};
+
+struct FileSystemGetFileOrDirectoryParams
+{
+  nsString filesystem;
+  nsString realPath;
+};
+
+union FileSystemParams
+{
+  FileSystemCreateDirectoryParams;
+  FileSystemGetFileOrDirectoryParams;
+};
+
 union PrefValue {
   nsCString;
   int32_t;
   bool;
 };
 
 union MaybePrefValue {
   PrefValue;
@@ -217,16 +236,17 @@ intr protocol PContent
     child opens PBackground;
 
     manages PAsmJSCacheEntry;
     manages PBlob;
     manages PBluetooth;
     manages PBrowser;
     manages PCrashReporter;
     manages PDeviceStorageRequest;
+    manages PFileSystemRequest;
     manages PExternalHelperApp;
     manages PFMRadio;
     manages PHal;
     manages PIndexedDB;
     manages PMemoryReportRequest;
     manages PNecko;
     manages PSms;
     manages PSpeechSynthesis;
@@ -366,16 +386,18 @@ parent:
      */
     sync GetProcessAttributes()
         returns (uint64_t id, bool isForApp, bool isForBrowser);
     sync GetXPCOMProcessAttributes()
         returns (bool isOffline);
 
     PDeviceStorageRequest(DeviceStorageParams params);
 
+    PFileSystemRequest(FileSystemParams params);
+
     sync PCrashReporter(NativeThreadId tid, uint32_t processType);
 
     sync GetRandomValues(uint32_t length)
         returns (uint8_t[] randomValues);
 
     PHal();
 
     PIndexedDB();
--- a/dom/ipc/moz.build
+++ b/dom/ipc/moz.build
@@ -94,16 +94,17 @@ LOCAL_INCLUDES += [
     '/content/base/src',
     '/content/media/webspeech/synth/ipc',
     '/docshell/base',
     '/dom/base',
     '/dom/bluetooth',
     '/dom/bluetooth/ipc',
     '/dom/devicestorage',
     '/dom/events',
+    '/dom/filesystem',
     '/dom/fmradio/ipc',
     '/dom/indexedDB',
     '/dom/indexedDB/ipc',
     '/dom/mobilemessage/src/ipc',
     '/extensions/cookie',
     '/hal/sandbox',
     '/js/ipc',
     '/layout/base',
--- a/dom/promise/Promise.h
+++ b/dom/promise/Promise.h
@@ -242,16 +242,32 @@ private:
     JSObject* abv = aArgument.Create(aCx, scope);
     if (!abv) {
       return false;
     }
     aValue.setObject(*abv);
     return true;
   }
 
+  // Accept objects that inherit from nsISupports but not nsWrapperCache (e.g.
+  // nsIDOMFile).
+  template <class T>
+  typename EnableIf<!IsBaseOf<nsWrapperCache, T>::value &&
+                    IsBaseOf<nsISupports, T>::value, bool>::Type
+  ArgumentToJSValue(T& aArgument,
+                    JSContext* aCx,
+                    JSObject* aScope,
+                    JS::MutableHandle<JS::Value> aValue)
+  {
+    JS::Rooted<JSObject*> scope(aCx, aScope);
+
+    nsresult rv = nsContentUtils::WrapNative(aCx, scope, &aArgument, aValue);
+    return NS_SUCCEEDED(rv);
+  }
+
   template <template <typename> class SmartPtr, typename T>
   bool
   ArgumentToJSValue(const SmartPtr<T>& aArgument,
                     JSContext* aCx,
                     JSObject* aScope,
                     JS::MutableHandle<JS::Value> aValue)
   {
     return ArgumentToJSValue(*aArgument.get(), aCx, aScope, aValue);
--- a/xpcom/base/ErrorList.h
+++ b/xpcom/base/ErrorList.h
@@ -821,16 +821,28 @@
   ERROR(NS_ERROR_SIGNED_JAR_ENTRY_MISSING,                FAILURE(4)),
   ERROR(NS_ERROR_SIGNED_JAR_WRONG_SIGNATURE,              FAILURE(5)),
   ERROR(NS_ERROR_SIGNED_JAR_ENTRY_TOO_LARGE,              FAILURE(6)),
   ERROR(NS_ERROR_SIGNED_JAR_ENTRY_INVALID,                FAILURE(7)),
   ERROR(NS_ERROR_SIGNED_JAR_MANIFEST_INVALID,             FAILURE(8)),
 #undef MODULE
 
   /* ======================================================================= */
+  /* 36: NS_ERROR_MODULE_DOM_FILESYSTEM */
+  /* ======================================================================= */
+#define MODULE NS_ERROR_MODULE_DOM_FILESYSTEM
+  ERROR(NS_ERROR_DOM_FILESYSTEM_INVALID_PATH_ERR,          FAILURE(1)),
+  ERROR(NS_ERROR_DOM_FILESYSTEM_INVALID_MODIFICATION_ERR,  FAILURE(2)),
+  ERROR(NS_ERROR_DOM_FILESYSTEM_NO_MODIFICATION_ALLOWED_ERR, FAILURE(3)),
+  ERROR(NS_ERROR_DOM_FILESYSTEM_PATH_EXISTS_ERR,           FAILURE(4)),
+  ERROR(NS_ERROR_DOM_FILESYSTEM_TYPE_MISMATCH_ERR,         FAILURE(5)),
+  ERROR(NS_ERROR_DOM_FILESYSTEM_UNKNOWN_ERR,               FAILURE(6)),
+#undef MODULE
+
+  /* ======================================================================= */
   /* 51: NS_ERROR_MODULE_GENERAL */
   /* ======================================================================= */
 #define MODULE NS_ERROR_MODULE_GENERAL
   /* Error code used internally by the incremental downloader to cancel the
    * network channel when the download is already complete. */
   ERROR(NS_ERROR_DOWNLOAD_COMPLETE,      FAILURE(1)),
   /* Error code used internally by the incremental downloader to cancel the
    * network channel when the response to a range request is 200 instead of
--- a/xpcom/base/nsError.h
+++ b/xpcom/base/nsError.h
@@ -64,16 +64,17 @@
 #define NS_ERROR_MODULE_IPC        28
 #define NS_ERROR_MODULE_SVG        29
 #define NS_ERROR_MODULE_STORAGE    30
 #define NS_ERROR_MODULE_SCHEMA     31
 #define NS_ERROR_MODULE_DOM_FILE   32
 #define NS_ERROR_MODULE_DOM_INDEXEDDB 33
 #define NS_ERROR_MODULE_DOM_FILEHANDLE 34
 #define NS_ERROR_MODULE_SIGNED_JAR 35
+#define NS_ERROR_MODULE_DOM_FILESYSTEM 36
 
 /* NS_ERROR_MODULE_GENERAL should be used by modules that do not
  * care if return code values overlap. Callers of methods that
  * return such codes should be aware that they are not
  * globally unique. Implementors should be careful about blindly
  * returning codes from other modules that might also use
  * the generic base.
  */