Fix definition of ESYSROOT to use SYSROOT's prefix

For a given location, we were basing ESYSROOT on the prefix of that
location instead of the prefix used by the SYSROOT location. For
example, if BROOT=/foo, ROOT=/bar, EPREFIX=/baz, EROOT=/bar/baz, and
SYSROOT=/ then ESYSROOT should be /foo, not /baz.

Cherry-picked from https://github.com/chewi/portage/tree/sysroot-fixes
Upstream status: Not sent

BUG=chromium:929503
TEST=build_packages

Change-Id: Ie8bfc4f3ad947f5d004e2665ef4e8e0bf43f382b
Reviewed-on: https://chromium-review.googlesource.com/1686968
Tested-by: Chris McDonald <cjmcdonald@chromium.org>
Commit-Ready: Chris McDonald <cjmcdonald@chromium.org>
Legacy-Commit-Queue: Commit Bot <commit-bot@chromium.org>
Reviewed-by: Mike Frysinger <vapier@chromium.org>
diff --git a/lib/portage/package/ebuild/_config/LocationsManager.py b/lib/portage/package/ebuild/_config/LocationsManager.py
index fe90c08..c184f18 100644
--- a/lib/portage/package/ebuild/_config/LocationsManager.py
+++ b/lib/portage/package/ebuild/_config/LocationsManager.py
@@ -71,8 +71,6 @@
 		else:
 			self.sysroot = normalize_path(os.path.abspath(self.sysroot or os.sep)).rstrip(os.sep) + os.sep
 
-		self.esysroot = self.sysroot.rstrip(os.sep) + self.eprefix + os.sep
-
 		# TODO: Set this via the constructor using
 		# PORTAGE_OVERRIDE_EPREFIX.
 		self.broot = portage.const.EPREFIX
@@ -320,6 +318,16 @@
 
 		self.eroot = self.target_root.rstrip(os.sep) + self.eprefix + os.sep
 
+		# In a cross-prefix scenario where SYSROOT=/ and
+		# ROOT=/, assume we want ESYSROOT to point to the
+		# target prefix.
+		if self.sysroot == self.target_root:
+			self.esysroot = self.sysroot.rstrip(os.sep) + self.eprefix + os.sep
+		elif self.sysroot == "/":
+			self.esysroot = self.broot + os.sep
+		else:
+			self.esysroot = self.sysroot
+
 		self.global_config_path = GLOBAL_CONFIG_PATH
 		if portage.const.EPREFIX:
 			self.global_config_path = os.path.join(portage.const.EPREFIX,
diff --git a/lib/portage/package/ebuild/config.py b/lib/portage/package/ebuild/config.py
index f04b7c0..27ca7c1 100644
--- a/lib/portage/package/ebuild/config.py
+++ b/lib/portage/package/ebuild/config.py
@@ -348,7 +348,6 @@
 			eprefix = locations_manager.eprefix
 			config_root = locations_manager.config_root
 			sysroot = locations_manager.sysroot
-			esysroot = locations_manager.esysroot
 			broot = locations_manager.broot
 			abs_user_config = locations_manager.abs_user_config
 			make_conf_paths = [
@@ -381,6 +380,7 @@
 			locations_manager.set_root_override(make_conf.get("ROOT"))
 			target_root = locations_manager.target_root
 			eroot = locations_manager.eroot
+			esysroot = locations_manager.esysroot
 			self.global_config_path = locations_manager.global_config_path
 
 			# The expand_map is used for variable substitution