OSDN Git Service

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