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