diff --git a/core/core.services.yml b/core/core.services.yml
index c4c7593..ceacade 100644
--- a/core/core.services.yml
+++ b/core/core.services.yml
@@ -189,6 +189,9 @@ services:
     factory_class: Drupal\Core\Database\Database
     factory_method: getConnection
     arguments: [default]
+  file_system:
+    class: Drupal\Core\File\FileSystem
+    arguments: ['@settings', '@logger.channel.file']
   form_builder:
     class: Drupal\Core\Form\FormBuilder
     arguments: ['@form_validator', '@form_submitter', '@form_cache', '@module_handler', '@event_dispatcher', '@request_stack', '@class_resolver', '@theme.manager', '@?csrf_token']
@@ -236,6 +239,11 @@ services:
   logger.channel.cron:
     parent: logger.channel_base
     arguments: ['cron']
+  logger.channel.file:
+    class: Drupal\Core\Logger\LoggerChannel
+    factory_method: get
+    factory_service: logger.factory
+    arguments: ['file']
   logger.channel.form:
     parent: logger.channel_base
     arguments: ['form']
diff --git a/core/includes/file.inc b/core/includes/file.inc
index d47fbc4..dbe3210 100644
--- a/core/includes/file.inc
+++ b/core/includes/file.inc
@@ -10,22 +10,11 @@
 use Drupal\Component\PhpStorage\FileStorage;
 use Drupal\Component\Utility\Bytes;
 use Drupal\Component\Utility\String;
-use Drupal\Core\Site\Settings;
 use Drupal\Core\StreamWrapper\PublicStream;
 use Drupal\Core\StreamWrapper\StreamWrapperInterface;
 use Drupal\Core\StreamWrapper\PrivateStream;
 
 /**
- * Default mode for new directories. See drupal_chmod().
- */
-const FILE_CHMOD_DIRECTORY = 0775;
-
-/**
- * Default mode for new files. See drupal_chmod().
- */
-const FILE_CHMOD_FILE = 0664;
-
-/**
  * @defgroup file File interface
  * @{
  * Common file handling functions.
@@ -129,40 +118,21 @@ function file_stream_wrapper_get_class($scheme) {
 /**
  * Returns the scheme of a URI (e.g. a stream).
  *
- * @param string $uri
- *   A stream, referenced as "scheme://target"  or "data:target".
- *
- * @return string
- *   A string containing the name of the scheme, or FALSE if none. For example,
- *   the URI "public://example.txt" would return "public".
- *
- * @see file_uri_target()
+ * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.0.
+ *   Use \Drupal\Core\File\FileSystem::uriScheme().
  */
 function file_uri_scheme($uri) {
-  if (preg_match('/^([\w\-]+):\/\/|^(data):/', $uri, $matches)) {
-    // The scheme will always be the last element in the matches array.
-    return array_pop($matches);
-  }
-
-  return FALSE;
+  return \Drupal::service('file_system')->uriScheme($uri);
 }
 
 /**
  * Checks that the scheme of a stream URI is valid.
  *
- * Confirms that there is a registered stream handler for the provided scheme
- * and that it is callable. This is useful if you want to confirm a valid
- * scheme without creating a new instance of the registered handler.
- *
- * @param string $scheme
- *   A URI scheme, a stream is referenced as "scheme://target".
- *
- * @return bool
- *   Returns TRUE if the string is the name of a validated stream,
- *   or FALSE if the scheme does not have a registered handler.
+ * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.0.
+ *   Use \Drupal\Core\File\FileSystem::validScheme().
  */
 function file_stream_wrapper_valid_scheme($scheme) {
-  return $scheme && class_exists(file_stream_wrapper_get_class($scheme));
+  return \Drupal::service('file_system')->validScheme($scheme);
 }
 
 
