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