install hooks: add a sanity check for bad multilib usage

We don't want lib64 being used on 32-bit systems like x86 or arm.
If it leaks in, we should abort early on rather than much later like
during test time.  So add a sanity check for these to reject lib64.

BUG=chromium:876634
TEST=precq passes
TEST=modifying an ebuild to install into /usr/lib64 and building on arm fails

Change-Id: I10d22c304080dde90626bff874d44425b3db0e7c
Reviewed-on: https://chromium-review.googlesource.com/1188852
Reviewed-by: Benson Leung <bleung@chromium.org>
Reviewed-by: C Shapiro <shapiroc@google.com>
Reviewed-by: Don Garrett <dgarrett@chromium.org>
Tested-by: Mike Frysinger <vapier@chromium.org>
diff --git a/hooks/install/multilib-sanity.sh b/hooks/install/multilib-sanity.sh
new file mode 100755
index 0000000..c8edf47
--- /dev/null
+++ b/hooks/install/multilib-sanity.sh
@@ -0,0 +1,50 @@
+#!/bin/bash
+# Copyright 2018 The Chromium OS Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+# Try and catch bad multilib usage at install time.  This check isn't meant
+# to be 100% comprehensive, but should catch most bad behavior to be useful.
+# We are basically hardcoding policy that already exists in Gentoo profiles,
+# but we don't currently care about supporting full flexibility as no CrOS
+# device should be doing weird stuff.
+#
+# We're a bit limited when it comes to lib64 users like x86_64 & aarch64.
+# On those systems, /lib/ and /usr/lib/ are OK for arch-independent files,
+# most commonly things like /usr/lib/debug/.  So it's trickier to detect
+# bad usage of that path vs good usage.
+#
+# Fortunately, most bad usage impacts 32-bit userlands because the sdk itself
+# tends to be 64-bit (lib64), so this hook should still be effective.
+
+# See whether the specified path exists in any form.
+# We'll update the |paths| array variable in the parent scope.
+bad_path_exists() {
+  local subdir="$1"
+  local basedir path ret=0
+  for basedir in / /usr /usr/local; do
+    path="${D}${basedir%/}/${subdir}"
+    if [[ -L "${path}" || -d "${path}" ]]; then
+      paths+=( "${path}" )
+      ret=1
+    fi
+  done
+  return ${ret}
+}
+
+# Main entry point for this hook.
+check_multilib() {
+  local paths=()
+  case ${ARCH} in
+  arm|x86)
+    if ! bad_path_exists "lib64"; then
+      eerror "Bad lib64 usage detected:"
+      find "${paths[@]}" -exec ls -ldh {} +
+      eerror "This arch (${ARCH}) should never use 'lib64'."
+      die "This package is installing into bad paths."
+    fi
+    ;;
+  esac
+}
+
+check_multilib