@@ -957,38 +927,11 @@ function file_unmanaged_delete_recursive($path, $callback = NULL) {
 /**
  * Moves an uploaded file to a new location.
  *
- * PHP's move_uploaded_file() does not properly support streams if open_basedir
- * is enabled, so this function fills that gap.
- *
- * Compatibility: normal paths and stream wrappers.
- *
- * @param $filename
- *   The filename of the uploaded file.
- * @param $uri
- *   A string containing the destination URI of the file.
- *
- * @return
- *   TRUE on success, or FALSE on failure.
- *
- * @see move_uploaded_file()
- * @see http://drupal.org/node/515192
- * @ingroup php_wrappers
+ * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.0.
+ *   Use \Drupal\Core\File\FileSystem::moveUploadedFile().
  */
 function drupal_move_uploaded_file($filename, $uri) {
-  $result = @move_uploaded_file($filename, $uri);
-  // PHP's move_uploaded_file() does not properly support streams if
-  // open_basedir is enabled so if the move failed, try finding a real path and
-  // retry the move operation.
-  if (!$result) {
-    if ($realpath = drupal_realpath($uri)) {
-      $result = move_uploaded_file($filename, $realpath);
-    }
-    else {
-      $result = move_uploaded_file($filename, $uri);
-    }
-  }
-
-  return $result;
+  return \Drupal::service('file_system')->moveUploadedFile($filename, $uri);
 }
 
 /**
@@ -1179,338 +1122,82 @@ function file_get_mimetype($uri, $mapping = NULL) {
 /**
  * Sets the permissions on a file or directory.
  *
- * This function will use the file_chmod_directory and
- * file_chmod_file settings for the default modes for directories
- * and uploaded/generated files. By default these will give everyone read access
- * so that users accessing the files with a user account without the webserver
- * group (e.g. via FTP) can read these files, and give group write permissions
- * so webserver group members (e.g. a vhost account) can alter files uploaded
- * and owned by the webserver.
- *
- * PHP's chmod does not support stream wrappers so we use our wrapper
- * implementation which interfaces with chmod() by default. Contrib wrappers
- * may override this behavior in their implementations as needed.
- *
- * @param $uri
- *   A string containing a URI file, or directory path.
- * @param $mode
- *   Integer value for the permissions. Consult PHP chmod() documentation for
- *   more information.
- *
- * @return bool
- *   TRUE for success, FALSE in the event of an error.
- *
- * @ingroup php_wrappers
+ * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.0.
+ *   Use \Drupal\Core\File\FileSystem::chmod().
  */
 function drupal_chmod($uri, $mode = NULL) {
-  if (!isset($mode)) {
-    if (is_dir($uri)) {
-      $mode = Settings::get('file_chmod_directory', FILE_CHMOD_DIRECTORY);
-    }
-    else {
-      $mode = Settings::get('file_chmod_file', FILE_CHMOD_FILE);
-    }
-  }
-
-  if (@chmod($uri, $mode)) {
-    return TRUE;
-  }
-
-  \Drupal::logger('file')->error('The file permissions could not be set on %uri.', array('%uri' => $uri));
-  return FALSE;
+  return \Drupal::service('file_system')->chmod($uri, $mode);
 }
 
 /**
  * Deletes a file.
  *
- * PHP's unlink() is broken on Windows, as it can fail to remove a file
- * when it has a read-only flag set.
- *
- * @param $uri
- *   A URI or pathname.
- * @param $context
- *   Refer to http://php.net/manual/ref.stream.php
- *
- * @return
- *   Boolean TRUE on success, or FALSE on failure.
- *
- * @see unlink()
- * @ingroup php_wrappers
+ * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.0.
+ *   Use \Drupal\Core\File\FileSystem::unlink().
  */
 function drupal_unlink($uri, $context = NULL) {
-  $scheme = file_uri_scheme($uri);
-  if (!file_stream_wrapper_valid_scheme($scheme) && (substr(PHP_OS, 0, 3) == 'WIN')) {
-    chmod($uri, 0600);
-  }
-  if ($context) {
-    return unlink($uri, $context);
-  }
-  else {
-    return unlink($uri);
-  }
+  return \Drupal::service('file_system')->unlink($uri, $context);
 }
 
 /**
  * Resolves the absolute filepath of a local URI or filepath.
  *
- * The use of drupal_realpath() is discouraged, because it does not work for
- * remote URIs. Except in rare cases, URIs should not be manually resolved.
- *
- * Only use this function if you know that the stream wrapper in the URI uses
- * the local file system, and you need to pass an absolute path to a function
- * that is incompatible with stream URIs.
- *
- * @param string $uri
- *   A stream wrapper URI or a filepath, possibly including one or more symbolic
- *   links.
- *
- * @return string|false
- *   The absolute local filepath (with no symbolic links), or FALSE on failure.
- *
- * @see \Drupal\Core\StreamWrapper\StreamWrapperInterface::realpath()
- * @see http://php.net/manual/function.realpath.php
- * @ingroup php_wrappers
+ * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.0.
+ *   Use \Drupal\Core\File\FileSystem::realpath().
  */
 function drupal_realpath($uri) {
-  // If this URI is a stream, pass it off to the appropriate stream wrapper.
-  // Otherwise, attempt PHP's realpath. This allows use of drupal_realpath even
-  // for unmanaged files outside of the stream wrapper interface.
-  if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
-    return $wrapper->realpath();
-  }
-
-  return realpath($uri);
+  return \Drupal::service('file_system')->realpath($uri);
 }
 
 /**
  * Gets the name of the directory from a given path.
  *
- * PHP's dirname() does not properly pass streams, so this function fills
- * that gap. It is backwards compatible with normal paths and will use
- * PHP's dirname() as a fallback.
- *
- * Compatibility: normal paths and stream wrappers.
- *
- * @param $uri
- *   A URI or path.
- *
- * @return
- *   A string containing the directory name.
- *
- * @see dirname()
- * @see http://drupal.org/node/515192
- * @ingroup php_wrappers
+ * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.0.
+ *   Use \Drupal\Core\File\FileSystem::dirname().
  */
 function drupal_dirname($uri) {
-  $scheme = file_uri_scheme($uri);
-
-  if (file_stream_wrapper_valid_scheme($scheme)) {
-    return file_stream_wrapper_get_instance_by_scheme($scheme)->dirname($uri);
-  }
-  else {
-    return dirname($uri);
-  }
+  return \Drupal::service('file_system')->dirname($uri);
 }
 
 /**
  * Gets the filename from a given path.
  *
- * PHP's basename() does not properly support streams or filenames beginning
- * with a non-US-ASCII character.
- *
- * @see http://bugs.php.net/bug.php?id=37738
- * @see basename()
- *
- * @ingroup php_wrappers
+ * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.0.
+ *   Use \Drupal\Core\File\FileSystem::basename().
  */
 function drupal_basename($uri, $suffix = NULL) {
-  $separators = '/';
-  if (DIRECTORY_SEPARATOR != '/') {
-    // For Windows OS add special separator.
-    $separators .= DIRECTORY_SEPARATOR;
-  }
-  // Remove right-most slashes when $uri points to directory.
-  $uri = rtrim($uri, $separators);
-  // Returns the trailing part of the $uri starting after one of the directory
-  // separators.
-  $filename = preg_match('@[^' . preg_quote($separators, '@') . ']+$@', $uri, $matches) ? $matches[0] : '';
-  // Cuts off a suffix from the filename.
-  if ($suffix) {
-    $filename = preg_replace('@' . preg_quote($suffix, '@') . '$@', '', $filename);
-  }
-  return $filename;
+  return \Drupal::service('file_system')->basename($uri, $suffix);
 }
 
 /**
  * Creates a directory, optionally creating missing components in the path to
  * the directory.
  *
- * When PHP's mkdir() creates a directory, the requested mode is affected by the
- * process's umask. This function overrides the umask and sets the mode
- * explicitly for all directory components created.
- *
- * @param $uri
- *   A URI or pathname.
- * @param $mode
- *   Mode given to created directories. Defaults to the directory mode
- *   configured in the Drupal installation. It must have a leading zero.
- * @param $recursive
- *   Create directories recursively, defaults to FALSE. Cannot work with a mode
- *   which denies writing or execution to the owner of the process.
- * @param $context
- *   Refer to http://php.net/manual/ref.stream.php
- *
- * @return
- *   Boolean TRUE on success, or FALSE on failure.
- *
- * @see mkdir()
- * @see http://drupal.org/node/515192
- * @ingroup php_wrappers
- *
- * @todo Update with open_basedir compatible recursion logic from
- *   \Drupal\Component\PhpStorage\FileStorage::ensureDirectory().
+ * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.0.
+ *   Use \Drupal\Core\File\FileSystem::mkdir().
  */
 function drupal_mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL) {
-  if (!isset($mode)) {
-    $mode = Settings::get('file_chmod_directory', FILE_CHMOD_DIRECTORY);
-  }
-
-  // If the URI has a scheme, don't override the umask - schemes can handle this
-  // issue in their own implementation.
-  if (file_uri_scheme($uri)) {
-    return _drupal_mkdir_call($uri, $mode, $recursive, $context);
-  }
-
-  // If recursive, create each missing component of the parent directory
-  // individually and set the mode explicitly to override the umask.
-  if ($recursive) {
-    // Ensure the path is using DIRECTORY_SEPARATOR.
-    $uri = str_replace('/', DIRECTORY_SEPARATOR, $uri);
-    // Determine the components of the path.
-    $components = explode(DIRECTORY_SEPARATOR, $uri);
-    // If the filepath is absolute the first component will be empty as there
-    // will be nothing before the first slash.
-    if ($components[0] == '') {
-      $recursive_path = DIRECTORY_SEPARATOR;
-      // Get rid of the empty first component.
-      array_shift($components);
-    }
-    else {
-      $recursive_path = '';
-    }
-    // Don't handle the top-level directory in this loop.
-    array_pop($components);
-    // Create each component if necessary.
-    foreach ($components as $component) {
-      $recursive_path .= $component;
-
-      if (!file_exists($recursive_path)) {
-        if (!_drupal_mkdir_call($recursive_path, $mode, FALSE, $context)) {
-          return FALSE;
-        }
-        // Not necessary to use drupal_chmod() as there is no scheme.
-        if (!chmod($recursive_path, $mode)) {
-          return FALSE;
-        }
-      }
-
-      $recursive_path .= DIRECTORY_SEPARATOR;
-    }
-  }
-
-  // Do not check if the top-level directory already exists, as this condition
-  // must cause this function to fail.
-  if (!_drupal_mkdir_call($uri, $mode, FALSE, $context)) {
-    return FALSE;
-  }
-  // Not necessary to use drupal_chmod() as there is no scheme.
-  return chmod($uri, $mode);
-}
-
-/**
- * Helper function. Ensures we don't pass a NULL as a context resource to
- * mkdir().
- *
- * @see drupal_mkdir()
- */
-function _drupal_mkdir_call($uri, $mode, $recursive, $context) {
-  if (is_null($context)) {
-    return mkdir($uri, $mode, $recursive);
-  }
-  else {
-    return mkdir($uri, $mode, $recursive, $context);
-  }
+  return \Drupal::service('file_system')->mkdir($uri, $mode, $recursive, $context);
 }
 
 /**
  * Removes a directory.
  *
- * PHP's rmdir() is broken on Windows, as it can fail to remove a directory
- * when it has a read-only flag set.
- *
- * @param $uri
- *   A URI or pathname.
- * @param $context
- *   Refer to http://php.net/manual/ref.stream.php
- *
- * @return
- *   Boolean TRUE on success, or FALSE on failure.
- *
- * @see rmdir()
- * @ingroup php_wrappers
+ * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.0.
+ *   Use \Drupal\Core\File\FileSystem::rmdir().
  */
 function drupal_rmdir($uri, $context = NULL) {
-  $scheme = file_uri_scheme($uri);
-  if (!file_stream_wrapper_valid_scheme($scheme) && (substr(PHP_OS, 0, 3) == 'WIN')) {
-    chmod($uri, 0700);
-  }
-  if ($context) {
-    return rmdir($uri, $context);
-  }
-  else {
-    return rmdir($uri);
-  }
+  return \Drupal::service('file_system')->rmdir($uri, $context);
 }
 
 /**
  * Creates a file with a unique filename in the specified directory.
  *
- * PHP's tempnam() does not return a URI like we want. This function
- * will return a URI if given a URI, or it will return a filepath if
- * given a filepath.
- *
- * Compatibility: normal paths and stream wrappers.
- *
- * @param $directory
- *   The directory where the temporary filename will be created.
- * @param $prefix
- *   The prefix of the generated temporary filename.
- *   Note: Windows uses only the first three characters of prefix.
- *
- * @return
- *   The new temporary filename, or FALSE on failure.
- *
- * @see tempnam()
- * @see http://drupal.org/node/515192
- * @ingroup php_wrappers
+ * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.0.
+ *   Use \Drupal\Core\File\FileSystem::tempnam().
  */
 function drupal_tempnam($directory, $prefix) {
-  $scheme = file_uri_scheme($directory);
-
-  if (file_stream_wrapper_valid_scheme($scheme)) {
-    $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
-
-    if ($filename = tempnam($wrapper->getDirectoryPath(), $prefix)) {
-      return $scheme . '://' . drupal_basename($filename);
-    }
-    else {
-      return FALSE;
-    }
-  }
-  else {
-    // Handle as a normal tempnam() call.
-    return tempnam($directory, $prefix);
-  }
+  return \Drupal::service('file_system')->tempnam($directory, $prefix);
 }
 
 /**
diff --git a/core/includes/install.core.inc b/core/includes/install.core.inc
index d3d7a04..f31a744 100644
--- a/core/includes/install.core.inc
+++ b/core/includes/install.core.inc
@@ -14,6 +14,7 @@
 use Drupal\Core\Installer\InstallerKernel;
 use Drupal\Core\Language\Language;
 use Drupal\Core\Language\LanguageManager;
+use Drupal\Core\Logger\LoggerChannelFactory;
 use Drupal\Core\Site\Settings;
 use Drupal\Core\StringTranslation\Translator\FileTranslation;
 use Drupal\Core\Extension\ExtensionDiscovery;
@@ -338,6 +339,10 @@ function install_begin_request($class_loader, &$install_state) {
   $container
     ->register('string_translation', 'Drupal\Core\StringTranslation\TranslationManager')
     ->addArgument(new Reference('language_manager'));
+  $container
+    ->register('file_system', 'Drupal\Core\File\FileSystem')
+    ->addArgument(Settings::getInstance())
+    ->addArgument((new LoggerChannelFactory())->get('file'));
 
   // Register the stream wrapper manager.
   $container
diff --git a/core/lib/Drupal.php b/core/lib/Drupal.php
index 7b52d13..7479825 100644
--- a/core/lib/Drupal.php
+++ b/core/lib/Drupal.php
@@ -5,10 +5,32 @@
  * Contains Drupal.
  */
 
