build_packages: Don't transitively upgrade critical SDK packages

Toolchain packages should only be upgraded on the build host by
`cros_setup_toolchains`, but are currently being upgraded as a result
of being in the transitive depgraph of build targets due to BDEPEND.
gcc and glibc are the most problematic packages being rebuilt to this
and are both not installed via Portage to board targets, so are safe to
hardcode in this manner while we find a better solution to the overall
problem.

BUG=chromium:1050752
TEST=`build_packages`

Change-Id: I2b0bfc4d2b18b7ac5fb24d776fee079463c8f08e
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/crosutils/+/1967866
Commit-Queue: Chris McDonald <cjmcdonald@chromium.org>
Tested-by: Chris McDonald <cjmcdonald@chromium.org>
Reviewed-by: Mike Frysinger <vapier@chromium.org>
diff --git a/build_packages b/build_packages
index da9f018..baf9e0c 100755
--- a/build_packages
+++ b/build_packages
@@ -353,6 +353,23 @@
   )
 fi
 
+# A list of critical system packages that should never be incidentally
+# reinstalled as a side effect of build_packages. All packages in this list
+# are special cased to prefer matching installed versions, overriding the
+# typical logic of upgrading to the newest available version.
+#
+# This list can't include any package that gets installed to a board!
+# Packages such as LLVM or binutils must not be in this list as the normal
+# rebuild logic must still apply to them for board targets.
+#
+# TODO(crbug/1050752): Remove this list and the corresponding arguments
+# to `emerge` below once we figure out how to exclude toolchain packages from
+# being upgraded transitively via BDEPEND relations.
+CRITICAL_SDK_PACKAGES=(
+  "sys-libs/glibc"
+  "sys-devel/gcc"
+)
+
 info "Merging board packages now"
 (
   # Support goma on bots. This has to run in subshell, otherwise EXIT trap
@@ -364,7 +381,9 @@
     trap "'${goma_ctl}' stop" EXIT
   fi
 
-  sudo -E "${EMERGE_CMD[@]}" "${EMERGE_FLAGS[@]}" "${PACKAGES[@]}"
+  sudo -E "${EMERGE_CMD[@]}" "${EMERGE_FLAGS[@]}" "${PACKAGES[@]}" \
+    --useoldpkg-atoms="${CRITICAL_SDK_PACKAGES[*]}" \
+    --rebuild-exclude="${CRITICAL_SDK_PACKAGES[*]}"
 )
 
 echo "Builds complete"