diff --git a/includes/menu.inc b/includes/menu.inc
index f236325109e18022a711c9f42579625ace35c0c7..5582c452e87cc358333f56cb98365663c1e5595f 100644
--- a/includes/menu.inc
+++ b/includes/menu.inc
@@ -431,6 +431,11 @@ function menu_get_item($path = NULL, $router_item = NULL) {
     $router_items[$path] = $router_item;
   }
   if (!isset($router_items[$path])) {
+    // Rebuild if we know it's needed, or if the menu masks are missing which
+    // occurs rarely, likely due to a race condition of multiple rebuilds.
+    if (variable_get('menu_rebuild_needed', FALSE) || !variable_get('menu_masks', array())) {
+      menu_rebuild();
+    }
     $original_map = arg(NULL, $path);
 
     // Since there is no limit to the length of $path, use a hash to keep it
@@ -490,11 +495,6 @@ function menu_execute_active_handler($path = NULL, $deliver = TRUE) {
 
   // Only continue if the site status is not set.
   if ($page_callback_result == MENU_SITE_ONLINE) {
-    // Rebuild if we know it's needed, or if the menu masks are missing which
-    // occurs rarely, likely due to a race condition of multiple rebuilds.
-    if (variable_get('menu_rebuild_needed', FALSE) || !variable_get('menu_masks', array())) {
-      menu_rebuild();
-    }
     if ($router_item = menu_get_item($path)) {
       if ($router_item['access']) {
         if ($router_item['include_file']) {
diff --git a/modules/simpletest/tests/menu.test b/modules/simpletest/tests/menu.test
index 5642fcee0e07edf0f24ddcde7d6c23589939b413..c0a79d4c233be96b63d01964f17984682ee199b7 100644
--- a/modules/simpletest/tests/menu.test
+++ b/modules/simpletest/tests/menu.test
@@ -394,6 +394,14 @@ class MenuRouterTestCase extends DrupalWebTestCase {
     $this->assertEqual($link['plid'], $plid, t('%path plid @link_plid is equal to @plid.', array('%path' => $link['router_path'], '@link_plid' => $link['plid'], '@plid' => $plid)));
   }
 
+  /**
+   * Test menu_get_item() with empty ancestors.
+   */
+  function testMenuGetItemNoAncestors() {
+    variable_set('menu_masks', array());
+    $this->drupalGet('');
+  }
+
   /**
    * Test menu_set_item().
    */