+use Drupal\Core\DependencyInjection\PlaceholderContainer;
 use Symfony\Component\DependencyInjection\ContainerInterface;
 use Drupal\Core\Url;
 
 /**
+ * Initialize \Drupal::$container with a placeholder object.
+ * See https://www.drupal.org/node/2363341
+ *
+ * This technique is the most reliable way to initialize static properties with
+ * non-trivial expressions. It should NOT be used for anything else. Also, the
+ * code being called MUST NOT have any side effects other than initializing the
+ * static properties.
+ *
+ * In general (e.g. in PSR-1), a PHP file should either declare symbols OR have
+ * side-effects, but not both. This specific case is ok only because the side
+ * effect applies to nothing else but the class declared in the same file, and
+ * it happens immediately after the class is being declared. A version of the
+ * class without this initialization applied is never available to the outside
+ * world.
+ *
+ * Note: PHP does not care whether this is called before or after the class
+ * declaration. It is called before only for better visibility.
+ */
+\Drupal::initStaticProperties();
+
+/**
  * Static Service Container wrapper.
  *
  * Generally, code in Drupal should accept its dependencies via either
@@ -103,15 +125,32 @@ class Drupal {
    * Sets a new global container.
    *
    * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
-   *   A new container instance to replace the current. NULL may be passed by
-   *   testing frameworks to ensure that the global state of a previous
-   *   environment does not leak into a test.
+   *   A new container instance to replace the current.
    */
