diff --git a/core/includes/common.inc b/core/includes/common.inc
index e2a28c3..b63c6be 100644
--- a/core/includes/common.inc
+++ b/core/includes/common.inc
@@ -3,8 +3,6 @@
 use Drupal\Component\Utility\Crypt;
 use Drupal\Core\Cache\Cache;
 use Symfony\Component\DependencyInjection\Container;
-use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
-use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
 use Symfony\Component\Yaml\Parser;
 use Drupal\Component\PhpStorage\PhpStorageFactory;
 use Drupal\Component\Utility\NestedArray;
@@ -6070,10 +6068,11 @@ function drupal_implode_tags($tags) {
  *   requests.
  */
 function drupal_flush_all_caches() {
+  $module_handler = Drupal::moduleHandler();
   // Flush all persistent caches.
   // This is executed based on old/previously known information, which is
   // sufficient, since new extensions cannot have any primed caches yet.
-  module_invoke_all('cache_flush');
+  $module_handler->invokeAll('cache_flush');
   foreach (Cache::getBins() as $service_id => $cache_backend) {
     if ($service_id != 'cache.menu') {
       $cache_backend->deleteAll();
@@ -6089,16 +6088,32 @@ function drupal_flush_all_caches() {
   drupal_static_reset();
 
   // Clear all non-drupal_static() static caches.
-  // @todo Rebuild the kernel/container.
-  Drupal::entityManager()->clearCachedDefinitions();
+  Drupal::service('plugin.manager.entity')->clearCachedDefinitions();
+
+  // Wipe the PHP Storage caches.
+  PhpStorageFactory::get('service_container')->deleteAll();
+  PhpStorageFactory::get('twig')->deleteAll();
 
   // Rebuild module and theme data.
-  system_rebuild_module_data();
+  $module_data = system_rebuild_module_data();
   system_rebuild_theme_data();
 
+  // Rebuild and reboot a new kernel.
+  // A simple DrupalKernel reboot is not sufficient, since the list of
+  // enabled modules might have been adjusted above due to changed code.
+  $files = array();
+  foreach ($module_data as $module => $data) {
+    if (isset($data->uri) && $data->status) {
+      $files[$module] = $data->uri;
+    }
+  }
+  Drupal::service('kernel')->updateModules($module_handler->getModuleList(), $files);
+  // New container, new module handler.
+  $module_handler = Drupal::moduleHandler();
+
   // Ensure that all modules that are currently supposed to be enabled are
   // actually loaded.
-  drupal_container()->get('module_handler')->loadAll();
+  $module_handler->loadAll();
 
   // Update the list of bootstrap modules.
   // Allows developers to get new bootstrap hooks implementations registered
@@ -6114,18 +6129,14 @@ function drupal_flush_all_caches() {
   drupal_get_schema(NULL, TRUE);
 
   // Rebuild all information based on new module data.
-  module_invoke_all('rebuild');
+  $module_handler->invokeAll('rebuild');
 
   // Rebuild the menu router based on all rebuilt data.
   // Important: This rebuild must happen last, so the menu router is guaranteed
   // to be based on up to date information.
-  drupal_container()->get('router.builder')->rebuild();
+  Drupal::service('router.builder')->rebuild();
   menu_router_rebuild();
 
-  // Wipe the PHP Storage caches.
-  PhpStorageFactory::get('service_container')->deleteAll();
-  PhpStorageFactory::get('twig')->deleteAll();
-
   // Re-initialize the maintenance theme, if the current request attempted to
   // use it. Unlike regular usages of this function, the installer and update
   // scripts need to flush all caches during GET requests/page building.
diff --git a/core/lib/Drupal/Core/DrupalKernel.php b/core/lib/Drupal/Core/DrupalKernel.php
index baa78b6..1c06890 100644
--- a/core/lib/Drupal/Core/DrupalKernel.php
+++ b/core/lib/Drupal/Core/DrupalKernel.php
@@ -431,7 +431,19 @@ protected function buildContainer() {
     foreach ($this->bundles as $bundle) {
       $bundle->build($container);
     }
-    $container->setParameter('persistIds', array_keys($container->findTaggedServiceIds('persist')));
+
+    // Identify all services whose instances should be persisted when rebuilding
+    // the container during the lifetime of the kernel (e.g., during a kernel
+    // reboot). Include synthetic services, because by definition, they cannot
+    // be automatically reinstantiated. Also include services tagged to persist.
+    $persist_ids = array();
+    foreach ($container->getDefinitions() as $id => $definition) {
+      if ($definition->isSynthetic() || $definition->getTag('persist')) {
+        $persist_ids[] = $id;
+      }
+    }
+    $container->setParameter('persistIds', $persist_ids);
+
     $container->compile();
     return $container;
   }
diff --git a/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php b/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
index fb6a882..ae04b1e 100644
--- a/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
+++ b/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
@@ -905,6 +905,7 @@ protected function writeSettings($settings) {
   protected function resetAll() {
     // Clear all database and static caches and rebuild data structures.
     drupal_flush_all_caches();
+    $this->container = \Drupal::getContainer();
 
     // Reload global $conf array and permissions.
     $this->refreshVariables();
diff --git a/core/rebuild.php b/core/rebuild.php
new file mode 100644
index 0000000..3d6213b
--- /dev/null
+++ b/core/rebuild.php
@@ -0,0 +1,33 @@
+<?php
+
+/**
+ * @file
+ * Rebuilds all Drupal caches even when Drupal itself does not work.
+ *
+ * Needs a token query argument which can be calculated using the
+ * scrits/rebuild_token_calculator.sh script.
+ */
+
+// Change the directory to the Drupal root.
+use Drupal\Component\PhpStorage\PhpStorageFactory;
+use Drupal\Core\Cache\CacheFactory;
+
+chdir('..');
+
+require_once dirname(__DIR__) . '/core/includes/bootstrap.inc';
+drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
+if (isset($_GET['token']) && isset($_GET['timestamp']) && REQUEST_TIME - $_GET['timestamp'] < 300 && $_GET['token'] === drupal_hmac_base64($_GET['timestamp'], $GLOBALS['drupal_hash_salt'])) {
+  // drupal_bootstrap(DRUPAL_BOOTSTRAP_KERNEL) will build a new kernel.
+  PhpStorageFactory::get('service_container')->deleteAll();
+  PhpStorageFactory::get('twig')->deleteAll();
+  $GLOBALS['conf']['system.performance']['cache.page.use_internal'] = FALSE;
+  // Bootstrap up to where caches exist and clear them.
+  drupal_bootstrap(DRUPAL_BOOTSTRAP_PAGE_CACHE);
+  foreach (CacheFactory::getBackends() as $bin => $backend) {
+    cache($bin)->deleteAll();
+  }
+  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
+  drupal_flush_all_caches();
+  drupal_set_message('Rebuild complete.');
+}
+header('Location: ' . $GLOBALS['base_url']);
diff --git a/core/scripts/rebuild_token_calculator.sh b/core/scripts/rebuild_token_calculator.sh
new file mode 100755
index 0000000..92a02aa
--- /dev/null
+++ b/core/scripts/rebuild_token_calculator.sh
@@ -0,0 +1,17 @@
+#!/usr/bin/env php
+<?php
+
+/**
+ * @file
+ * Command line token calculator for rebuild.php.
+ */
+
+if (PHP_SAPI !== 'cli') {
+  exit;
+}
+$core = dirname(__DIR__);
+include dirname($core) . '/sites/default/settings.php';
+include $core . '/includes/bootstrap.inc';
+$timestamp = time();
+$token = drupal_hmac_base64($timestamp, $drupal_hash_salt);
+print "timestamp=$timestamp&token=$token\n";
diff --git a/index.php b/index.php
index f0949e0..4934bd2 100644
--- a/index.php
+++ b/index.php
@@ -9,4 +9,10 @@
  */
 
 require_once __DIR__ . '/core/includes/bootstrap.inc';
-drupal_handle_request();
+try {
+  drupal_handle_request();
+}
+catch (Exception $e) {
+  print 'If you have just changed code (for example deployed a new module or moved an existing one) read http://drupal.org/documentation/rebuild';
+  throw $e;
+}
