• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/bin/bash
2
3# Builds mysteriously fail if stdout is non-blocking.
4fixup_ptys() {
5  python3 << 'EOF'
6import fcntl, os, sys
7fd = sys.stdout.fileno()
8flags = fcntl.fcntl(fd, fcntl.F_GETFL)
9flags &= ~(fcntl.FASYNC | os.O_NONBLOCK | os.O_APPEND)
10fcntl.fcntl(fd, fcntl.F_SETFL, flags)
11EOF
12}
13
14# Common kernel options
15OPTIONS=" ANDROID DEBUG_SPINLOCK DEBUG_ATOMIC_SLEEP DEBUG_MUTEXES DEBUG_RT_MUTEXES"
16OPTIONS="$OPTIONS WARN_ALL_UNSEEDED_RANDOM IKCONFIG IKCONFIG_PROC"
17OPTIONS="$OPTIONS DEVTMPFS DEVTMPFS_MOUNT FHANDLE"
18OPTIONS="$OPTIONS IPV6 IPV6_ROUTER_PREF IPV6_MULTIPLE_TABLES IPV6_ROUTE_INFO"
19OPTIONS="$OPTIONS TUN SYN_COOKIES IP_ADVANCED_ROUTER IP_MULTIPLE_TABLES"
20OPTIONS="$OPTIONS NETFILTER NETFILTER_ADVANCED NETFILTER_XTABLES"
21OPTIONS="$OPTIONS NETFILTER_XT_MARK NETFILTER_XT_TARGET_MARK"
22OPTIONS="$OPTIONS IP_NF_IPTABLES IP_NF_MANGLE IP_NF_FILTER"
23OPTIONS="$OPTIONS IP6_NF_IPTABLES IP6_NF_MANGLE IP6_NF_FILTER INET6_IPCOMP"
24OPTIONS="$OPTIONS IPV6_OPTIMISTIC_DAD"
25OPTIONS="$OPTIONS IPV6_ROUTE_INFO IPV6_ROUTER_PREF"
26OPTIONS="$OPTIONS NETFILTER_XT_TARGET_IDLETIMER"
27OPTIONS="$OPTIONS NETFILTER_XT_TARGET_NFLOG"
28OPTIONS="$OPTIONS NETFILTER_XT_MATCH_POLICY"
29OPTIONS="$OPTIONS NETFILTER_XT_MATCH_QUOTA"
30OPTIONS="$OPTIONS NETFILTER_XT_MATCH_QUOTA2"
31OPTIONS="$OPTIONS NETFILTER_XT_MATCH_QUOTA2_LOG"
32OPTIONS="$OPTIONS NETFILTER_XT_MATCH_SOCKET"
33OPTIONS="$OPTIONS NETFILTER_XT_MATCH_QTAGUID"
34OPTIONS="$OPTIONS INET_DIAG INET_UDP_DIAG INET_DIAG_DESTROY"
35OPTIONS="$OPTIONS IP_SCTP"
36OPTIONS="$OPTIONS IP_NF_TARGET_REJECT IP_NF_TARGET_REJECT_SKERR"
37OPTIONS="$OPTIONS IP6_NF_TARGET_REJECT IP6_NF_TARGET_REJECT_SKERR"
38OPTIONS="$OPTIONS NET_KEY XFRM_USER XFRM_STATISTICS CRYPTO_CBC"
39OPTIONS="$OPTIONS CRYPTO_CTR CRYPTO_HMAC CRYPTO_AES CRYPTO_SHA1"
40OPTIONS="$OPTIONS CRYPTO_XCBC CRYPTO_CHACHA20POLY1305"
41OPTIONS="$OPTIONS CRYPTO_USER INET_ESP INET_XFRM_MODE_TRANSPORT"
42OPTIONS="$OPTIONS INET_XFRM_MODE_TUNNEL INET6_ESP"
43OPTIONS="$OPTIONS INET6_XFRM_MODE_TRANSPORT INET6_XFRM_MODE_TUNNEL"
44OPTIONS="$OPTIONS CRYPTO_SHA256 CRYPTO_SHA512 CRYPTO_AES_X86_64 CRYPTO_NULL"
45OPTIONS="$OPTIONS CRYPTO_GCM CRYPTO_ECHAINIV NET_IPVTI"
46OPTIONS="$OPTIONS DUMMY"
47
48# Kernel version specific options
49OPTIONS="$OPTIONS XFRM_INTERFACE"                # Various device kernels
50OPTIONS="$OPTIONS XFRM_MIGRATE"                  # Added in 5.10
51OPTIONS="$OPTIONS CGROUP_BPF"                    # Added in android-4.9
52OPTIONS="$OPTIONS NF_SOCKET_IPV4 NF_SOCKET_IPV6" # Added in 4.9
53OPTIONS="$OPTIONS INET_SCTP_DIAG"                # Added in 4.7
54OPTIONS="$OPTIONS SOCK_CGROUP_DATA"              # Added in 4.5
55OPTIONS="$OPTIONS CRYPTO_ECHAINIV"               # Added in 4.1
56OPTIONS="$OPTIONS BPF_SYSCALL"                   # Added in 3.18
57OPTIONS="$OPTIONS IPV6_VTI"                      # Added in 3.13
58OPTIONS="$OPTIONS IPV6_PRIVACY"                  # Removed in 3.12
59OPTIONS="$OPTIONS NETFILTER_TPROXY"              # Removed in 3.11
60
61# UML specific options
62OPTIONS="$OPTIONS BLK_DEV_UBD HOSTFS"
63
64# QEMU specific options
65OPTIONS="$OPTIONS PCI VIRTIO VIRTIO_PCI VIRTIO_BLK NET_9P NET_9P_VIRTIO 9P_FS"
66OPTIONS="$OPTIONS CRYPTO_DEV_VIRTIO SERIAL_8250 SERIAL_8250_PCI"
67
68# Obsolete options present at some time in Android kernels
69OPTIONS="$OPTIONS IP_NF_TARGET_REJECT_SKERR IP6_NF_TARGET_REJECT_SKERR"
70
71# These two break the flo kernel due to differences in -Werror on recent GCC.
72DISABLE_OPTIONS=" REISERFS_FS ANDROID_PMEM"
73
74# How many TAP interfaces to create to provide the VM with real network access
75# via the host. This requires privileges (e.g., root access) on the host.
76#
77# This is not needed to run the tests, but can be used, for example, to allow
78# the VM to update system packages, or to write tests that need access to a
79# real network. The VM does not set up networking by default, but it contains a
80# DHCP client and has the ability to use IPv6 autoconfiguration. This script
81# does not perform any host-level setup beyond configuring tap interfaces;
82# configuring IPv4 NAT and/or IPv6 router advertisements or ND proxying must
83# be done separately.
84NUMTAPINTERFACES=0
85
86# The root filesystem disk image we'll use.
87ROOTFS=${ROOTFS:-net_test.rootfs.20150203}
88COMPRESSED_ROOTFS=$ROOTFS.xz
89URL=https://dl.google.com/dl/android/$COMPRESSED_ROOTFS
90
91# Parse arguments and figure out which test to run.
92ARCH=${ARCH:-um}
93J=${J:-$(nproc)}
94MAKE="make"
95OUT_DIR=$(readlink -f ${OUT_DIR:-.})
96KERNEL_DIR=$(readlink -f ${KERNEL_DIR:-.})
97if [ "$OUT_DIR" != "$KERNEL_DIR" ]; then
98    MAKE="$MAKE O=$OUT_DIR"
99fi
100SCRIPT_DIR=$(dirname $(readlink -f $0))
101CONFIG_SCRIPT=${KERNEL_DIR}/scripts/config
102CONFIG_FILE=${OUT_DIR}/.config
103consolemode=
104netconfig=
105testmode=
106cmdline=
107nowrite=1
108nobuild=0
109norun=0
110
111if [[ -z "${DEFCONFIG:-}" ]]; then
112  case "${ARCH}" in
113    um)
114      export DEFCONFIG=defconfig
115      ;;
116    arm64)
117      if [[ -e arch/arm64/configs/gki_defconfig ]]; then
118        export DEFCONFIG=gki_defconfig
119      elif [[ -e arch/arm64/configs/cuttlefish_defconfig ]]; then
120        export DEFCONFIG=cuttlefish_defconfig
121      fi
122      ;;
123    x86_64)
124      if [[ -e arch/x86/configs/gki_defconfig ]]; then
125        export DEFCONFIG=gki_defconfig
126      elif [[ -e arch/x86/configs/x86_64_cuttlefish_defconfig ]]; then
127        export DEFCONFIG=x86_64_cuttlefish_defconfig
128      fi
129  esac
130fi
131
132if tty >/dev/null; then
133  verbose=
134else
135  verbose=1
136fi
137
138test=all_tests.sh
139while [[ -n "$1" ]]; do
140  if [[ "$1" == "--builder" || "$1" == "-b" ]]; then
141    consolemode="con=null,fd:1"
142    testmode=builder
143    shift
144  elif [[ "$1" == "--readwrite" || "$1" == "--rw" ]]; then
145    nowrite=0
146    shift
147  elif [[ "$1" == "--readonly" ||  "$1" == "--ro" ]]; then
148    nowrite=1
149    shift
150  elif [[ "$1" == "--nobuild" ]]; then
151    nobuild=1
152    shift
153  elif [[ "$1" == "--norun" ]]; then
154    norun=1
155    shift
156  elif [[ "$1" == "--verbose" ]]; then
157    verbose=1
158    shift
159  elif [[ "$1" == "--noverbose" ]]; then
160    verbose=
161    shift
162  else
163    test=$1
164    break  # Arguments after the test file are passed to the test itself.
165  fi
166done
167
168# Check that test file exists and is readable
169test_file=$SCRIPT_DIR/$test
170if [[ ! -e $test_file ]]; then
171  echo "test file '${test_file}' does not exist"
172  exit 1
173fi
174
175if [[ ! -x $test_file ]]; then
176  echo "test file '${test_file}' is not executable"
177  exit 1
178fi
179
180# Collect trailing arguments to pass to $test
181test_args=${@:2}
182
183function isRunningTest() {
184  ! (( norun ))
185}
186
187function isBuildOnly() {
188  (( norun )) && ! (( nobuild ))
189}
190
191if ! isRunningTest && ! isBuildOnly; then
192  echo "Usage:" >&2
193  echo "  $0 [--builder] [--readonly|--ro|--readwrite|--rw] [--nobuild] [--verbose] [<test>]" >&2
194  echo "      - if [<test>] is not specified, run all_tests.sh" >&2
195  echo "  $0 --norun" >&2
196  exit 1
197fi
198
199cd $OUT_DIR
200echo Running tests from: `pwd`
201
202set -e
203
204# Check if we need to uncompress the disk image.
205# We use xz because it compresses better: to 42M vs 72M (gzip) / 62M (bzip2).
206cd $SCRIPT_DIR
207if [ ! -f $ROOTFS ]; then
208  echo "Deleting $COMPRESSED_ROOTFS" >&2
209  rm -f $COMPRESSED_ROOTFS
210  echo "Downloading $URL" >&2
211  wget -nv $URL
212  echo "Uncompressing $COMPRESSED_ROOTFS" >&2
213  unxz $COMPRESSED_ROOTFS
214fi
215if ! [[ "${ROOTFS}" =~ ^/ ]]; then
216  ROOTFS="${SCRIPT_DIR}/${ROOTFS}"
217fi
218echo "Using $ROOTFS"
219cd -
220
221# If network access was requested, create NUMTAPINTERFACES tap interfaces on
222# the host, and prepare UML command line params to use them. The interfaces are
223# called <user>TAP0, <user>TAP1, on the host, and eth0, eth1, ..., in the VM.
224if (( $NUMTAPINTERFACES > 0 )); then
225  user=${USER:0:10}
226  tapinterfaces=
227  for id in $(seq 0 $(( NUMTAPINTERFACES - 1 )) ); do
228    tap=${user}TAP$id
229    tapinterfaces="$tapinterfaces $tap"
230    mac=$(printf fe:fd:00:00:00:%02x $id)
231    if [ "$ARCH" == "um" ]; then
232      netconfig="$netconfig eth$id=tuntap,$tap,$mac"
233    else
234      netconfig="$netconfig -netdev tap,id=hostnet$id,ifname=$tap,script=no,downscript=no"
235      netconfig="$netconfig -device virtio-net-pci,netdev=hostnet$id,id=net$id,mac=$mac"
236    fi
237  done
238
239  for tap in $tapinterfaces; do
240    if ! ip link list $tap > /dev/null; then
241      echo "Creating tap interface $tap" >&2
242      sudo tunctl -u $USER -t $tap
243      sudo ip link set $tap up
244    fi
245  done
246fi
247
248if [[ -n "${KERNEL_BINARY:-}" ]]; then
249  nobuild=1
250else
251  # Set default KERNEL_BINARY location if it was not provided.
252  if [ "$ARCH" == "um" ]; then
253    KERNEL_BINARY=./linux
254  elif [ "$ARCH" == "i386" -o "$ARCH" == "x86_64" -o "$ARCH" == "x86" ]; then
255    KERNEL_BINARY=./arch/x86/boot/bzImage
256  elif [ "$ARCH" == "arm64" ]; then
257    KERNEL_BINARY=./arch/arm64/boot/Image.gz
258  fi
259fi
260
261if ((nobuild == 0)); then
262  make_flags=
263  if [ "$ARCH" == "um" ]; then
264    # Exporting ARCH=um SUBARCH=x86_64 doesn't seem to work, as it
265    # "sometimes" (?) results in a 32-bit kernel.
266    make_flags="$make_flags ARCH=$ARCH SUBARCH=${SUBARCH:-x86_64} CROSS_COMPILE= "
267  fi
268  if [[ -n "${CC:-}" ]]; then
269    # The CC flag is *not* inherited from the environment, so it must be
270    # passed in on the command line.
271    make_flags="$make_flags CC=$CC"
272  fi
273
274  # If there's no kernel config at all, create one or UML won't work.
275  [ -f $CONFIG_FILE ] || (cd $KERNEL_DIR && $MAKE $make_flags $DEFCONFIG)
276
277  # Enable the kernel config options listed in $OPTIONS.
278  $CONFIG_SCRIPT --file $CONFIG_FILE ${OPTIONS// / -e }
279
280  # Disable the kernel config options listed in $DISABLE_OPTIONS.
281  $CONFIG_SCRIPT --file $CONFIG_FILE ${DISABLE_OPTIONS// / -d }
282
283  echo "Running: $MAKE $make_flags olddefconfig"
284  $MAKE $make_flags olddefconfig
285
286  # Compile the kernel.
287  if [ "$ARCH" == "um" ]; then
288    echo "Running: $MAKE -j$J $make_flags linux"
289    $MAKE -j$J $make_flags linux
290  else
291    echo "Running: $MAKE -j$J $make_flags"
292    $MAKE -j$J $make_flags
293  fi
294fi
295
296if (( norun == 1 )); then
297  exit 0
298fi
299
300if (( nowrite == 1 )); then
301  cmdline="ro"
302fi
303
304if (( verbose == 1 )); then
305  cmdline="$cmdline verbose=1"
306fi
307
308cmdline="$cmdline panic=1 init=/sbin/net_test.sh"
309cmdline="$cmdline net_test_args=\"$test_args\" net_test_mode=$testmode"
310
311# Experience shows that we need at least 128 bits of entropy for the
312# kernel's crng init to complete (before it fully initializes stuff behaves
313# *weirdly* and there's plenty of kernel warnings and some tests even fail),
314# hence net_test.sh needs at least 32 hex chars (which is the amount of hex
315# in a single random UUID) provided to it on the kernel cmdline.
316#
317# Just to be safe, we'll pass in 384 bits, and we'll do this as a random
318# 64 character base64 seed (because this is shorter than base16).
319# We do this by getting *three* random UUIDs and concatenating their hex
320# digits into an *even* length hex encoded string, which we then convert
321# into base64.
322entropy="$(cat /proc/sys/kernel/random{/,/,/}uuid | tr -d '\n-')"
323entropy="$(xxd -r -p <<< "${entropy}" | base64 -w 0)"
324cmdline="${cmdline} random.trust_cpu=on entropy=${entropy}"
325
326if [ "$ARCH" == "um" ]; then
327  # Get the absolute path to the test file that's being run.
328  cmdline="$cmdline net_test=/host$SCRIPT_DIR/$test"
329
330  # We'd use UML's /proc/exitcode feature to communicate errors on test failure,
331  # if not for UML having a tendency to crash during shutdown,
332  # so instead use an extra serial line we'll redirect to an open fd...
333  cmdline="$cmdline exitcode=/dev/ttyS3"
334
335  # Map the --readonly flag to UML block device names
336  if ((nowrite == 0)); then
337    blockdevice=ubda
338  else
339    blockdevice=ubdar
340  fi
341
342  # Create a temp file for 'serial line 3' for return code.
343  SSL3="$(mktemp)"
344
345  exitcode=0
346  $KERNEL_BINARY >&2 3>"${SSL3}" umid=net_test mem=512M \
347    $blockdevice=$ROOTFS $netconfig $consolemode ssl3=null,fd:3 $cmdline \
348  || exitcode=$?
349
350  # Return to beginning of line (via carriage return) after the above newline moved us down.
351  echo -en '\r'
352  # re-enable: 'postprocess output' and 'translate newline to carriage return-newline'
353  stty opost onlcr || :
354
355  if [[ "${exitcode}" == 134 && -s "${SSL3}" && "$(tr -d '\r' < "${SSL3}")" == 0 ]]; then
356    # Sometimes the tests all pass, but UML crashes during the shutdown process itself.
357    # As such we can't actually rely on the /proc/exitcode returned value.
358    echo "Warning: UML appears to have crashed after successfully executing the tests." 1>&2
359  elif [[ "${exitcode}" != 0 ]]; then
360    echo "Warning: UML exited with ${exitcode} instead of zero." 1>&2
361  fi
362
363  if [[ -s "${SSL3}" ]]; then
364    exitcode="$(tr -d '\r' < "${SSL3}")"
365    echo "Info: retrieved exit code ${exitcode}." 1>&2
366  fi
367
368  rm -f "${SSL3}"
369  unset SSL3
370
371  # UML is kind of crazy in how guest syscalls work.  It requires host kernel
372  # to not be in vsyscall=none mode.
373  if [[ "${exitcode}" != '0' ]]; then
374    {
375      # Hopefully one of these exists
376      cat /proc/config || :
377      zcat /proc/config.gz || :
378      cat "/boot/config-$(uname -r)" || :
379      zcat "/boot/config-$(uname -r).gz" || :
380    } 2>/dev/null \
381    | egrep -q '^CONFIG_LEGACY_VSYSCALL_NONE=y' \
382    && ! egrep -q '(^| )vsyscall=(native|emulate|xonly)( |$)' /proc/cmdline \
383    && {
384      echo -e "\r"
385      echo -e "-----=====-----\r"
386      echo -e "If above you saw a 'net_test.sh[1]: segfault at ...' followed by\r"
387      echo -e "'Kernel panic - not syncing: Attempted to kill init!' then please\r"
388      echo -e "set 'vsyscall=emulate' on *host* kernel command line.\r"
389      echo -e "On Linux 5.2+ you can instead use the slightly safer 'vsyscall=xonly'.\r"
390      echo -e "(for example via GRUB_CMDLINE_LINUX in /etc/default/grub)\r"
391      echo -e "-----=====-----\r"
392    }
393  fi
394else
395  # We boot into the filesystem image directly in all cases
396  cmdline="$cmdline root=/dev/vda"
397
398  # The path is stripped by the 9p export; we don't need SCRIPT_DIR
399  cmdline="$cmdline net_test=/host/$test"
400
401  # Map the --readonly flag to a QEMU block device flag
402  if ((nowrite > 0)); then
403    blockdevice=",readonly"
404  else
405    blockdevice=
406  fi
407  blockdevice="-drive file=$ROOTFS,format=raw,if=none,id=drive-virtio-disk0$blockdevice"
408  blockdevice="$blockdevice -device virtio-blk-pci,drive=drive-virtio-disk0"
409
410  # Pass through our current console/screen size to inner shell session
411  read rows cols < <(stty size 2>/dev/null)
412  [[ -z "${rows}" ]] || cmdline="${cmdline} console_rows=${rows}"
413  [[ -z "${cols}" ]] || cmdline="${cmdline} console_cols=${cols}"
414  unset rows cols
415
416  # QEMU has no way to modify its exitcode; simulate it with a serial port.
417  #
418  # Choose to do it this way over writing a file to /host, because QEMU will
419  # initialize the 'exitcode' file for us, it avoids unnecessary writes to the
420  # host filesystem (which is normally not written to) and it allows us to
421  # communicate an exit code back in cases we do not have /host mounted.
422  #
423  if [ "$ARCH" == "i386" -o "$ARCH" == "x86_64" -o "$ARCH" == "x86" ]; then
424    # Assume we have hardware-accelerated virtualization support for amd64
425    qemu="qemu-system-x86_64 -machine pc,accel=kvm -cpu host"
426
427    # We know 'ttyS0' will be our serial port on x86 from the hard-coded
428    # '-serial mon:stdio' flag below
429    cmdline="$cmdline console=ttyS0"
430
431    # The assignment of 'ttyS1' here is magical; we know ttyS0 was used up
432    # by '-serial mon:stdio', and so this second serial port will be 'ttyS1'
433    cmdline="$cmdline exitcode=/dev/ttyS1"
434  elif [ "$ARCH" == "arm64" ]; then
435    # This uses a software model CPU, based on cortex-a57
436    qemu="qemu-system-aarch64 -machine virt -cpu cortex-a57"
437
438    # We know 'ttyAMA0' will be our serial port on arm64 from the hard-coded
439    # '-serial mon:stdio' flag below
440    cmdline="$cmdline console=ttyAMA0"
441
442    # The kernel will print messages via a virtual ARM serial port (ttyAMA0),
443    # but for command line consistency with x86, we put the exitcode serial
444    # port on the PCI bus, and it will be the only one.
445    cmdline="$cmdline exitcode=/dev/ttyS0"
446  fi
447
448  $qemu >&2 -name net_test -m 512 \
449    -kernel $KERNEL_BINARY \
450    -no-user-config -nodefaults -no-reboot \
451    -display none -nographic -serial mon:stdio -parallel none \
452    -smp 4,sockets=4,cores=1,threads=1 \
453    -device virtio-rng-pci \
454    -chardev file,id=exitcode,path=exitcode \
455    -device pci-serial,chardev=exitcode \
456    -fsdev local,security_model=mapped-xattr,id=fsdev0,fmode=0644,dmode=0755,path=$SCRIPT_DIR \
457    -device virtio-9p-pci,id=fs0,fsdev=fsdev0,mount_tag=host \
458    $blockdevice $netconfig -append "$cmdline"
459  [[ -s exitcode ]] && exitcode=`cat exitcode | tr -d '\r'` || exitcode=1
460  rm -f exitcode
461fi
462
463# UML reliably screws up the ptys, QEMU probably can as well...
464fixup_ptys
465stty sane || :
466tput smam || :
467
468echo "Returning exit code ${exitcode}." 1>&2
469exit "${exitcode}"
470