-  public static function setContainer(ContainerInterface $container = NULL) {
+  public static function setContainer(ContainerInterface $container) {
     static::$container = $container;
   }
 
   /**
+   * Unsets the global container.
+   *
+   * @param string|null $message
+   *   The message to pass to the placeholder container.
+   */
+  public static function unsetContainer($message = NULL) {
+    $message = $message ?: '\Drupal::$container was unset with \Drupal::unsetContainer().';
+    static::setContainer(new PlaceholderContainer($message));
+  }
+
+  /**
+   * Initializes the static properties. Called from within the class file.
+   */
+  public static function initStaticProperties() {
+    $message = '\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.';
+    static::setContainer(new PlaceholderContainer($message));
+  }
+
+  /**
    * Returns the currently active global container.
    *
    * @deprecated This method is only useful for the testing environment. It
@@ -120,6 +159,15 @@ public static function setContainer(ContainerInterface $container = NULL) {
    * @return \Symfony\Component\DependencyInjection\ContainerInterface|null
    */
   public static function getContainer() {
+    if (static::$container instanceof PlaceholderContainer) {
+      // @todo Currently drush depends on this method returning NULL if not
+      //   initialized. Once drush is fixed, remove this workaround.
+      if (PHP_SAPI === 'cli') {
+        return NULL;
+      }
+      // Trigger the exception from the placeholder container.
+      static::$container->throwException();
+    }
     return static::$container;
   }
 
@@ -149,7 +197,7 @@ public static function service($id) {
    *   TRUE if the specified service exists, FALSE otherwise.
    */
   public static function hasService($id) {
-    return static::$container && static::$container->has($id);
+    return static::$container->has($id);
   }
 
   /**
@@ -168,7 +216,7 @@ public static function root() {
    *   TRUE if there is a currently active request object, FALSE otherwise.
    */
   public static function hasRequest() {
-    return static::$container && static::$container->has('request_stack') && static::$container->get('request_stack')->getCurrentRequest() !== NULL;
+    return static::$container->has('request_stack') && static::$container->get('request_stack')->getCurrentRequest() !== NULL;
   }
 
   /**
diff --git a/core/lib/Drupal/Core/DependencyInjection/ContainerNotInitializedException.php b/core/lib/Drupal/Core/DependencyInjection/ContainerNotInitializedException.php
new file mode 100644
index 0000000..e593243
--- /dev/null
+++ b/core/lib/Drupal/Core/DependencyInjection/ContainerNotInitializedException.php
@@ -0,0 +1,19 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\DependencyInjection\ContainerNotInitializedException.
+ */
+
+namespace Drupal\Core\DependencyInjection;
+
+/**
+ * Exception thrown when a method is called that requires a container, but the
+ * container is not initialized yet.
+ *
+ * @see \Drupal
+ * @see \Drupal\Core\DependencyInjection\PlaceholderContainer
+ */
+class ContainerNotInitializedException extends \RuntimeException {
+
+}
diff --git a/core/lib/Drupal/Core/DependencyInjection/PlaceholderContainer.php b/core/lib/Drupal/Core/DependencyInjection/PlaceholderContainer.php
new file mode 100644
index 0000000..c039b7a
--- /dev/null
+++ b/core/lib/Drupal/Core/DependencyInjection/PlaceholderContainer.php
@@ -0,0 +1,123 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\DependencyInjection\PlaceholderContainer.
+ */
+
+namespace Drupal\Core\DependencyInjection;
+
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\DependencyInjection\ScopeInterface;
+
+/**
+ * A placeholder container that throws an exception whenever it does anything.
+ *
+ * @see \Drupal
+ */
+class PlaceholderContainer implements ContainerInterface {
+
+  /**
+   * Message for ContainerNotInitializedException.
+   *
+   * @var string
+   */
+  protected $message;
+
+  /**
+   * Constructs a PlaceholderContainer object.
+   *
+   * @param string $exception_message
+   *   Message for ContainerNotInitializedException.
+   */
+  public function __construct($exception_message = NULL) {
+    $this->message = $exception_message ?: 'Container not initialized.';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function set($id, $service, $scope = self::SCOPE_CONTAINER) {
+    $this->throwException();
+  }
+
+  /**
+   * Throws an exception.
+   *
+   * @throws \Drupal\Core\DependencyInjection\ContainerNotInitializedException
+   */
+  public function throwException() {
+    throw new ContainerNotInitializedException($this->message);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE) {
+    $this->throwException();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function has($id) {
+    return FALSE;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getParameter($name) {
+    $this->throwException();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function hasParameter($name) {
+    $this->throwException();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function setParameter($name, $value) {
+    $this->throwException();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function enterScope($name) {
+    $this->throwException();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function leaveScope($name) {
+    $this->throwException();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function addScope(ScopeInterface $scope) {
+    $this->throwException();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function hasScope($name) {
+    $this->throwException();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function isScopeActive($name) {
+    $this->throwException();
+  }
+
+}
diff --git a/core/lib/Drupal/Core/File/FileSystem.php b/core/lib/Drupal/Core/File/FileSystem.php
new file mode 100644
index 0000000..75e9b57
--- /dev/null
+++ b/core/lib/Drupal/Core/File/FileSystem.php
@@ -0,0 +1,507 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Core\File\File.
+ */
+
+namespace Drupal\Core\File;
+
+use Drupal\Core\Site\Settings;
+use Psr\Log\LoggerInterface;
+
+/**
+ * Provides helpers to operate on files and stream wrappers.
+ */
+class FileSystem {
+
+  /**
+   * Default mode for new directories. See self::chmod().
+   */
+  const CHMOD_DIRECTORY = 0775;
+
+  /**
+   * Default mode for new files. See self::chmod().
+   */
+  const CHMOD_FILE = 0664;
+
+  /**
+   * The site settings.
+   *
+   * @var \Drupal\Core\Site\Settings
+   */
+  protected $settings;
+
+  /**
+   * The file logger channel.
+   *
+   * @var \Psr\Log\LoggerInterface
+   */
+  protected $logger;
+
+  /**
+   * Constructs a new FileSystem.
+   *
+   * @param \Drupal\Core\Site\Settings $settings
+   *   The site settings.
+   * @param \Psr\Log\LoggerInterface $logger
+   *   The file logger channel.
+   */
+  public function __construct(Settings $settings, LoggerInterface $logger) {
+    $this->settings = $settings;
+    $this->logger = $logger;
+  }
+
+  /**
+   * Moves an uploaded file to a new location.
+   *
+   * PHP's move_uploaded_file() does not properly support streams if
+   * open_basedir is enabled, so this function fills that gap.
+   *
+   * Compatibility: normal paths and stream wrappers.
+   *
+   * @param string $filename
+   *   The filename of the uploaded file.
+   * @param string $uri
+   *   A string containing the destination URI of the file.
+   *
+   * @return bool
+   *   TRUE on success, or FALSE on failure.
+   *
+   * @see move_uploaded_file()
+   * @see http://drupal.org/node/515192
+   * @ingroup php_wrappers
+   */
+  public function moveUploadedFile($filename, $uri) {
+    $result = @move_uploaded_file($filename, $uri);
+    // PHP's move_uploaded_file() does not properly support streams if
+    // open_basedir is enabled so if the move failed, try finding a real path
+    // and retry the move operation.
+    if (!$result) {
+      if ($realpath = $this->realpath($uri)) {
+        $result = move_uploaded_file($filename, $realpath);
+      }
+      else {
+        $result = move_uploaded_file($filename, $uri);
+      }
+    }
+
+    return $result;
+  }
+
+  /**
+   * Sets the permissions on a file or directory.
+   *
+   * This function will use the file_chmod_directory and
+   * file_chmod_file settings for the default modes for directories
+   * and uploaded/generated files. By default these will give everyone read
+   * access so that users accessing the files with a user account without the
+   * webserver group (e.g. via FTP) can read these files, and give group write
+   * permissions so webserver group members (e.g. a vhost account) can alter
+   * files uploaded and owned by the webserver.
+   *
+   * PHP's chmod does not support stream wrappers so we use our wrapper
+   * implementation which interfaces with chmod() by default. Contrib wrappers
+   * may override this behavior in their implementations as needed.
+   *
+   * @param $uri
+   *   A string containing a URI file, or directory path.
+   * @param $mode
+   *   Integer value for the permissions. Consult PHP chmod() documentation for
+   *   more information.
+   *
+   * @return bool
+   *   TRUE for success, FALSE in the event of an error.
+   *
+   * @ingroup php_wrappers
+   */
+  public function chmod($uri, $mode = NULL) {
+    if (!isset($mode)) {
+      if (is_dir($uri)) {
+        $mode = $this->getSetting('file_chmod_directory', static::CHMOD_DIRECTORY);
+      }
+      else {
+        $mode = $this->getSetting('file_chmod_file', static::CHMOD_FILE);
+      }
+    }
+
+    if (@chmod($uri, $mode)) {
+      return TRUE;
+    }
+
+    $this->logger->error('The file permissions could not be set on %uri.', array('%uri' => $uri));
+    return FALSE;
+  }
+
+  /**
+   * Deletes a file.
+   *
+   * PHP's unlink() is broken on Windows, as it can fail to remove a file when
+   * it has a read-only flag set.
+   *
+   * @param string $uri
+   *   A URI or pathname.
+   * @param $context
+   *   Refer to http://php.net/manual/ref.stream.php
+   *
+   * @return bool
+   *   Boolean TRUE on success, or FALSE on failure.
+   *
+   * @see unlink()
+   * @ingroup php_wrappers
+   */
+  public function unlink($uri, $context = NULL) {
+    $scheme = $this->uriScheme($uri);
+    if (!$this->validScheme($scheme) && (substr(PHP_OS, 0, 3) == 'WIN')) {
+      chmod($uri, 0600);
+    }
+    if ($context) {
+      return unlink($uri, $context);
+    }
+    else {
+      return unlink($uri);
+    }
+  }
+
+  /**
+   * Resolves the absolute filepath of a local URI or filepath.
+   *
+   * The use of this method is discouraged, because it does not work for
+   * remote URIs. Except in rare cases, URIs should not be manually resolved.
+   *
+   * Only use this function if you know that the stream wrapper in the URI uses
+   * the local file system, and you need to pass an absolute path to a function
+   * that is incompatible with stream URIs.
+   *
+   * @param string $uri
+   *   A stream wrapper URI or a filepath, possibly including one or more
+   *   symbolic links.
+   *
+   * @return string|false
+   *   The absolute local filepath (with no symbolic links) or FALSE on failure.
+   *
+   * @see \Drupal\Core\StreamWrapper\StreamWrapperInterface::realpath()
+   * @see http://php.net/manual/function.realpath.php
+   * @ingroup php_wrappers
+   */
+  public function realpath($uri) {
+    // If this URI is a stream, pass it off to the appropriate stream wrapper.
+    // Otherwise, attempt PHP's realpath. This allows use of this method even
+    // for unmanaged files outside of the stream wrapper interface.
+    if ($wrapper = $this->getStreamWrapperByUri($uri)) {
+      return $wrapper->realpath();
+    }
+
+    return realpath($uri);
+  }
+
+  /**
+   * Gets the name of the directory from a given path.
+   *
+   * PHP's dirname() does not properly pass streams, so this function fills that
+   * gap. It is backwards compatible with normal paths and will use PHP's
+   * dirname() as a fallback.
+   *
+   * Compatibility: normal paths and stream wrappers.
+   *
+   * @param string $uri
+   *   A URI or path.
+   *
+   * @return string
+   *   A string containing the directory name.
+   *
+   * @see dirname()
+   * @see http://drupal.org/node/515192
+   * @ingroup php_wrappers
+   */
+  public function dirname($uri) {
+    $scheme = $this->uriScheme($uri);
+
+    if ($this->validScheme($scheme)) {
+      return $this->getStreamWrapperByScheme($scheme)->dirname($uri);
+    }
+    else {
+      return dirname($uri);
+    }
+  }
+
+  /**
+   * Gets the filename from a given path.
+   *
+   * PHP's basename() does not properly support streams or filenames beginning
+   * with a non-US-ASCII character.
+   *
+   * @see http://bugs.php.net/bug.php?id=37738
+   * @see basename()
+   *
+   * @ingroup php_wrappers
+   */
+  public function basename($uri, $suffix = NULL) {
+    $separators = '/';
+    if (DIRECTORY_SEPARATOR != '/') {
+      // For Windows OS add special separator.
+      $separators .= DIRECTORY_SEPARATOR;
+    }
+    // Remove right-most slashes when $uri points to directory.
+    $uri = rtrim($uri, $separators);
+    // Returns the trailing part of the $uri starting after one of the directory
+    // separators.
+    $filename = preg_match('@[^' . preg_quote($separators, '@') . ']+$@', $uri, $matches) ? $matches[0] : '';
+    // Cuts off a suffix from the filename.
+    if ($suffix) {
+      $filename = preg_replace('@' . preg_quote($suffix, '@') . '$@', '', $filename);
+    }
+    return $filename;
+  }
+
+  /**
+   * Creates a directory, optionally creating missing components in the path to
+   * the directory.
+   *
+   * When PHP's mkdir() creates a directory, the requested mode is affected by
+   * the process's umask. This function overrides the umask and sets the mode
+   * explicitly for all directory components created.
+   *
+   * @param $uri
+   *   A URI or pathname.
+   * @param $mode
+   *   Mode given to created directories. Defaults to the directory mode
+   *   configured in the Drupal installation. It must have a leading zero.
+   * @param $recursive
+   *   Create directories recursively, defaults to FALSE. Cannot work with a
+   *   mode which denies writing or execution to the owner of the process.
+   * @param $context
+   *   Refer to http://php.net/manual/ref.stream.php
+   *
+   * @return bool
+   *   Boolean TRUE on success, or FALSE on failure.
+   *
+   * @see mkdir()
+   * @see http://drupal.org/node/515192
+   * @ingroup php_wrappers
+   *
+   * @todo Update with open_basedir compatible recursion logic from
+   *   \Drupal\Component\PhpStorage\FileStorage::ensureDirectory().
+   */
+  public function mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL) {
+    if (!isset($mode)) {
+      $mode = $this->getSetting('file_chmod_directory', static::CHMOD_DIRECTORY);
+    }
+
+    // If the URI has a scheme, don't override the umask - schemes can handle
+    // this issue in their own implementation.
+    if ($this->uriScheme($uri)) {
+      return $this->mkdirCall($uri, $mode, $recursive, $context);
+    }
+
+    // If recursive, create each missing component of the parent directory
+    // individually and set the mode explicitly to override the umask.
+    if ($recursive) {
+      // Ensure the path is using DIRECTORY_SEPARATOR.
+      $uri = str_replace('/', DIRECTORY_SEPARATOR, $uri);
+      // Determine the components of the path.
+      $components = explode(DIRECTORY_SEPARATOR, $uri);
+      // If the filepath is absolute the first component will be empty as there
+      // will be nothing before the first slash.
+      if ($components[0] == '') {
+        $recursive_path = DIRECTORY_SEPARATOR;
+        // Get rid of the empty first component.
+        array_shift($components);
+      }
+      else {
+        $recursive_path = '';
+      }
+      // Don't handle the top-level directory in this loop.
+      array_pop($components);
+      // Create each component if necessary.
+      foreach ($components as $component) {
+        $recursive_path .= $component;
+
+        if (!file_exists($recursive_path)) {
+          if (!$this->mkdirCall($recursive_path, $mode, FALSE, $context)) {
+            return FALSE;
+          }
+          // Not necessary to use self::chmod() as there is no scheme.
+          if (!chmod($recursive_path, $mode)) {
+            return FALSE;
+          }
+        }
+
+        $recursive_path .= DIRECTORY_SEPARATOR;
+      }
+    }
+
+    // Do not check if the top-level directory already exists, as this condition
+    // must cause this function to fail.
+    if (!$this->mkdirCall($uri, $mode, FALSE, $context)) {
+      return FALSE;
+    }
+    // Not necessary to use self::chmod() as there is no scheme.
+    return chmod($uri, $mode);
+  }
+
+  /**
+   * Helper function. Ensures we don't pass a NULL as a context resource to
+   * mkdir().
+   *
+   * @see self::mkdir()
+   */
+  protected function mkdirCall($uri, $mode, $recursive, $context) {
+    if (is_null($context)) {
+      return mkdir($uri, $mode, $recursive);
+    }
+    else {
+      return mkdir($uri, $mode, $recursive, $context);
+    }
+  }
+
+  /**
+   * Removes a directory.
+   *
+   * PHP's rmdir() is broken on Windows, as it can fail to remove a directory
+   * when it has a read-only flag set.
+   *
+   * @param $uri
+   *   A URI or pathname.
+   * @param $context
+   *   Refer to http://php.net/manual/ref.stream.php
+   *
+   * @return bool
+   *   Boolean TRUE on success, or FALSE on failure.
+   *
+   * @see rmdir()
+   * @ingroup php_wrappers
+   */
+  public function rmdir($uri, $context = NULL) {
+    $scheme = $this->uriScheme($uri);
+    if (!$this->validScheme($scheme) && (substr(PHP_OS, 0, 3) == 'WIN')) {
+      chmod($uri, 0700);
+    }
+    if ($context) {
+      return rmdir($uri, $context);
+    }
+    else {
+      return rmdir($uri);
+    }
+  }
+
+  /**
+   * Creates a file with a unique filename in the specified directory.
+   *
+   * PHP's tempnam() does not return a URI like we want. This function will
+   * return a URI if given a URI, or it will return a filepath if given a
+   * filepath.
+   *
+   * Compatibility: normal paths and stream wrappers.
+   *
+   * @param $directory
+   *   The directory where the temporary filename will be created.
+   * @param $prefix
+   *   The prefix of the generated temporary filename.
+   *   Note: Windows uses only the first three characters of prefix.
+   *
+   * @return string|bool
+   *   The new temporary filename, or FALSE on failure.
+   *
+   * @see tempnam()
+   * @see http://drupal.org/node/515192
+   * @ingroup php_wrappers
+   */
+  public function tempnam($directory, $prefix) {
+    $scheme = $this->uriScheme($directory);
+
+    if ($this->validScheme($scheme)) {
+      $wrapper = $this->getStreamWrapperByScheme($scheme);
+
+      if ($filename = tempnam($wrapper->getDirectoryPath(), $prefix)) {
+        return $scheme . '://' . static::basename($filename);
+      }
+      else {
+        return FALSE;
+      }
+    }
+    else {
+      // Handle as a normal tempnam() call.
+      return tempnam($directory, $prefix);
+    }
+  }
+
+  /**
+   * Returns the scheme of a URI (e.g. a stream).
+   *
+   * @param string $uri
+   *   A stream, referenced as "scheme://target" or "data:target".
+   *
+   * @return string|bool
+   *   A string containing the name of the scheme, or FALSE if none. For
+   *   example, the URI "public://example.txt" would return "public".
+   *
+   * @see file_uri_target()
+   */
+  public function uriScheme($uri) {
+    if (preg_match('/^([\w\-]+):\/\/|^(data):/', $uri, $matches)) {
+      // The scheme will always be the last element in the matches array.
+      return array_pop($matches);
+    }
+
+    return FALSE;
+  }
+
+  /**
+   * Checks that the scheme of a stream URI is valid.
+   *
+   * Confirms that there is a registered stream handler for the provided scheme
+   * and that it is callable. This is useful if you want to confirm a valid
+   * scheme without creating a new instance of the registered handler.
+   *
+   * @param $scheme
+   *   A URI scheme, a stream is referenced as "scheme://target".
+   *
+   * @return bool
+   *   Returns TRUE if the string is the name of a validated stream, or FALSE if
+   *   the scheme does not have a registered handler.
+   */
+  public function validScheme($scheme) {
+    if (!$scheme) {
+      return FALSE;
+    }
+    return class_exists($this->getStreamWrapperClass($scheme));
+  }
+
+  /**
+   * Wraps file_stream_wrapper_get_class().
+   *
+   * @codeCoverageIgnore
+   */
+  protected function getStreamWrapperClass($scheme) {
+    return file_stream_wrapper_get_class($scheme);
+  }
+
+  /**
+   * Wraps file_stream_wrapper_get_instance_by_scheme().
+   *
+   * @codeCoverageIgnore
+   */
+  protected function getStreamWrapperByScheme($scheme) {
+    return file_stream_wrapper_get_instance_by_scheme($scheme);
+  }
+
+  /**
+   * Wraps file_stream_wrapper_get_instance_by_uri().
+   *
+   * @codeCoverageIgnore
+   */
+  protected function getStreamWrapperByUri($uri) {
+    return file_stream_wrapper_get_instance_by_uri($uri);
+  }
+
+  /**
+   * Wraps the global Settings singleton.
+   *
+   * @codeCoverageIgnore
+   */
+  protected function getSetting($name, $default = NULL) {
+    return $this->settings->get($name, $default);
+  }
+
+}
diff --git a/core/modules/simpletest/src/KernelTestBase.php b/core/modules/simpletest/src/KernelTestBase.php
index d2c5341..94f8acc 100644
--- a/core/modules/simpletest/src/KernelTestBase.php
+++ b/core/modules/simpletest/src/KernelTestBase.php
@@ -147,9 +147,6 @@ protected function setUp() {
       $this->settingsSet('container_yamls', [$testing_services_file]);
     }
 
-    // Create and set new configuration directories.
-    $this->prepareConfigDirectories();
-
     // Add this test class as a service provider.
     // @todo Remove the indirection; implement ServiceProviderInterface instead.
     $GLOBALS['conf']['container_service_providers']['TestServiceProvider'] = 'Drupal\simpletest\TestServiceProvider';
@@ -172,6 +169,9 @@ protected function setUp() {
     // method sets additional settings.
     new Settings($settings + Settings::getAll());
 
+    // Create and set new configuration directories.
+    $this->prepareConfigDirectories();
+
     // Set the request scope.
     $this->container = $this->kernel->getContainer();
     $this->container->get('request_stack')->push($request);
diff --git a/core/modules/simpletest/src/TestBase.php b/core/modules/simpletest/src/TestBase.php
index b4901af..a6d1bf2 100644
--- a/core/modules/simpletest/src/TestBase.php
+++ b/core/modules/simpletest/src/TestBase.php
@@ -1187,7 +1187,7 @@ private function prepareEnvironment() {
 
     // Ensure there is no service container.
     $this->container = NULL;
-    \Drupal::setContainer(NULL);
+    \Drupal::unsetContainer();
 
     // Unset globals.
     unset($GLOBALS['config_directories']);
diff --git a/core/modules/simpletest/src/WebTestBase.php b/core/modules/simpletest/src/WebTestBase.php
index 98253a4..b3c9f59 100644
--- a/core/modules/simpletest/src/WebTestBase.php
+++ b/core/modules/simpletest/src/WebTestBase.php
@@ -1005,13 +1005,28 @@ protected function installParameters() {
 
     // If we only have one db driver available, we cannot set the driver.
     include_once DRUPAL_ROOT . '/core/includes/install.inc';
-    if (count(drupal_get_database_types()) == 1) {
+    if (count($this->getDatabaseTypes()) == 1) {
       unset($parameters['forms']['install_settings_form']['driver']);
     }
     return $parameters;
   }
 
   /**
+   * Returns all supported database driver installer objects.
+   *
+   * This wraps drupal_get_database_types() for use without a current container.
+   *
+   * @return \Drupal\Core\Database\Install\Tasks[]
+   *   An array of available database driver installer objects.
+   */
+  protected function getDatabaseTypes() {
+    \Drupal::setContainer($this->originalContainer);
+    $database_types = drupal_get_database_types();
+    \Drupal::unsetContainer();
+    return $database_types;
+  }
+
+  /**
    * Rewrites the settings.php file of the test site.
    *
    * @param array $settings
diff --git a/core/modules/system/src/Tests/Bootstrap/GetFilenameUnitTest.php b/core/modules/system/src/Tests/Bootstrap/GetFilenameUnitTest.php
index a7bcca7..1636b1f 100644
--- a/core/modules/system/src/Tests/Bootstrap/GetFilenameUnitTest.php
+++ b/core/modules/system/src/Tests/Bootstrap/GetFilenameUnitTest.php
@@ -16,10 +16,32 @@
  */
 class GetFilenameUnitTest extends KernelTestBase {
 
+  /**
+   * The container used by the test, moved out of the way.
+   *
+   * @var \Symfony\Component\DependencyInjection\ContainerInterface
+   */
+  protected $previousContainer;
+
+  /**
+   * {@inheritdoc}
+   */
   protected function setUp() {
     parent::setUp();
+    // Store the previous container.
+    $this->previousContainer = $this->container;
     $this->container = NULL;
-    \Drupal::setContainer(NULL);
+    \Drupal::unsetContainer();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function tearDown() {
+    parent::tearDown();
+    // Restore the previous container.
+    $this->container = $this->previousContainer;
+    \Drupal::setContainer($this->previousContainer);
   }
 
   /**
diff --git a/core/modules/system/src/Tests/DrupalKernel/DrupalKernelTest.php b/core/modules/system/src/Tests/DrupalKernel/DrupalKernelTest.php
index af8ce27..ebd8307 100644
--- a/core/modules/system/src/Tests/DrupalKernel/DrupalKernelTest.php
+++ b/core/modules/system/src/Tests/DrupalKernel/DrupalKernelTest.php
@@ -36,6 +36,15 @@ protected function setUp() {
   }
 
   /**
+   * {@inheritdoc}
+   */
+  protected function prepareConfigDirectories() {
+    \Drupal::setContainer($this->originalContainer);
+    parent::prepareConfigDirectories();
+    \Drupal::unsetContainer();
+  }
+
+  /**
    * Build a kernel for testings.
    *
    * Because the bootstrap is in DrupalKernel::boot and that involved loading
diff --git a/core/modules/system/src/Tests/File/UnmanagedCopyTest.php b/core/modules/system/src/Tests/File/UnmanagedCopyTest.php
index 0169702..f525c1d 100644
--- a/core/modules/system/src/Tests/File/UnmanagedCopyTest.php
+++ b/core/modules/system/src/Tests/File/UnmanagedCopyTest.php
@@ -8,6 +8,7 @@
 namespace Drupal\system\Tests\File;
 
 use Drupal\Core\Site\Settings;
+use Drupal\Core\File\FileSystem;
 
 /**
  * Tests the unmanaged file copy function.
@@ -29,7 +30,7 @@ function testNormal() {
     $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
     $this->assertTrue(file_exists($uri), 'Original file remains.');
     $this->assertTrue(file_exists($new_filepath), 'New file exists.');
-    $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
+    $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FileSystem::CHMOD_FILE));
 
     // Copying with rename.
     $desired_filepath = 'public://' . $this->randomMachineName();
@@ -39,7 +40,7 @@ function testNormal() {
     $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
     $this->assertTrue(file_exists($uri), 'Original file remains.');
     $this->assertTrue(file_exists($newer_filepath), 'New file exists.');
-    $this->assertFilePermissions($newer_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
+    $this->assertFilePermissions($newer_filepath, Settings::get('file_chmod_file', FileSystem::CHMOD_FILE));
 
     // TODO: test copying to a directory (rather than full directory/file path)
     // TODO: test copying normal files using normal paths (rather than only streams)
@@ -69,7 +70,7 @@ function testOverwriteSelf() {
     $this->assertNotEqual($new_filepath, $uri, 'Copied file has a new name.');
     $this->assertTrue(file_exists($uri), 'Original file exists after copying onto itself.');
     $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
-    $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
+    $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FileSystem::CHMOD_FILE));
 
     // Copy the file onto itself without renaming fails.
     $new_filepath = file_unmanaged_copy($uri, $uri, FILE_EXISTS_ERROR);
@@ -87,6 +88,6 @@ function testOverwriteSelf() {
     $this->assertNotEqual($new_filepath, $uri, 'Copied file has a new name.');
     $this->assertTrue(file_exists($uri), 'Original file exists after copying onto itself.');
     $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
-    $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
+    $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FileSystem::CHMOD_FILE));
   }
 }
diff --git a/core/modules/system/src/Tests/File/UnmanagedMoveTest.php b/core/modules/system/src/Tests/File/UnmanagedMoveTest.php
index e2bece8..ea39c54 100644
--- a/core/modules/system/src/Tests/File/UnmanagedMoveTest.php
+++ b/core/modules/system/src/Tests/File/UnmanagedMoveTest.php
@@ -8,6 +8,7 @@
 namespace Drupal\system\Tests\File;
 
 use Drupal\Core\Site\Settings;
+use Drupal\Core\File\FileSystem;
 
 /**
  * Tests the unmanaged file move function.
@@ -29,7 +30,7 @@ function testNormal() {
     $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
     $this->assertTrue(file_exists($new_filepath), 'File exists at the new location.');
     $this->assertFalse(file_exists($uri), 'No file remains at the old location.');
-    $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
+    $this->assertFilePermissions($new_filepath, Settings::get('file_chmod_file', FileSystem::CHMOD_FILE));
 
     // Moving with rename.
     $desired_filepath = 'public://' . $this->randomMachineName();
@@ -40,7 +41,7 @@ function testNormal() {
     $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
     $this->assertTrue(file_exists($newer_filepath), 'File exists at the new location.');
     $this->assertFalse(file_exists($new_filepath), 'No file remains at the old location.');
-    $this->assertFilePermissions($newer_filepath, Settings::get('file_chmod_file', FILE_CHMOD_FILE));
+    $this->assertFilePermissions($newer_filepath, Settings::get('file_chmod_file', FileSystem::CHMOD_FILE));
 
     // TODO: test moving to a directory (rather than full directory/file path)
     // TODO: test creating and moving normal files (rather than streams)
diff --git a/core/modules/system/src/Tests/Routing/RouteProviderTest.php b/core/modules/system/src/Tests/Routing/RouteProviderTest.php
index be8862c..6ba9f97 100644
--- a/core/modules/system/src/Tests/Routing/RouteProviderTest.php
+++ b/core/modules/system/src/Tests/Routing/RouteProviderTest.php
@@ -50,6 +50,7 @@ class RouteProviderTest extends KernelTestBase {
   protected $state;
 
   protected function setUp() {
+    parent::setUp();
     $this->fixtures = new RoutingFixtures();
     $this->routeBuilder = new NullRouteBuilder();
     $this->state = new State(new KeyValueMemoryFactory());
diff --git a/core/tests/Drupal/Tests/Core/DrupalContainerNotInitializedTest.php b/core/tests/Drupal/Tests/Core/DrupalContainerNotInitializedTest.php
new file mode 100644
index 0000000..5161e71
--- /dev/null
+++ b/core/tests/Drupal/Tests/Core/DrupalContainerNotInitializedTest.php
@@ -0,0 +1,156 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Tests\Core\DrupalTest.
+ */
+
+namespace Drupal\Tests\Core;
+
+use Drupal\Core\DependencyInjection\ContainerNotInitializedException;
+use Drupal\Core\Url;
+
+/**
+ * Tests the case where Drupal::$container is not initialized.
+ *
+ * @group DrupalTest
+ */
+class DrupalContainerNotInitializedTest extends \PHPUnit_Framework_TestCase {
+
+  /**
+   * Tests the case where \Drupal::$container is not initialized.
+   *
+   * @dataProvider methodsWithReturnProvider
+   *
+   * @param string $method
+   *   The static method to call on \Drupal::
+   * @param mixed $expected
+   *   Expected return value.
+   * @param array $args
+   *   Arguments to pass into \Drupal::$method(..)
+   */
+  public function testContainerNotInitializedReturn($method, $expected, $args = array()) {
+    $result = call_user_func_array(['Drupal', $method], $args);
+    $this->assertEquals($expected, $result);
+  }
+
+  /**
+   * Tests the case where \Drupal::$container is not initialized.
+   *
+   * @dataProvider methodsWithExceptionProvider
+   *
+   * @param string $method
+   *   The static method to call on \Drupal::
+   * @param array $args
+   *   Arguments to pass into \Drupal::$method(..)
+   *
+   * @expectedException \Drupal\Core\DependencyInjection\ContainerNotInitializedException
+   * @expectedExceptionMessage \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.
+   */
+  public function testContainerNotInitializedException($method, $args = array()) {
+    call_user_func_array(['Drupal', $method], $args);
+  }
+
+  /**
+   * Tests the case where \Drupal::$container was unset.
+   *
+   * @dataProvider methodsWithReturnProvider
+   *
+   * @param string $method
+   *   The static method to call on \Drupal::
+   * @param mixed $expected
+   *   Expected return value.
+   * @param array $args
+   *   Arguments to pass into \Drupal::$method(..)
+   */
+  public function testUnsetContainerReturn($method, $expected, $args = array()) {
+    \Drupal::unsetContainer(__METHOD__);
+    $result = call_user_func_array(['Drupal', $method], $args);
+    $this->assertEquals($expected, $result);
+  }
+
+  /**
+   * Tests the case where \Drupal::$container was unset.
+   *
+   * @dataProvider methodsWithExceptionProvider
+   *
+   * @param string $method
+   *   The static method to call on \Drupal::
+   * @param array $args
+   *   Arguments to pass into \Drupal::$method(..)
+   *
+   * @expectedException \Drupal\Core\DependencyInjection\ContainerNotInitializedException
+   * @expectedExceptionMessage Custom exception message.
+   */
+  public function testUnsetContainerException($method, $args = array()) {
+    \Drupal::unsetContainer('Custom exception message.');
+    call_user_func_array(['Drupal', $method], $args);
+  }
+
+  /**
+   * Data provider for two methods, see "@see" below.
+   *
+   * @return array[]
+   *
+   * @see testContainerNotInitializedReturn()
+   * @see testUnsetContainerReturn()
+   */
+  public function methodsWithReturnProvider() {
+    return array(
+      ['getContainer', NULL],
+      ['hasService', FALSE, ['test_service']],
+      ['hasRequest', FALSE],
+    );
+  }
+
+  /**
+   * Data provider for two methods, see "@see" below.
+   *
+   * @return array[]
+   *
+   * @see testContainerNotInitializedException()
+   * @see testUnsetContainerException()
+   */
+  public function methodsWithExceptionProvider() {
+    return array(
+      ['service', ['test_service']],
+      ['request'],
+      ['requestStack'],
+      ['routeMatch'],
+      ['currentUser'],
+      ['entityManager'],
+      ['database'],
+      ['cache', ['test']],
+      ['keyValueExpirable', ['test_collection']],
+      ['lock'],
+      ['config', ['test_config']],
+      ['configFactory'],
+      ['queue', ['test_queue', TRUE]],
+      ['keyValue', ['test_collection']],
+      ['state'],
+      ['httpClient'],
+      ['entityQuery', ['OR']],
+      ['entityQueryAggregate', ['test_entity', 'OR']],
+      ['flood', ['test_service']],
+      ['moduleHandler', ['test_service']],
+      ['typedDataManager', ['test_service']],
+      ['token'],
+      ['urlGenerator'],
+      ['url', ['test_route']],
+      ['linkGenerator'],
+      ['l', ['Test title', new Url('test_route')]],
+      ['translation'],
+      ['languageManager'],
+      ['csrfToken'],
+      ['transliteration'],
+      ['formBuilder'],
+      ['theme'],
+      ['isConfigSyncing'],
+      ['logger', ['test_channel']],
+      ['menuTree'],
+      ['pathValidator'],
+      ['accessManager'],
+    );
+  }
+
+}
diff --git a/core/tests/Drupal/Tests/Core/File/FileSystemTest.php b/core/tests/Drupal/Tests/Core/File/FileSystemTest.php
new file mode 100644
index 0000000..da854f7
--- /dev/null
+++ b/core/tests/Drupal/Tests/Core/File/FileSystemTest.php
@@ -0,0 +1,182 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Tests\Core\File\FileSystemTest.
+ */
+
+namespace Drupal\Tests\Core\File;
+
+use Drupal\Core\File\FileSystem;
+use Drupal\Core\Site\Settings;
+use Drupal\Tests\UnitTestCase;
+use org\bovigo\vfs\vfsStream;
+
+/**
+ * @coversDefaultClass \Drupal\Core\File\FileSystem
+ *
+ * @group File
+ */
+class FileSystemTest extends UnitTestCase {
+
+  /**
+   * @var \Drupal\Core\File\FileSystem
+   */
+  protected $fileSystem;
+
+  /**
+   * The file logger channel.
+   *
+   * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $logger;
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function setUp() {
+    parent::setUp();
+
+    $settings = new Settings([]);
+    $this->logger = $this->getMock('Psr\Log\LoggerInterface');
+    $this->fileSystem = new FileSystem($settings, $this->logger);
+  }
+
+  /**
+   * @covers ::chmod
+   */
+  public function testChmodFile() {
+    vfsStream::setup('dir');
+    vfsStream::create(['test.txt' => 'asdf']);
+    $uri = 'vfs://dir/test.txt';
+
+    $this->assertTrue($this->fileSystem->chmod($uri));
+    $this->assertFilePermissions(FileSystem::CHMOD_FILE, $uri);
+    $this->assertTrue($this->fileSystem->chmod($uri, 0444));
+    $this->assertFilePermissions(0444, $uri);
+  }
+
+  /**
+   * @covers ::chmod
+   */
+  public function testChmodDir() {
+    vfsStream::setup('dir');
+    vfsStream::create(['nested_dir' => []]);
+    $uri = 'vfs://dir/nested_dir';
+
+    $this->assertTrue($this->fileSystem->chmod($uri));
+    $this->assertFilePermissions(FileSystem::CHMOD_DIRECTORY, $uri);
+    $this->assertTrue($this->fileSystem->chmod($uri, 0444));
+    $this->assertFilePermissions(0444, $uri);
+  }
+
+  /**
+   * @covers ::chmod
+   */
+  public function testChmodUnsuccessful() {
+    vfsStream::setup('dir');
+    $this->logger->expects($this->once())
+      ->method('error');
+    $this->assertFalse($this->fileSystem->chmod('vfs://dir/test.txt'));
+  }
+
+  /**
+   * @covers ::unlink
+   */
+  public function testUnlink() {
+    vfsStream::setup('dir');
+    vfsStream::create(['test.txt' => 'asdf']);
+    $uri = 'vfs://dir/test.txt';
+
+    $this->fileSystem = $this->getMockBuilder('Drupal\Core\File\FileSystem')
+      ->disableOriginalConstructor()
+      ->setMethods(['validScheme'])
+      ->getMock();
+    $this->fileSystem->expects($this->once())
+      ->method('validScheme')
+      ->willReturn(TRUE);
+
+    $this->assertFileExists($uri);
+    $this->fileSystem->unlink($uri);
+    $this->assertFileNotExists($uri);
+  }
+
+  /**
+   * @covers ::basename
+   *
+   * @dataProvider providerTestBasename
+   */
+  public function testBasename($uri, $expected, $suffix = NULL) {
+    $this->assertSame($expected, $this->fileSystem->basename($uri, $suffix));
+  }
+
+  public function providerTestBasename() {
+    $data = [];
+    $data[] = [
+      'public://nested/dir',
+      'dir',
+    ];
+    $data[] = [
+      'public://dir/test.txt',
+      'test.txt',
+    ];
+    $data[] = [
+      'public://dir/test.txt',
+      'test',
+      '.txt'
+    ];
+    return $data;
+  }
+
+  /**
+   * @covers ::uriScheme
+   *
+   * @dataProvider providerTestUriScheme
+   */
+  public function testUriScheme($uri, $expected) {
+    $this->assertSame($expected, $this->fileSystem->uriScheme($uri));
+  }
+
+  public function providerTestUriScheme() {
+    $data = [];
+    $data[] = [
+      'public://filename',
+      'public',
+    ];
+    $data[] = [
+      'public://extra://',
+      'public',
+    ];
+    $data[] = [
+      'invalid',
+      FALSE,
+    ];
+    return $data;
+  }
+
+  /**
+   * Asserts that the file permissions of a given URI matches.
+   *
+   * @param int $expected_mode
+   * @param string $uri
+   * @param string $message
+   */
+  protected function assertFilePermissions($expected_mode, $uri, $message = '') {
+    // Mask out all but the last three octets.
+    $actual_mode = fileperms($uri) & 0777;
+
+    // PHP on Windows has limited support for file permissions. Usually each of
+    // "user", "group" and "other" use one octal digit (3 bits) to represent the
+    // read/write/execute bits. On Windows, chmod() ignores the "group" and
+    // "other" bits, and fileperms() returns the "user" bits in all three
+    // positions. $expected_mode is updated to reflect this.
+    if (substr(PHP_OS, 0, 3) == 'WIN') {
+      // Reset the "group" and "other" bits.
+      $expected_mode = $expected_mode & 0700;
+      // Shift the "user" bits to the "group" and "other" positions also.
+      $expected_mode = $expected_mode | $expected_mode >> 3 | $expected_mode >> 6;
+    }
+    $this->assertSame($expected_mode, $actual_mode, $message);
+  }
+
+}
diff --git a/core/tests/Drupal/Tests/UnitTestCase.php b/core/tests/Drupal/Tests/UnitTestCase.php
index d6deb9e..e82c3a9 100644
--- a/core/tests/Drupal/Tests/UnitTestCase.php
+++ b/core/tests/Drupal/Tests/UnitTestCase.php
@@ -39,7 +39,7 @@ protected function setUp() {
     parent::setUp();
     // Ensure that an instantiated container in the global state of \Drupal from
     // a previous test does not leak into this test.
-    \Drupal::setContainer(NULL);
+    \Drupal::unsetContainer();
 
     $this->root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
   }
