OSDN Git Service

Merge tag 'android-7.1.1_r9' of https://android.googlesource.com/platform/build into...
[android-x86/build.git] / envsetup.sh
1 function hmm() {
2 cat <<EOF
3 Invoke ". build/envsetup.sh" from your shell to add the following functions to your environment:
4 - lunch:     lunch <product_name>-<build_variant>
5 - tapas:     tapas [<App1> <App2> ...] [arm|x86|mips|armv5|arm64|x86_64|mips64] [eng|userdebug|user]
6 - croot:     Changes directory to the top of the tree.
7 - m:         Makes from the top of the tree.
8 - mm:        Builds all of the modules in the current directory, but not their dependencies.
9 - mmm:       Builds all of the modules in the supplied directories, but not their dependencies.
10              To limit the modules being built use the syntax: mmm dir/:target1,target2.
11 - mma:       Builds all of the modules in the current directory, and their dependencies.
12 - mmma:      Builds all of the modules in the supplied directories, and their dependencies.
13 - provision: Flash device with all required partitions. Options will be passed on to fastboot.
14 - cgrep:     Greps on all local C/C++ files.
15 - ggrep:     Greps on all local Gradle files.
16 - jgrep:     Greps on all local Java files.
17 - resgrep:   Greps on all local res/*.xml files.
18 - mangrep:   Greps on all local AndroidManifest.xml files.
19 - mgrep:     Greps on all local Makefiles files.
20 - sepgrep:   Greps on all local sepolicy files.
21 - sgrep:     Greps on all local source files.
22 - godir:     Go to the directory containing a file.
23
24 EOF
25
26     __print_cm_functions_help
27
28 cat <<EOF
29
30 Environment options:
31 - SANITIZE_HOST: Set to 'true' to use ASAN for all host modules. Note that
32                  ASAN_OPTIONS=detect_leaks=0 will be set by default until the
33                  build is leak-check clean.
34
35 Look at the source to view more functions. The complete list is:
36 EOF
37     T=$(gettop)
38     for i in `cat $T/build/envsetup.sh $T/vendor/cm/build/envsetup.sh | sed -n "/^[[:blank:]]*function /s/function \([a-z_]*\).*/\1/p" | sort | uniq`; do
39       echo "$i"
40     done | column
41 }
42
43 # Get all the build variables needed by this script in a single call to the build system.
44 function build_build_var_cache()
45 {
46     T=$(gettop)
47     # Grep out the variable names from the script.
48     cached_vars=`cat $T/build/envsetup.sh $T/vendor/cm/build/envsetup.sh | tr '()' '  ' | awk '{for(i=1;i<=NF;i++) if($i~/get_build_var/) print $(i+1)}' | sort -u | tr '\n' ' '`
49     cached_abs_vars=`cat $T/build/envsetup.sh $T/vendor/cm/build/envsetup.sh | tr '()' '  ' | awk '{for(i=1;i<=NF;i++) if($i~/get_abs_build_var/) print $(i+1)}' | sort -u | tr '\n' ' '`
50     # Call the build system to dump the "<val>=<value>" pairs as a shell script.
51     build_dicts_script=`\cd $T; export CALLED_FROM_SETUP=true; export BUILD_SYSTEM=build/core; \
52                         command make --no-print-directory -f build/core/config.mk \
53                         dump-many-vars \
54                         DUMP_MANY_VARS="$cached_vars" \
55                         DUMP_MANY_ABS_VARS="$cached_abs_vars" \
56                         DUMP_VAR_PREFIX="var_cache_" \
57                         DUMP_ABS_VAR_PREFIX="abs_var_cache_"`
58     local ret=$?
59     if [ $ret -ne 0 ]
60     then
61         unset build_dicts_script
62         return $ret
63     fi
64     # Excute the script to store the "<val>=<value>" pairs as shell variables.
65     eval "$build_dicts_script"
66     ret=$?
67     unset build_dicts_script
68     if [ $ret -ne 0 ]
69     then
70         return $ret
71     fi
72     BUILD_VAR_CACHE_READY="true"
73 }
74
75 # Delete the build var cache, so that we can still call into the build system
76 # to get build variables not listed in this script.
77 function destroy_build_var_cache()
78 {
79     unset BUILD_VAR_CACHE_READY
80     for v in $(echo $cached_vars | tr " " "\n"); do
81       unset var_cache_$v
82     done
83     unset cached_vars
84     for v in $(echo $cached_abs_vars | tr " " "\n"); do
85       unset abs_var_cache_$v
86     done
87     unset cached_abs_vars
88 }
89
90 # Get the value of a build variable as an absolute path.
91 function get_abs_build_var()
92 {
93     if [ "$BUILD_VAR_CACHE_READY" = "true" ]
94     then
95         eval echo \"\${abs_var_cache_$1}\"
96     return
97     fi
98
99     T=$(gettop)
100     if [ ! "$T" ]; then
101         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
102         return
103     fi
104     (\cd $T; export CALLED_FROM_SETUP=true; export BUILD_SYSTEM=build/core; \
105       command make --no-print-directory -f build/core/config.mk dumpvar-abs-$1)
106 }
107
108 # Get the exact value of a build variable.
109 function get_build_var()
110 {
111     if [ "$BUILD_VAR_CACHE_READY" = "true" ]
112     then
113         eval echo \"\${var_cache_$1}\"
114     return
115     fi
116
117     T=$(gettop)
118     if [ ! "$T" ]; then
119         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
120         return
121     fi
122     (\cd $T; export CALLED_FROM_SETUP=true; export BUILD_SYSTEM=build/core; \
123       command make --no-print-directory -f build/core/config.mk dumpvar-$1)
124 }
125
126 # check to see if the supplied product is one we can build
127 function check_product()
128 {
129     T=$(gettop)
130     if [ ! "$T" ]; then
131         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
132         return
133     fi
134
135     if (echo -n $1 | grep -q -e "^lineage_") ; then
136         CM_BUILD=$(echo -n $1 | sed -e 's/^lineage_//g')
137         export BUILD_NUMBER=$( (date +%s%N ; echo $CM_BUILD; hostname) | openssl sha1 | sed -e 's/.*=//g; s/ //g' | cut -c1-10 )
138     elif (echo -n $1 | grep -q -e "^cm_") ; then
139         # Fall back to cm_<product>
140         CM_BUILD=$(echo -n $1 | sed -e 's/^cm_//g')
141         export BUILD_NUMBER=$( (date +%s%N ; echo $CM_BUILD; hostname) | openssl sha1 | sed -e 's/.*=//g; s/ //g' | cut -c1-10 )
142     else
143         CM_BUILD=
144     fi
145     export CM_BUILD
146
147         TARGET_PRODUCT=$1 \
148         TARGET_BUILD_VARIANT= \
149         TARGET_BUILD_TYPE= \
150         TARGET_BUILD_APPS= \
151         get_build_var TARGET_DEVICE > /dev/null
152     # hide successful answers, but allow the errors to show
153 }
154
155 VARIANT_CHOICES=(user userdebug eng)
156
157 # check to see if the supplied variant is valid
158 function check_variant()
159 {
160     for v in ${VARIANT_CHOICES[@]}
161     do
162         if [ "$v" = "$1" ]
163         then
164             return 0
165         fi
166     done
167     return 1
168 }
169
170 function setpaths()
171 {
172     T=$(gettop)
173     if [ ! "$T" ]; then
174         echo "Couldn't locate the top of the tree.  Try setting TOP."
175         return
176     fi
177
178     ##################################################################
179     #                                                                #
180     #              Read me before you modify this code               #
181     #                                                                #
182     #   This function sets ANDROID_BUILD_PATHS to what it is adding  #
183     #   to PATH, and the next time it is run, it removes that from   #
184     #   PATH.  This is required so lunch can be run more than once   #
185     #   and still have working paths.                                #
186     #                                                                #
187     ##################################################################
188
189     # Note: on windows/cygwin, ANDROID_BUILD_PATHS will contain spaces
190     # due to "C:\Program Files" being in the path.
191
192     # out with the old
193     if [ -n "$ANDROID_BUILD_PATHS" ] ; then
194         export PATH=${PATH/$ANDROID_BUILD_PATHS/}
195     fi
196     if [ -n "$ANDROID_PRE_BUILD_PATHS" ] ; then
197         export PATH=${PATH/$ANDROID_PRE_BUILD_PATHS/}
198         # strip leading ':', if any
199         export PATH=${PATH/:%/}
200     fi
201
202     # and in with the new
203     prebuiltdir=$(getprebuilt)
204     gccprebuiltdir=$(get_abs_build_var ANDROID_GCC_PREBUILTS)
205
206     # defined in core/config.mk
207     targetgccversion=$(get_build_var TARGET_GCC_VERSION)
208     targetgccversion2=$(get_build_var 2ND_TARGET_GCC_VERSION)
209     export TARGET_GCC_VERSION=$targetgccversion
210
211     # The gcc toolchain does not exists for windows/cygwin. In this case, do not reference it.
212     export ANDROID_TOOLCHAIN=
213     export ANDROID_TOOLCHAIN_2ND_ARCH=
214     local ARCH=$(get_build_var TARGET_ARCH)
215     case $ARCH in
216         x86) toolchaindir=x86/x86_64-linux-android-$targetgccversion/bin
217             ;;
218         x86_64) toolchaindir=x86/x86_64-linux-android-$targetgccversion/bin
219             ;;
220         arm) toolchaindir=arm/arm-linux-androideabi-$targetgccversion/bin
221             ;;
222         arm64) toolchaindir=aarch64/aarch64-linux-android-$targetgccversion/bin;
223                toolchaindir2=arm/arm-linux-androideabi-$targetgccversion2/bin
224             ;;
225         mips|mips64) toolchaindir=mips/mips64el-linux-android-$targetgccversion/bin
226             ;;
227         *)
228             echo "Can't find toolchain for unknown architecture: $ARCH"
229             toolchaindir=xxxxxxxxx
230             ;;
231     esac
232     if [ -d "$gccprebuiltdir/$toolchaindir" ]; then
233         export ANDROID_TOOLCHAIN=$gccprebuiltdir/$toolchaindir
234     fi
235
236     if [ -d "$gccprebuiltdir/$toolchaindir2" ]; then
237         export ANDROID_TOOLCHAIN_2ND_ARCH=$gccprebuiltdir/$toolchaindir2
238     fi
239
240     export ANDROID_DEV_SCRIPTS=$T/development/scripts:$T/prebuilts/devtools/tools:$T/external/selinux/prebuilts/bin
241     export ANDROID_BUILD_PATHS=$(get_build_var ANDROID_BUILD_PATHS):$ANDROID_TOOLCHAIN:$ANDROID_TOOLCHAIN_2ND_ARCH:$ANDROID_DEV_SCRIPTS:
242
243     # If prebuilts/android-emulator/<system>/ exists, prepend it to our PATH
244     # to ensure that the corresponding 'emulator' binaries are used.
245     case $(uname -s) in
246         Darwin)
247             ANDROID_EMULATOR_PREBUILTS=$T/prebuilts/android-emulator/darwin-x86_64
248             ;;
249         Linux)
250             ANDROID_EMULATOR_PREBUILTS=$T/prebuilts/android-emulator/linux-x86_64
251             ;;
252         *)
253             ANDROID_EMULATOR_PREBUILTS=
254             ;;
255     esac
256     if [ -n "$ANDROID_EMULATOR_PREBUILTS" -a -d "$ANDROID_EMULATOR_PREBUILTS" ]; then
257         ANDROID_BUILD_PATHS=$ANDROID_BUILD_PATHS$ANDROID_EMULATOR_PREBUILTS:
258         export ANDROID_EMULATOR_PREBUILTS
259     fi
260
261     export PATH=$ANDROID_BUILD_PATHS$PATH
262     export PYTHONPATH=$T/development/python-packages:$PYTHONPATH
263
264     unset ANDROID_JAVA_TOOLCHAIN
265     unset ANDROID_PRE_BUILD_PATHS
266     if [ -n "$JAVA_HOME" ]; then
267         export ANDROID_JAVA_TOOLCHAIN=$JAVA_HOME/bin
268         export ANDROID_PRE_BUILD_PATHS=$ANDROID_JAVA_TOOLCHAIN:
269         export PATH=$ANDROID_PRE_BUILD_PATHS$PATH
270     fi
271
272     unset ANDROID_PRODUCT_OUT
273     export ANDROID_PRODUCT_OUT=$(get_abs_build_var PRODUCT_OUT)
274     export OUT=$ANDROID_PRODUCT_OUT
275
276     unset ANDROID_HOST_OUT
277     export ANDROID_HOST_OUT=$(get_abs_build_var HOST_OUT)
278
279     if [ -n "$ANDROID_CCACHE_DIR" ]; then
280         export CCACHE_DIR=$ANDROID_CCACHE_DIR
281     fi
282
283     # needed for building linux on MacOS
284     # TODO: fix the path
285     #export HOST_EXTRACFLAGS="-I "$T/system/kernel_headers/host_include
286 }
287
288 function printconfig()
289 {
290     T=$(gettop)
291     if [ ! "$T" ]; then
292         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
293         return
294     fi
295     get_build_var report_config
296 }
297
298 function set_stuff_for_environment()
299 {
300     settitle
301     set_java_home
302     setpaths
303     set_sequence_number
304
305     # With this environment variable new GCC can apply colors to warnings/errors
306     export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
307     export ASAN_OPTIONS=detect_leaks=0
308 }
309
310 function set_sequence_number()
311 {
312     export BUILD_ENV_SEQUENCE_NUMBER=10
313 }
314
315 function settitle()
316 {
317     if [ "$STAY_OFF_MY_LAWN" = "" ]; then
318         local arch=$(gettargetarch)
319         local product=$TARGET_PRODUCT
320         local variant=$TARGET_BUILD_VARIANT
321         local apps=$TARGET_BUILD_APPS
322         if [ -z "$PROMPT_COMMAND"  ]; then
323             # No prompts
324             PROMPT_COMMAND="echo -ne \"\033]0;${USER}@${HOSTNAME}: ${PWD}\007\""
325         elif [ -z "$(echo $PROMPT_COMMAND | grep '033]0;')" ]; then
326             # Prompts exist, but no hardstatus
327             PROMPT_COMMAND="echo -ne \"\033]0;${USER}@${HOSTNAME}: ${PWD}\007\";${PROMPT_COMMAND}"
328         fi
329         if [ ! -z "$ANDROID_PROMPT_PREFIX" ]; then
330             PROMPT_COMMAND="$(echo $PROMPT_COMMAND | sed -e 's/$ANDROID_PROMPT_PREFIX //g')"
331         fi
332
333         if [ -z "$apps" ]; then
334             ANDROID_PROMPT_PREFIX="[${arch}-${product}-${variant}]"
335         else
336             ANDROID_PROMPT_PREFIX="[$arch $apps $variant]"
337         fi
338         export ANDROID_PROMPT_PREFIX
339
340         # Inject build data into hardstatus
341         export PROMPT_COMMAND="$(echo $PROMPT_COMMAND | sed -e 's/\\033]0;\(.*\)\\007/\\033]0;$ANDROID_PROMPT_PREFIX \1\\007/g')"
342     fi
343 }
344
345 function check_bash_version()
346 {
347     # Keep us from trying to run in something that isn't bash.
348     if [ -z "${BASH_VERSION}" ]; then
349         return 1
350     fi
351
352     # Keep us from trying to run in bash that's too old.
353     if [ "${BASH_VERSINFO[0]}" -lt 4 ] ; then
354         return 2
355     fi
356
357     return 0
358 }
359
360 function choosetype()
361 {
362     echo "Build type choices are:"
363     echo "     1. release"
364     echo "     2. debug"
365     echo
366
367     local DEFAULT_NUM DEFAULT_VALUE
368     DEFAULT_NUM=1
369     DEFAULT_VALUE=release
370
371     export TARGET_BUILD_TYPE=
372     local ANSWER
373     while [ -z $TARGET_BUILD_TYPE ]
374     do
375         echo -n "Which would you like? ["$DEFAULT_NUM"] "
376         if [ -z "$1" ] ; then
377             read ANSWER
378         else
379             echo $1
380             ANSWER=$1
381         fi
382         case $ANSWER in
383         "")
384             export TARGET_BUILD_TYPE=$DEFAULT_VALUE
385             ;;
386         1)
387             export TARGET_BUILD_TYPE=release
388             ;;
389         release)
390             export TARGET_BUILD_TYPE=release
391             ;;
392         2)
393             export TARGET_BUILD_TYPE=debug
394             ;;
395         debug)
396             export TARGET_BUILD_TYPE=debug
397             ;;
398         *)
399             echo
400             echo "I didn't understand your response.  Please try again."
401             echo
402             ;;
403         esac
404         if [ -n "$1" ] ; then
405             break
406         fi
407     done
408
409     build_build_var_cache
410     set_stuff_for_environment
411     destroy_build_var_cache
412 }
413
414 #
415 # This function isn't really right:  It chooses a TARGET_PRODUCT
416 # based on the list of boards.  Usually, that gets you something
417 # that kinda works with a generic product, but really, you should
418 # pick a product by name.
419 #
420 function chooseproduct()
421 {
422     if [ "x$TARGET_PRODUCT" != x ] ; then
423         default_value=$TARGET_PRODUCT
424     else
425         default_value=aosp_arm
426     fi
427
428     export TARGET_BUILD_APPS=
429     export TARGET_PRODUCT=
430     local ANSWER
431     while [ -z "$TARGET_PRODUCT" ]
432     do
433         echo -n "Which product would you like? [$default_value] "
434         if [ -z "$1" ] ; then
435             read ANSWER
436         else
437             echo $1
438             ANSWER=$1
439         fi
440
441         if [ -z "$ANSWER" ] ; then
442             export TARGET_PRODUCT=$default_value
443         else
444             if check_product $ANSWER
445             then
446                 export TARGET_PRODUCT=$ANSWER
447             else
448                 echo "** Not a valid product: $ANSWER"
449             fi
450         fi
451         if [ -n "$1" ] ; then
452             break
453         fi
454     done
455
456     build_build_var_cache
457     set_stuff_for_environment
458     destroy_build_var_cache
459 }
460
461 function choosevariant()
462 {
463     echo "Variant choices are:"
464     local index=1
465     local v
466     for v in ${VARIANT_CHOICES[@]}
467     do
468         # The product name is the name of the directory containing
469         # the makefile we found, above.
470         echo "     $index. $v"
471         index=$(($index+1))
472     done
473
474     local default_value=eng
475     local ANSWER
476
477     export TARGET_BUILD_VARIANT=
478     while [ -z "$TARGET_BUILD_VARIANT" ]
479     do
480         echo -n "Which would you like? [$default_value] "
481         if [ -z "$1" ] ; then
482             read ANSWER
483         else
484             echo $1
485             ANSWER=$1
486         fi
487
488         if [ -z "$ANSWER" ] ; then
489             export TARGET_BUILD_VARIANT=$default_value
490         elif (echo -n $ANSWER | grep -q -e "^[0-9][0-9]*$") ; then
491             if [ "$ANSWER" -le "${#VARIANT_CHOICES[@]}" ] ; then
492                 export TARGET_BUILD_VARIANT=${VARIANT_CHOICES[$(($ANSWER-1))]}
493             fi
494         else
495             if check_variant $ANSWER
496             then
497                 export TARGET_BUILD_VARIANT=$ANSWER
498             else
499                 echo "** Not a valid variant: $ANSWER"
500             fi
501         fi
502         if [ -n "$1" ] ; then
503             break
504         fi
505     done
506 }
507
508 function choosecombo()
509 {
510     choosetype $1
511
512     echo
513     echo
514     chooseproduct $2
515
516     echo
517     echo
518     choosevariant $3
519
520     echo
521     build_build_var_cache
522     set_stuff_for_environment
523     printconfig
524     destroy_build_var_cache
525 }
526
527 # Clear this variable.  It will be built up again when the vendorsetup.sh
528 # files are included at the end of this file.
529 unset LUNCH_MENU_CHOICES
530 function add_lunch_combo()
531 {
532     local new_combo=$1
533     local c
534     for c in ${LUNCH_MENU_CHOICES[@]} ; do
535         if [ "$new_combo" = "$c" ] ; then
536             return
537         fi
538     done
539     LUNCH_MENU_CHOICES=(${LUNCH_MENU_CHOICES[@]} $new_combo)
540 }
541
542 # add the default one here
543 add_lunch_combo aosp_arm-eng
544 add_lunch_combo aosp_arm64-eng
545 add_lunch_combo aosp_mips-eng
546 add_lunch_combo aosp_mips64-eng
547 add_lunch_combo aosp_x86-eng
548 add_lunch_combo aosp_x86_64-eng
549
550 function print_lunch_menu()
551 {
552     local uname=$(uname)
553     echo
554     echo "You're building on" $uname
555     echo
556     if [ "z${CM_DEVICES_ONLY}" != "z" ]; then
557        echo "Breakfast menu... pick a combo:"
558     else
559        echo "Lunch menu... pick a combo:"
560     fi
561
562     local i=1
563     local choice
564     for choice in ${LUNCH_MENU_CHOICES[@]}
565     do
566         echo " $i. $choice "
567         i=$(($i+1))
568     done | column
569
570     if [ "z${CM_DEVICES_ONLY}" != "z" ]; then
571        echo "... and don't forget the bacon!"
572     fi
573
574     echo
575 }
576
577 function lunch()
578 {
579     local answer
580     LUNCH_MENU_CHOICES=($(for l in ${LUNCH_MENU_CHOICES[@]}; do echo "$l"; done | sort))
581
582     if [ "$1" ] ; then
583         answer=$1
584     else
585         print_lunch_menu
586         echo -n "Which would you like? [aosp_arm-eng] "
587         read answer
588     fi
589
590     local selection=
591
592     if [ -z "$answer" ]
593     then
594         selection=aosp_arm-eng
595     elif (echo -n $answer | grep -q -e "^[0-9][0-9]*$")
596     then
597         if [ $answer -le ${#LUNCH_MENU_CHOICES[@]} ]
598         then
599             selection=${LUNCH_MENU_CHOICES[$(($answer-1))]}
600         fi
601     elif (echo -n $answer | grep -q -e "^[^\-][^\-]*-[^\-][^\-]*$")
602     then
603         selection=$answer
604     fi
605
606     if [ -z "$selection" ]
607     then
608         echo
609         echo "Invalid lunch combo: $answer"
610         return 1
611     fi
612
613     export TARGET_BUILD_APPS=
614
615     local variant=$(echo -n $selection | sed -e "s/^[^\-]*-//")
616     check_variant $variant
617     if [ $? -ne 0 ]
618     then
619         echo
620         echo "** Invalid variant: '$variant'"
621         echo "** Must be one of ${VARIANT_CHOICES[@]}"
622         variant=
623     fi
624
625     local product=$(echo -n $selection | sed -e "s/-.*$//")
626     check_product $product
627     if [ $? -ne 0 ]
628     then
629         # if we can't find a product, try to grab it off the CM github
630         T=$(gettop)
631         pushd $T > /dev/null
632         vendor/cm/build/tools/roomservice.py $product
633         cd - > /dev/null
634         check_product $product
635     else
636         T=$(gettop)
637         pushd $T > /dev/null
638         vendor/cm/build/tools/roomservice.py $product true
639         cd - > /dev/null
640     fi
641     TARGET_PRODUCT=$product \
642     TARGET_BUILD_VARIANT=$variant \
643     build_build_var_cache
644
645     if [ $? -ne 0 ]
646     then
647         echo
648         echo "** Don't have a product spec for: '$product'"
649         echo "** Do you have the right repo manifest?"
650         product=
651     fi
652
653     if [ -z "$product" -o -z "$variant" ]
654     then
655         echo
656         return 1
657     fi
658
659     export TARGET_PRODUCT=$product
660     export TARGET_BUILD_VARIANT=$variant
661     export TARGET_BUILD_TYPE=release
662
663     echo
664
665     fixup_common_out_dir
666
667     set_stuff_for_environment
668     printconfig
669     destroy_build_var_cache
670 }
671
672 # Tab completion for lunch.
673 function _lunch()
674 {
675     local cur prev opts
676     COMPREPLY=()
677     cur="${COMP_WORDS[COMP_CWORD]}"
678     prev="${COMP_WORDS[COMP_CWORD-1]}"
679
680     COMPREPLY=( $(compgen -W "${LUNCH_MENU_CHOICES[*]}" -- ${cur}) )
681     return 0
682 }
683 complete -F _lunch lunch 2>/dev/null
684
685 # Configures the build to build unbundled apps.
686 # Run tapas with one or more app names (from LOCAL_PACKAGE_NAME)
687 function tapas()
688 {
689     local arch="$(echo $* | xargs -n 1 echo | \grep -E '^(arm|x86|mips|armv5|arm64|x86_64|mips64)$' | xargs)"
690     local variant="$(echo $* | xargs -n 1 echo | \grep -E '^(user|userdebug|eng)$' | xargs)"
691     local density="$(echo $* | xargs -n 1 echo | \grep -E '^(ldpi|mdpi|tvdpi|hdpi|xhdpi|xxhdpi|xxxhdpi|alldpi)$' | xargs)"
692     local apps="$(echo $* | xargs -n 1 echo | \grep -E -v '^(user|userdebug|eng|arm|x86|mips|armv5|arm64|x86_64|mips64|ldpi|mdpi|tvdpi|hdpi|xhdpi|xxhdpi|xxxhdpi|alldpi)$' | xargs)"
693
694     if [ $(echo $arch | wc -w) -gt 1 ]; then
695         echo "tapas: Error: Multiple build archs supplied: $arch"
696         return
697     fi
698     if [ $(echo $variant | wc -w) -gt 1 ]; then
699         echo "tapas: Error: Multiple build variants supplied: $variant"
700         return
701     fi
702     if [ $(echo $density | wc -w) -gt 1 ]; then
703         echo "tapas: Error: Multiple densities supplied: $density"
704         return
705     fi
706
707     local product=aosp_arm
708     case $arch in
709       x86)    product=aosp_x86;;
710       mips)   product=aosp_mips;;
711       armv5)  product=generic_armv5;;
712       arm64)  product=aosp_arm64;;
713       x86_64) product=aosp_x86_64;;
714       mips64)  product=aosp_mips64;;
715     esac
716     if [ -z "$variant" ]; then
717         variant=eng
718     fi
719     if [ -z "$apps" ]; then
720         apps=all
721     fi
722     if [ -z "$density" ]; then
723         density=alldpi
724     fi
725
726     export TARGET_PRODUCT=$product
727     export TARGET_BUILD_VARIANT=$variant
728     export TARGET_BUILD_DENSITY=$density
729     export TARGET_BUILD_TYPE=release
730     export TARGET_BUILD_APPS=$apps
731
732     build_build_var_cache
733     set_stuff_for_environment
734     printconfig
735     destroy_build_var_cache
736 }
737
738 function gettop
739 {
740     local TOPFILE=build/core/envsetup.mk
741     if [ -n "$TOP" -a -f "$TOP/$TOPFILE" ] ; then
742         # The following circumlocution ensures we remove symlinks from TOP.
743         (cd $TOP; PWD= /bin/pwd)
744     else
745         if [ -f $TOPFILE ] ; then
746             # The following circumlocution (repeated below as well) ensures
747             # that we record the true directory name and not one that is
748             # faked up with symlink names.
749             PWD= /bin/pwd
750         else
751             local HERE=$PWD
752             T=
753             while [ \( ! \( -f $TOPFILE \) \) -a \( $PWD != "/" \) ]; do
754                 \cd ..
755                 T=`PWD= /bin/pwd -P`
756             done
757             \cd $HERE
758             if [ -f "$T/$TOPFILE" ]; then
759                 echo $T
760             fi
761         fi
762     fi
763 }
764
765 # Return driver for "make", if any (eg. static analyzer)
766 function getdriver()
767 {
768     local T="$1"
769     test "$WITH_STATIC_ANALYZER" = "0" && unset WITH_STATIC_ANALYZER
770     if [ -n "$WITH_STATIC_ANALYZER" ]; then
771         echo "\
772 $T/prebuilts/misc/linux-x86/analyzer/tools/scan-build/scan-build \
773 --use-analyzer $T/prebuilts/misc/linux-x86/analyzer/bin/analyzer \
774 --status-bugs \
775 --top=$T"
776     fi
777 }
778
779 function m()
780 {
781     local T=$(gettop)
782     local DRV=$(getdriver $T)
783     if [ "$T" ]; then
784         $DRV make -C $T -f build/core/main.mk $@
785     else
786         echo "Couldn't locate the top of the tree.  Try setting TOP."
787         return 1
788     fi
789 }
790
791 function findmakefile()
792 {
793     TOPFILE=build/core/envsetup.mk
794     local HERE=$PWD
795     T=
796     while [ \( ! \( -f $TOPFILE \) \) -a \( $PWD != "/" \) ]; do
797         T=`PWD= /bin/pwd`
798         if [ -f "$T/Android.mk" ]; then
799             echo $T/Android.mk
800             \cd $HERE
801             return
802         fi
803         \cd ..
804     done
805     \cd $HERE
806 }
807
808 function mm()
809 {
810     local T=$(gettop)
811     local DRV=$(getdriver $T)
812     # If we're sitting in the root of the build tree, just do a
813     # normal make.
814     if [ -f build/core/envsetup.mk -a -f Makefile ]; then
815         $DRV make $@
816     else
817         # Find the closest Android.mk file.
818         local M=$(findmakefile)
819         local MODULES=
820         local GET_INSTALL_PATH=
821         # Remove the path to top as the makefilepath needs to be relative
822         local M=`echo $M|sed 's:'$T'/::'`
823         if [ ! "$T" ]; then
824             echo "Couldn't locate the top of the tree.  Try setting TOP."
825             return 1
826         elif [ ! "$M" ]; then
827             echo "Couldn't locate a makefile from the current directory."
828             return 1
829         else
830             for ARG in $@; do
831                 case $ARG in
832                   GET-INSTALL-PATH) GET_INSTALL_PATH=$ARG;;
833                 esac
834             done
835             if [ -n "$GET_INSTALL_PATH" ]; then
836               MODULES=
837               # set all args to 'GET-INSTALL-PATH'
838               set -- GET-INSTALL-PATH
839             else
840               MODULES=all_modules
841             fi
842             ONE_SHOT_MAKEFILE=$M $DRV make -C $T -f build/core/main.mk $MODULES "$@"
843         fi
844     fi
845 }
846
847 function mmm()
848 {
849     local T=$(gettop)
850     local DRV=$(getdriver $T)
851     if [ "$T" ]; then
852         local MAKEFILE=
853         local MODULES=
854         local ARGS=
855         local DIR TO_CHOP
856         local GET_INSTALL_PATH=
857
858         if [ "$(__detect_shell)" = "zsh" ]; then
859             set -lA DASH_ARGS $(echo "$@" | awk -v RS=" " -v ORS=" " '/^-.*$/')
860             set -lA DIRS $(echo "$@" | awk -v RS=" " -v ORS=" " '/^[^-].*$/')
861         else
862             local DASH_ARGS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^-.*$/')
863             local DIRS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^[^-].*$/')
864         fi
865
866         for DIR in $DIRS ; do
867             MODULES=`echo $DIR | sed -n -e 's/.*:\(.*$\)/\1/p' | sed 's/,/ /'`
868             if [ "$MODULES" = "" ]; then
869                 MODULES=all_modules
870             fi
871             DIR=`echo $DIR | sed -e 's/:.*//' -e 's:/$::'`
872             if [ -f $DIR/Android.mk ]; then
873                 local TO_CHOP=`(\cd -P -- $T && pwd -P) | wc -c | tr -d ' '`
874                 local TO_CHOP=`expr $TO_CHOP + 1`
875                 local START=`PWD= /bin/pwd`
876                 local MFILE=`echo $START | cut -c${TO_CHOP}-`
877                 if [ "$MFILE" = "" ] ; then
878                     MFILE=$DIR/Android.mk
879                 else
880                     MFILE=$MFILE/$DIR/Android.mk
881                 fi
882                 MAKEFILE="$MAKEFILE $MFILE"
883             else
884                 case $DIR in
885                   showcommands | snod | dist | *=*) ARGS="$ARGS $DIR";;
886                   GET-INSTALL-PATH) GET_INSTALL_PATH=$DIR;;
887                   *) if [ -d $DIR ]; then
888                          echo "No Android.mk in $DIR.";
889                      else
890                          echo "Couldn't locate the directory $DIR";
891                      fi
892                      return 1;;
893                 esac
894             fi
895         done
896         if [ -n "$GET_INSTALL_PATH" ]; then
897           ARGS=$GET_INSTALL_PATH
898           MODULES=
899         fi
900         ONE_SHOT_MAKEFILE="$MAKEFILE" $DRV make -C $T -f build/core/main.mk $DASH_ARGS $MODULES $ARGS
901     else
902         echo "Couldn't locate the top of the tree.  Try setting TOP."
903         return 1
904     fi
905 }
906
907 function mma()
908 {
909   local T=$(gettop)
910   local DRV=$(getdriver $T)
911   if [ -f build/core/envsetup.mk -a -f Makefile ]; then
912     $DRV make $@
913   else
914     if [ ! "$T" ]; then
915       echo "Couldn't locate the top of the tree.  Try setting TOP."
916       return 1
917     fi
918     local MY_PWD=`PWD= /bin/pwd|sed 's:'$T'/::'`
919     local MODULES_IN_PATHS=MODULES-IN-$MY_PWD
920     # Convert "/" to "-".
921     MODULES_IN_PATHS=${MODULES_IN_PATHS//\//-}
922     $DRV make -C $T -f build/core/main.mk $@ $MODULES_IN_PATHS
923   fi
924 }
925
926 function mmma()
927 {
928   local T=$(gettop)
929   local DRV=$(getdriver $T)
930   if [ "$T" ]; then
931     if [ "$(__detect_shell)" = "zsh" ]; then
932         set -lA DASH_ARGS $(echo "$@" | awk -v RS=" " -v ORS=" " '/^-.*$/')
933         set -lA DIRS $(echo "$@" | awk -v RS=" " -v ORS=" " '/^[^-].*$/')
934     else
935         local DASH_ARGS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^-.*$/')
936         local DIRS=$(echo "$@" | awk -v RS=" " -v ORS=" " '/^[^-].*$/')
937     fi
938     local MY_PWD=`PWD= /bin/pwd`
939     if [ "$MY_PWD" = "$T" ]; then
940       MY_PWD=
941     else
942       MY_PWD=`echo $MY_PWD|sed 's:'$T'/::'`
943     fi
944     local DIR=
945     local MODULES_IN_PATHS=
946     local ARGS=
947     for DIR in $DIRS ; do
948       if [ -d $DIR ]; then
949         # Remove the leading ./ and trailing / if any exists.
950         DIR=${DIR#./}
951         DIR=${DIR%/}
952         if [ "$MY_PWD" != "" ]; then
953           DIR=$MY_PWD/$DIR
954         fi
955         MODULES_IN_PATHS="$MODULES_IN_PATHS MODULES-IN-$DIR"
956       else
957         case $DIR in
958           showcommands | snod | dist | *=*) ARGS="$ARGS $DIR";;
959           *) echo "Couldn't find directory $DIR"; return 1;;
960         esac
961       fi
962     done
963     # Convert "/" to "-".
964     MODULES_IN_PATHS=${MODULES_IN_PATHS//\//-}
965     $DRV make -C $T -f build/core/main.mk $DASH_ARGS $ARGS $MODULES_IN_PATHS
966   else
967     echo "Couldn't locate the top of the tree.  Try setting TOP."
968     return 1
969   fi
970 }
971
972 function croot()
973 {
974     T=$(gettop)
975     if [ "$T" ]; then
976         \cd $(gettop)
977     else
978         echo "Couldn't locate the top of the tree.  Try setting TOP."
979     fi
980 }
981
982 function cproj()
983 {
984     TOPFILE=build/core/envsetup.mk
985     local HERE=$PWD
986     T=
987     while [ \( ! \( -f $TOPFILE \) \) -a \( $PWD != "/" \) ]; do
988         T=$PWD
989         if [ -f "$T/Android.mk" ]; then
990             \cd $T
991             return
992         fi
993         \cd ..
994     done
995     \cd $HERE
996     echo "can't find Android.mk"
997 }
998
999 # simplified version of ps; output in the form
1000 # <pid> <procname>
1001 function qpid() {
1002     local prepend=''
1003     local append=''
1004     if [ "$1" = "--exact" ]; then
1005         prepend=' '
1006         append='$'
1007         shift
1008     elif [ "$1" = "--help" -o "$1" = "-h" ]; then
1009         echo "usage: qpid [[--exact] <process name|pid>"
1010         return 255
1011     fi
1012
1013     local EXE="$1"
1014     if [ "$EXE" ] ; then
1015         qpid | \grep "$prepend$EXE$append"
1016     else
1017         adb shell ps \
1018             | tr -d '\r' \
1019             | sed -e 1d -e 's/^[^ ]* *\([0-9]*\).* \([^ ]*\)$/\1 \2/'
1020     fi
1021 }
1022
1023 function pid()
1024 {
1025     local prepend=''
1026     local append=''
1027     if [ "$1" = "--exact" ]; then
1028         prepend=' '
1029         append='$'
1030         shift
1031     fi
1032     local EXE="$1"
1033     if [ "$EXE" ] ; then
1034         local PID=`adb shell ps \
1035             | tr -d '\r' \
1036             | \grep "$prepend$EXE$append" \
1037             | sed -e 's/^[^ ]* *\([0-9]*\).*$/\1/'`
1038         echo "$PID"
1039     else
1040         echo "usage: pid [--exact] <process name>"
1041         return 255
1042     fi
1043 }
1044
1045 # coredump_setup - enable core dumps globally for any process
1046 #                  that has the core-file-size limit set correctly
1047 #
1048 # NOTE: You must call also coredump_enable for a specific process
1049 #       if its core-file-size limit is not set already.
1050 # NOTE: Core dumps are written to ramdisk; they will not survive a reboot!
1051
1052 function coredump_setup()
1053 {
1054     echo "Getting root...";
1055     adb root;
1056     adb wait-for-device;
1057
1058     echo "Remounting root partition read-write...";
1059     adb shell mount -w -o remount -t rootfs rootfs;
1060     sleep 1;
1061     adb wait-for-device;
1062     adb shell mkdir -p /cores;
1063     adb shell mount -t tmpfs tmpfs /cores;
1064     adb shell chmod 0777 /cores;
1065
1066     echo "Granting SELinux permission to dump in /cores...";
1067     adb shell restorecon -R /cores;
1068
1069     echo "Set core pattern.";
1070     adb shell 'echo /cores/core.%p > /proc/sys/kernel/core_pattern';
1071
1072     echo "Done."
1073 }
1074
1075 # coredump_enable - enable core dumps for the specified process
1076 # $1 = PID of process (e.g., $(pid mediaserver))
1077 #
1078 # NOTE: coredump_setup must have been called as well for a core
1079 #       dump to actually be generated.
1080
1081 function coredump_enable()
1082 {
1083     local PID=$1;
1084     if [ -z "$PID" ]; then
1085         printf "Expecting a PID!\n";
1086         return;
1087     fi;
1088     echo "Setting core limit for $PID to infinite...";
1089     adb shell prlimit $PID 4 -1 -1
1090 }
1091
1092 # core - send SIGV and pull the core for process
1093 # $1 = PID of process (e.g., $(pid mediaserver))
1094 #
1095 # NOTE: coredump_setup must be called once per boot for core dumps to be
1096 #       enabled globally.
1097
1098 function core()
1099 {
1100     local PID=$1;
1101
1102     if [ -z "$PID" ]; then
1103         printf "Expecting a PID!\n";
1104         return;
1105     fi;
1106
1107     local CORENAME=core.$PID;
1108     local COREPATH=/cores/$CORENAME;
1109     local SIG=SEGV;
1110
1111     coredump_enable $1;
1112
1113     local done=0;
1114     while [ $(adb shell "[ -d /proc/$PID ] && echo -n yes") ]; do
1115         printf "\tSending SIG%s to %d...\n" $SIG $PID;
1116         adb shell kill -$SIG $PID;
1117         sleep 1;
1118     done;
1119
1120     adb shell "while [ ! -f $COREPATH ] ; do echo waiting for $COREPATH to be generated; sleep 1; done"
1121     echo "Done: core is under $COREPATH on device.";
1122 }
1123
1124 # systemstack - dump the current stack trace of all threads in the system process
1125 # to the usual ANR traces file
1126 function systemstack()
1127 {
1128     stacks system_server
1129 }
1130
1131 function stacks()
1132 {
1133     if [[ $1 =~ ^[0-9]+$ ]] ; then
1134         local PID="$1"
1135     elif [ "$1" ] ; then
1136         local PIDLIST="$(pid $1)"
1137         if [[ $PIDLIST =~ ^[0-9]+$ ]] ; then
1138             local PID="$PIDLIST"
1139         elif [ "$PIDLIST" ] ; then
1140             echo "more than one process: $1"
1141         else
1142             echo "no such process: $1"
1143         fi
1144     else
1145         echo "usage: stacks [pid|process name]"
1146     fi
1147
1148     if [ "$PID" ] ; then
1149         # Determine whether the process is native
1150         if adb shell ls -l /proc/$PID/exe | grep -q /system/bin/app_process ; then
1151             # Dump stacks of Dalvik process
1152             local TRACES=/data/anr/traces.txt
1153             local ORIG=/data/anr/traces.orig
1154             local TMP=/data/anr/traces.tmp
1155
1156             # Keep original traces to avoid clobbering
1157             adb shell mv $TRACES $ORIG
1158
1159             # Make sure we have a usable file
1160             adb shell touch $TRACES
1161             adb shell chmod 666 $TRACES
1162
1163             # Dump stacks and wait for dump to finish
1164             adb shell kill -3 $PID
1165             adb shell notify $TRACES >/dev/null
1166
1167             # Restore original stacks, and show current output
1168             adb shell mv $TRACES $TMP
1169             adb shell mv $ORIG $TRACES
1170             adb shell cat $TMP
1171         else
1172             # Dump stacks of native process
1173             local USE64BIT="$(is64bit $PID)"
1174             adb shell debuggerd$USE64BIT -b $PID
1175         fi
1176     fi
1177 }
1178
1179 # Read the ELF header from /proc/$PID/exe to determine if the process is
1180 # 64-bit.
1181 function is64bit()
1182 {
1183     local PID="$1"
1184     if [ "$PID" ] ; then
1185         if [[ "$(adb shell cat /proc/$PID/exe | xxd -l 1 -s 4 -ps)" -eq "02" ]] ; then
1186             echo "64"
1187         else
1188             echo ""
1189         fi
1190     else
1191         echo ""
1192     fi
1193 }
1194
1195 case `uname -s` in
1196     Darwin)
1197         function sgrep()
1198         {
1199             find -E . -name .repo -prune -o -name .git -prune -o  -type f -iregex '.*\.(c|h|cc|cpp|S|java|xml|sh|mk|aidl|vts)' \
1200                 -exec grep --color -n "$@" {} +
1201         }
1202
1203         ;;
1204     *)
1205         function sgrep()
1206         {
1207             find . -name .repo -prune -o -name .git -prune -o  -type f -iregex '.*\.\(c\|h\|cc\|cpp\|S\|java\|xml\|sh\|mk\|aidl\|vts\)' \
1208                 -exec grep --color -n "$@" {} +
1209         }
1210         ;;
1211 esac
1212
1213 function gettargetarch
1214 {
1215     get_build_var TARGET_ARCH
1216 }
1217
1218 function ggrep()
1219 {
1220     find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f -name "*\.gradle" \
1221         -exec grep --color -n "$@" {} +
1222 }
1223
1224 function jgrep()
1225 {
1226     find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f -name "*\.java" \
1227         -exec grep --color -n "$@" {} +
1228 }
1229
1230 function cgrep()
1231 {
1232     find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f \( -name '*.c' -o -name '*.cc' -o -name '*.cpp' -o -name '*.h' -o -name '*.hpp' \) \
1233         -exec grep --color -n "$@" {} +
1234 }
1235
1236 function resgrep()
1237 {
1238     for dir in `find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -name res -type d`; do
1239         find $dir -type f -name '*\.xml' -exec grep --color -n "$@" {} +
1240     done
1241 }
1242
1243 function mangrep()
1244 {
1245     find . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -type f -name 'AndroidManifest.xml' \
1246         -exec grep --color -n "$@" {} +
1247 }
1248
1249 function sepgrep()
1250 {
1251     find . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -name sepolicy -type d \
1252         -exec grep --color -n -r --exclude-dir=\.git "$@" {} +
1253 }
1254
1255 function rcgrep()
1256 {
1257     find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f -name "*\.rc*" \
1258         -exec grep --color -n "$@" {} +
1259 }
1260
1261 case `uname -s` in
1262     Darwin)
1263         function mgrep()
1264         {
1265             find -E . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -type f -iregex '.*/(Makefile|Makefile\..*|.*\.make|.*\.mak|.*\.mk)' \
1266                 -exec grep --color -n "$@" {} +
1267         }
1268
1269         function treegrep()
1270         {
1271             find -E . -name .repo -prune -o -name .git -prune -o -type f -iregex '.*\.(c|h|cpp|S|java|xml)' \
1272                 -exec grep --color -n -i "$@" {} +
1273         }
1274
1275         ;;
1276     *)
1277         function mgrep()
1278         {
1279             find . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -regextype posix-egrep -iregex '(.*\/Makefile|.*\/Makefile\..*|.*\.make|.*\.mak|.*\.mk)' -type f \
1280                 -exec grep --color -n "$@" {} +
1281         }
1282
1283         function treegrep()
1284         {
1285             find . -name .repo -prune -o -name .git -prune -o -regextype posix-egrep -iregex '.*\.(c|h|cpp|S|java|xml)' -type f \
1286                 -exec grep --color -n -i "$@" {} +
1287         }
1288
1289         ;;
1290 esac
1291
1292 function getprebuilt
1293 {
1294     get_abs_build_var ANDROID_PREBUILTS
1295 }
1296
1297 function tracedmdump()
1298 {
1299     T=$(gettop)
1300     if [ ! "$T" ]; then
1301         echo "Couldn't locate the top of the tree.  Try setting TOP."
1302         return
1303     fi
1304     local prebuiltdir=$(getprebuilt)
1305     local arch=$(gettargetarch)
1306     local KERNEL=$T/prebuilts/qemu-kernel/$arch/vmlinux-qemu
1307
1308     local TRACE=$1
1309     if [ ! "$TRACE" ] ; then
1310         echo "usage:  tracedmdump  tracename"
1311         return
1312     fi
1313
1314     if [ ! -r "$KERNEL" ] ; then
1315         echo "Error: cannot find kernel: '$KERNEL'"
1316         return
1317     fi
1318
1319     local BASETRACE=$(basename $TRACE)
1320     if [ "$BASETRACE" = "$TRACE" ] ; then
1321         TRACE=$ANDROID_PRODUCT_OUT/traces/$TRACE
1322     fi
1323
1324     echo "post-processing traces..."
1325     rm -f $TRACE/qtrace.dexlist
1326     post_trace $TRACE
1327     if [ $? -ne 0 ]; then
1328         echo "***"
1329         echo "*** Error: malformed trace.  Did you remember to exit the emulator?"
1330         echo "***"
1331         return
1332     fi
1333     echo "generating dexlist output..."
1334     /bin/ls $ANDROID_PRODUCT_OUT/system/framework/*.jar $ANDROID_PRODUCT_OUT/system/app/*.apk $ANDROID_PRODUCT_OUT/data/app/*.apk 2>/dev/null | xargs dexlist > $TRACE/qtrace.dexlist
1335     echo "generating dmtrace data..."
1336     q2dm -r $ANDROID_PRODUCT_OUT/symbols $TRACE $KERNEL $TRACE/dmtrace || return
1337     echo "generating html file..."
1338     dmtracedump -h $TRACE/dmtrace >| $TRACE/dmtrace.html || return
1339     echo "done, see $TRACE/dmtrace.html for details"
1340     echo "or run:"
1341     echo "    traceview $TRACE/dmtrace"
1342 }
1343
1344 # communicate with a running device or emulator, set up necessary state,
1345 # and run the hat command.
1346 function runhat()
1347 {
1348     # process standard adb options
1349     local adbTarget=""
1350     if [ "$1" = "-d" -o "$1" = "-e" ]; then
1351         adbTarget=$1
1352         shift 1
1353     elif [ "$1" = "-s" ]; then
1354         adbTarget="$1 $2"
1355         shift 2
1356     fi
1357     local adbOptions=${adbTarget}
1358     #echo adbOptions = ${adbOptions}
1359
1360     # runhat options
1361     local targetPid=$1
1362
1363     if [ "$targetPid" = "" ]; then
1364         echo "Usage: runhat [ -d | -e | -s serial ] target-pid"
1365         return
1366     fi
1367
1368     # confirm hat is available
1369     if [ -z $(which hat) ]; then
1370         echo "hat is not available in this configuration."
1371         return
1372     fi
1373
1374     # issue "am" command to cause the hprof dump
1375     local devFile=/data/local/tmp/hprof-$targetPid
1376     echo "Poking $targetPid and waiting for data..."
1377     echo "Storing data at $devFile"
1378     adb ${adbOptions} shell am dumpheap $targetPid $devFile
1379     echo "Press enter when logcat shows \"hprof: heap dump completed\""
1380     echo -n "> "
1381     read
1382
1383     local localFile=/tmp/$$-hprof
1384
1385     echo "Retrieving file $devFile..."
1386     adb ${adbOptions} pull $devFile $localFile
1387
1388     adb ${adbOptions} shell rm $devFile
1389
1390     echo "Running hat on $localFile"
1391     echo "View the output by pointing your browser at http://localhost:7000/"
1392     echo ""
1393     hat -JXmx512m $localFile
1394 }
1395
1396 function getbugreports()
1397 {
1398     local reports=(`adb shell ls /sdcard/bugreports | tr -d '\r'`)
1399
1400     if [ ! "$reports" ]; then
1401         echo "Could not locate any bugreports."
1402         return
1403     fi
1404
1405     local report
1406     for report in ${reports[@]}
1407     do
1408         echo "/sdcard/bugreports/${report}"
1409         adb pull /sdcard/bugreports/${report} ${report}
1410         gunzip ${report}
1411     done
1412 }
1413
1414 function getsdcardpath()
1415 {
1416     adb ${adbOptions} shell echo -n \$\{EXTERNAL_STORAGE\}
1417 }
1418
1419 function getscreenshotpath()
1420 {
1421     echo "$(getsdcardpath)/Pictures/Screenshots"
1422 }
1423
1424 function getlastscreenshot()
1425 {
1426     local screenshot_path=$(getscreenshotpath)
1427     local screenshot=`adb ${adbOptions} ls ${screenshot_path} | grep Screenshot_[0-9-]*.*\.png | sort -rk 3 | cut -d " " -f 4 | head -n 1`
1428     if [ "$screenshot" = "" ]; then
1429         echo "No screenshots found."
1430         return
1431     fi
1432     echo "${screenshot}"
1433     adb ${adbOptions} pull ${screenshot_path}/${screenshot}
1434 }
1435
1436 function startviewserver()
1437 {
1438     local port=4939
1439     if [ $# -gt 0 ]; then
1440             port=$1
1441     fi
1442     adb shell service call window 1 i32 $port
1443 }
1444
1445 function stopviewserver()
1446 {
1447     adb shell service call window 2
1448 }
1449
1450 function isviewserverstarted()
1451 {
1452     adb shell service call window 3
1453 }
1454
1455 function key_home()
1456 {
1457     adb shell input keyevent 3
1458 }
1459
1460 function key_back()
1461 {
1462     adb shell input keyevent 4
1463 }
1464
1465 function key_menu()
1466 {
1467     adb shell input keyevent 82
1468 }
1469
1470 function smoketest()
1471 {
1472     if [ ! "$ANDROID_PRODUCT_OUT" ]; then
1473         echo "Couldn't locate output files.  Try running 'lunch' first." >&2
1474         return
1475     fi
1476     T=$(gettop)
1477     if [ ! "$T" ]; then
1478         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
1479         return
1480     fi
1481
1482     (\cd "$T" && mmm tests/SmokeTest) &&
1483       adb uninstall com.android.smoketest > /dev/null &&
1484       adb uninstall com.android.smoketest.tests > /dev/null &&
1485       adb install $ANDROID_PRODUCT_OUT/data/app/SmokeTestApp.apk &&
1486       adb install $ANDROID_PRODUCT_OUT/data/app/SmokeTest.apk &&
1487       adb shell am instrument -w com.android.smoketest.tests/android.test.InstrumentationTestRunner
1488 }
1489
1490 # simple shortcut to the runtest command
1491 function runtest()
1492 {
1493     T=$(gettop)
1494     if [ ! "$T" ]; then
1495         echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
1496         return
1497     fi
1498     ("$T"/development/testrunner/runtest.py $@)
1499 }
1500
1501 function godir () {
1502     if [[ -z "$1" ]]; then
1503         echo "Usage: godir <regex>"
1504         return
1505     fi
1506     T=$(gettop)
1507     if [ ! "$OUT_DIR" = "" ]; then
1508         mkdir -p $OUT_DIR
1509         FILELIST=$OUT_DIR/filelist
1510     else
1511         FILELIST=$T/filelist
1512     fi
1513     if [[ ! -f $FILELIST ]]; then
1514         echo -n "Creating index..."
1515         (\cd $T; find . -wholename ./out -prune -o -wholename ./.repo -prune -o -type f > $FILELIST)
1516         echo " Done"
1517         echo ""
1518     fi
1519     local lines
1520     lines=($(\grep "$1" $FILELIST | sed -e 's/\/[^/]*$//' | sort | uniq))
1521     if [[ ${#lines[@]} = 0 ]]; then
1522         echo "Not found"
1523         return
1524     fi
1525     local pathname
1526     local choice
1527     if [[ ${#lines[@]} > 1 ]]; then
1528         while [[ -z "$pathname" ]]; do
1529             local index=1
1530             local line
1531             for line in ${lines[@]}; do
1532                 printf "%6s %s\n" "[$index]" $line
1533                 index=$(($index + 1))
1534             done
1535             echo
1536             echo -n "Select one: "
1537             unset choice
1538             read choice
1539             if [[ $choice -gt ${#lines[@]} || $choice -lt 1 ]]; then
1540                 echo "Invalid choice"
1541                 continue
1542             fi
1543             pathname=${lines[$(($choice-1))]}
1544         done
1545     else
1546         pathname=${lines[0]}
1547     fi
1548     \cd $T/$pathname
1549 }
1550
1551 # Force JAVA_HOME to point to java 1.7/1.8 if it isn't already set.
1552 function set_java_home() {
1553     # Clear the existing JAVA_HOME value if we set it ourselves, so that
1554     # we can reset it later, depending on the version of java the build
1555     # system needs.
1556     #
1557     # If we don't do this, the JAVA_HOME value set by the first call to
1558     # build/envsetup.sh will persist forever.
1559     if [ -n "$ANDROID_SET_JAVA_HOME" ]; then
1560       export JAVA_HOME=""
1561     fi
1562
1563     if [ ! "$JAVA_HOME" ]; then
1564       if [ -n "$LEGACY_USE_JAVA7" ]; then
1565         echo Warning: Support for JDK 7 will be dropped. Switch to JDK 8.
1566         case `uname -s` in
1567             Darwin)
1568                 export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
1569                 ;;
1570             *)
1571                 export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
1572                 ;;
1573         esac
1574       else
1575         case `uname -s` in
1576             Darwin)
1577                 export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)
1578                 ;;
1579             *)
1580                 export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
1581                 ;;
1582         esac
1583       fi
1584
1585       # Keep track of the fact that we set JAVA_HOME ourselves, so that
1586       # we can change it on the next envsetup.sh, if required.
1587       export ANDROID_SET_JAVA_HOME=true
1588     fi
1589 }
1590
1591 # Print colored exit condition
1592 function pez {
1593     "$@"
1594     local retval=$?
1595     if [ $retval -ne 0 ]
1596     then
1597         echo $'\E'"[0;31mFAILURE\e[00m"
1598     else
1599         echo $'\E'"[0;32mSUCCESS\e[00m"
1600     fi
1601     return $retval
1602 }
1603
1604 function get_make_command()
1605 {
1606   echo command make
1607 }
1608
1609 function mk_timer()
1610 {
1611     local start_time=$(date +"%s")
1612     $@
1613     local ret=$?
1614     local end_time=$(date +"%s")
1615     local tdiff=$(($end_time-$start_time))
1616     local hours=$(($tdiff / 3600 ))
1617     local mins=$((($tdiff % 3600) / 60))
1618     local secs=$(($tdiff % 60))
1619     local ncolors=$(tput colors 2>/dev/null)
1620     if [ -n "$ncolors" ] && [ $ncolors -ge 8 ]; then
1621         color_failed=$'\E'"[0;31m"
1622         color_success=$'\E'"[0;32m"
1623         color_reset=$'\E'"[00m"
1624     else
1625         color_failed=""
1626         color_success=""
1627         color_reset=""
1628     fi
1629     echo
1630     if [ $ret -eq 0 ] ; then
1631         echo -n "${color_success}#### make completed successfully "
1632     else
1633         echo -n "${color_failed}#### make failed to build some targets "
1634     fi
1635     if [ $hours -gt 0 ] ; then
1636         printf "(%02g:%02g:%02g (hh:mm:ss))" $hours $mins $secs
1637     elif [ $mins -gt 0 ] ; then
1638         printf "(%02g:%02g (mm:ss))" $mins $secs
1639     elif [ $secs -gt 0 ] ; then
1640         printf "(%s seconds)" $secs
1641     fi
1642     echo " ####${color_reset}"
1643     echo
1644     return $ret
1645 }
1646
1647 function provision()
1648 {
1649     if [ ! "$ANDROID_PRODUCT_OUT" ]; then
1650         echo "Couldn't locate output files.  Try running 'lunch' first." >&2
1651         return 1
1652     fi
1653     if [ ! -e "$ANDROID_PRODUCT_OUT/provision-device" ]; then
1654         echo "There is no provisioning script for the device." >&2
1655         return 1
1656     fi
1657
1658     # Check if user really wants to do this.
1659     if [ "$1" = "--no-confirmation" ]; then
1660         shift 1
1661     else
1662         echo "This action will reflash your device."
1663         echo ""
1664         echo "ALL DATA ON THE DEVICE WILL BE IRREVOCABLY ERASED."
1665         echo ""
1666         echo -n "Are you sure you want to do this (yes/no)? "
1667         read
1668         if [[ "${REPLY}" != "yes" ]] ; then
1669             echo "Not taking any action. Exiting." >&2
1670             return 1
1671         fi
1672     fi
1673     "$ANDROID_PRODUCT_OUT/provision-device" "$@"
1674 }
1675
1676 function make()
1677 {
1678     mk_timer $(get_make_command) "$@"
1679 }
1680
1681 function __detect_shell() {
1682     case `ps -o command -p $$` in
1683         *bash*)
1684             echo bash
1685             ;;
1686         *zsh*)
1687             echo zsh
1688             ;;
1689         *)
1690             echo unknown
1691             return 1
1692             ;;
1693     esac
1694     return
1695 }
1696
1697
1698 if ! __detect_shell > /dev/null; then
1699     echo "WARNING: Only bash and zsh are supported, use of other shell may lead to erroneous results"
1700 fi
1701
1702 # Execute the contents of any vendorsetup.sh files we can find.
1703 for f in `test -d device && find -L device -maxdepth 4 -name 'vendorsetup.sh' 2> /dev/null | sort` \
1704          `test -d vendor && find -L vendor -maxdepth 4 -name 'vendorsetup.sh' 2> /dev/null | sort` \
1705          `test -d product && find -L product -maxdepth 4 -name 'vendorsetup.sh' 2> /dev/null | sort`
1706 do
1707     echo "including $f"
1708     . $f
1709 done
1710 unset f
1711
1712 # Add completions
1713 check_bash_version && {
1714     dirs="sdk/bash_completion vendor/cm/bash_completion"
1715     for dir in $dirs; do
1716     if [ -d ${dir} ]; then
1717         for f in `/bin/ls ${dir}/[a-z]*.bash 2> /dev/null`; do
1718             echo "including $f"
1719             . $f
1720         done
1721     fi
1722     done
1723 }
1724
1725 export ANDROID_BUILD_TOP=$(gettop)
1726
1727 . $ANDROID_BUILD_TOP/vendor/cm/build/envsetup.sh