OSDN Git Service

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