envsetup.sh revision 267a928deb5a4e7aef83f47fba7da953cfd91a49
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            adb shell debuggerd -b $PID
958        fi
959    fi
960}
961
962function gdbwrapper()
963{
964    local GDB_CMD="$1"
965    shift 1
966    $GDB_CMD -x "$@"
967}
968
969function get_symbols_directory()
970{
971    echo $(get_abs_build_var TARGET_OUT_UNSTRIPPED)
972}
973
974# process the symbolic link of /proc/$PID/exe and use the host file tool to
975# determine whether it is a 32-bit or 64-bit executable. It returns "" or "64"
976# which can be conveniently used as suffix.
977function is64bit()
978{
979    local PID="$1"
980    if [ "$PID" ] ; then
981        local EXE=`adb shell readlink /proc/$PID/exe`
982        local EXE_DIR=`get_abs_build_var PRODUCT_OUT`
983        local IS64BIT=`file "$EXE_DIR$EXE" | grep "64-bit"`
984        if [ "$IS64BIT" != "" ]; then
985            echo "64"
986        else
987            echo ""
988        fi
989    else
990        echo ""
991    fi
992}
993
994# gdbclient now determines whether the user wants to debug a 32-bit or 64-bit
995# executable, set up the approriate gdbserver, then invokes the proper host
996# gdb.
997function gdbclient()
998{
999   local OUT_ROOT=$(get_abs_build_var PRODUCT_OUT)
1000   local OUT_SYMBOLS=$(get_abs_build_var TARGET_OUT_UNSTRIPPED)
1001   local OUT_SO_SYMBOLS=$(get_abs_build_var TARGET_OUT_SHARED_LIBRARIES_UNSTRIPPED)
1002   local OUT_VENDOR_SO_SYMBOLS=$(get_abs_build_var TARGET_OUT_VENDOR_SHARED_LIBRARIES_UNSTRIPPED)
1003   local OUT_EXE_SYMBOLS=$(get_symbols_directory)
1004   local PREBUILTS=$(get_abs_build_var ANDROID_PREBUILTS)
1005   local ARCH=$(get_build_var TARGET_ARCH)
1006   local GDB
1007   case "$ARCH" in
1008       arm) GDB=arm-linux-androideabi-gdb;;
1009       arm64) GDB=arm-linux-androideabi-gdb; GDB64=aarch64-linux-android-gdb;;
1010       mips) GDB=mipsel-linux-android-gdb;;
1011       mips64) GDB=mipsel-linux-android-gdb;;
1012       x86) GDB=x86_64-linux-android-gdb;;
1013       x86_64) GDB=x86_64-linux-android-gdb;;
1014       *) echo "Unknown arch $ARCH"; return 1;;
1015   esac
1016
1017   if [ "$OUT_ROOT" -a "$PREBUILTS" ]; then
1018       local EXE="$1"
1019       if [ "$EXE" ] ; then
1020           EXE=$1
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
1066       echo >|"$OUT_ROOT/gdbclient.cmds" "set solib-absolute-prefix $OUT_SYMBOLS"
1067       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"
1068       echo >>"$OUT_ROOT/gdbclient.cmds" "source $ANDROID_BUILD_TOP/development/scripts/gdb/dalvik.gdb"
1069       echo >>"$OUT_ROOT/gdbclient.cmds" "target remote $PORT"
1070       echo >>"$OUT_ROOT/gdbclient.cmds" ""
1071
1072       local WHICH_GDB=
1073       # 64-bit exe found
1074       if [ "$USE64BIT" != "" ] ; then
1075           WHICH_GDB=$ANDROID_TOOLCHAIN/$GDB64
1076       # 32-bit exe / 32-bit platform
1077       elif [ "$(get_build_var TARGET_2ND_ARCH)" = "" ]; then
1078           WHICH_GDB=$ANDROID_TOOLCHAIN/$GDB
1079       # 32-bit exe / 64-bit platform
1080       else
1081           WHICH_GDB=$ANDROID_TOOLCHAIN_2ND_ARCH/$GDB
1082       fi
1083
1084       gdbwrapper $WHICH_GDB "$OUT_ROOT/gdbclient.cmds" "$OUT_EXE_SYMBOLS/$EXE"
1085  else
1086       echo "Unable to determine build system output dir."
1087   fi
1088
1089}
1090
1091case `uname -s` in
1092    Darwin)
1093        function sgrep()
1094        {
1095            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 "$@"
1096        }
1097
1098        ;;
1099    *)
1100        function sgrep()
1101        {
1102            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 "$@"
1103        }
1104        ;;
1105esac
1106
1107function gettargetarch
1108{
1109    get_build_var TARGET_ARCH
1110}
1111
1112function ggrep()
1113{
1114    find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f -name "*\.gradle" -print0 | xargs -0 grep --color -n "$@"
1115}
1116
1117function jgrep()
1118{
1119    find . -name .repo -prune -o -name .git -prune -o -name out -prune -o -type f -name "*\.java" -print0 | xargs -0 grep --color -n "$@"
1120}
1121
1122function cgrep()
1123{
1124    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 "$@"
1125}
1126
1127function resgrep()
1128{
1129    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;
1130}
1131
1132function mangrep()
1133{
1134    find . -name .repo -prune -o -name .git -prune -o -path ./out -prune -o -type f -name 'AndroidManifest.xml' -print0 | xargs -0 grep --color -n "$@"
1135}
1136
1137function sepgrep()
1138{
1139    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 "$@"
1140}
1141
1142case `uname -s` in
1143    Darwin)
1144        function mgrep()
1145        {
1146            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 "$@"
1147        }
1148
1149        function treegrep()
1150        {
1151            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 "$@"
1152        }
1153
1154        ;;
1155    *)
1156        function mgrep()
1157        {
1158            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 "$@"
1159        }
1160
1161        function treegrep()
1162        {
1163            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 "$@"
1164        }
1165
1166        ;;
1167esac
1168
1169function getprebuilt
1170{
1171    get_abs_build_var ANDROID_PREBUILTS
1172}
1173
1174function tracedmdump()
1175{
1176    T=$(gettop)
1177    if [ ! "$T" ]; then
1178        echo "Couldn't locate the top of the tree.  Try setting TOP."
1179        return
1180    fi
1181    local prebuiltdir=$(getprebuilt)
1182    local arch=$(gettargetarch)
1183    local KERNEL=$T/prebuilts/qemu-kernel/$arch/vmlinux-qemu
1184
1185    local TRACE=$1
1186    if [ ! "$TRACE" ] ; then
1187        echo "usage:  tracedmdump  tracename"
1188        return
1189    fi
1190
1191    if [ ! -r "$KERNEL" ] ; then
1192        echo "Error: cannot find kernel: '$KERNEL'"
1193        return
1194    fi
1195
1196    local BASETRACE=$(basename $TRACE)
1197    if [ "$BASETRACE" = "$TRACE" ] ; then
1198        TRACE=$ANDROID_PRODUCT_OUT/traces/$TRACE
1199    fi
1200
1201    echo "post-processing traces..."
1202    rm -f $TRACE/qtrace.dexlist
1203    post_trace $TRACE
1204    if [ $? -ne 0 ]; then
1205        echo "***"
1206        echo "*** Error: malformed trace.  Did you remember to exit the emulator?"
1207        echo "***"
1208        return
1209    fi
1210    echo "generating dexlist output..."
1211    /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
1212    echo "generating dmtrace data..."
1213    q2dm -r $ANDROID_PRODUCT_OUT/symbols $TRACE $KERNEL $TRACE/dmtrace || return
1214    echo "generating html file..."
1215    dmtracedump -h $TRACE/dmtrace >| $TRACE/dmtrace.html || return
1216    echo "done, see $TRACE/dmtrace.html for details"
1217    echo "or run:"
1218    echo "    traceview $TRACE/dmtrace"
1219}
1220
1221# communicate with a running device or emulator, set up necessary state,
1222# and run the hat command.
1223function runhat()
1224{
1225    # process standard adb options
1226    local adbTarget=""
1227    if [ "$1" = "-d" -o "$1" = "-e" ]; then
1228        adbTarget=$1
1229        shift 1
1230    elif [ "$1" = "-s" ]; then
1231        adbTarget="$1 $2"
1232        shift 2
1233    fi
1234    local adbOptions=${adbTarget}
1235    #echo adbOptions = ${adbOptions}
1236
1237    # runhat options
1238    local targetPid=$1
1239
1240    if [ "$targetPid" = "" ]; then
1241        echo "Usage: runhat [ -d | -e | -s serial ] target-pid"
1242        return
1243    fi
1244
1245    # confirm hat is available
1246    if [ -z $(which hat) ]; then
1247        echo "hat is not available in this configuration."
1248        return
1249    fi
1250
1251    # issue "am" command to cause the hprof dump
1252    local sdcard=$(adb ${adbOptions} shell echo -n '$EXTERNAL_STORAGE')
1253    local devFile=$sdcard/hprof-$targetPid
1254    #local devFile=/data/local/hprof-$targetPid
1255    echo "Poking $targetPid and waiting for data..."
1256    echo "Storing data at $devFile"
1257    adb ${adbOptions} shell am dumpheap $targetPid $devFile
1258    echo "Press enter when logcat shows \"hprof: heap dump completed\""
1259    echo -n "> "
1260    read
1261
1262    local localFile=/tmp/$$-hprof
1263
1264    echo "Retrieving file $devFile..."
1265    adb ${adbOptions} pull $devFile $localFile
1266
1267    adb ${adbOptions} shell rm $devFile
1268
1269    echo "Running hat on $localFile"
1270    echo "View the output by pointing your browser at http://localhost:7000/"
1271    echo ""
1272    hat -JXmx512m $localFile
1273}
1274
1275function getbugreports()
1276{
1277    local reports=(`adb shell ls /sdcard/bugreports | tr -d '\r'`)
1278
1279    if [ ! "$reports" ]; then
1280        echo "Could not locate any bugreports."
1281        return
1282    fi
1283
1284    local report
1285    for report in ${reports[@]}
1286    do
1287        echo "/sdcard/bugreports/${report}"
1288        adb pull /sdcard/bugreports/${report} ${report}
1289        gunzip ${report}
1290    done
1291}
1292
1293function getsdcardpath()
1294{
1295    adb ${adbOptions} shell echo -n \$\{EXTERNAL_STORAGE\}
1296}
1297
1298function getscreenshotpath()
1299{
1300    echo "$(getsdcardpath)/Pictures/Screenshots"
1301}
1302
1303function getlastscreenshot()
1304{
1305    local screenshot_path=$(getscreenshotpath)
1306    local screenshot=`adb ${adbOptions} ls ${screenshot_path} | grep Screenshot_[0-9-]*.*\.png | sort -rk 3 | cut -d " " -f 4 | head -n 1`
1307    if [ "$screenshot" = "" ]; then
1308        echo "No screenshots found."
1309        return
1310    fi
1311    echo "${screenshot}"
1312    adb ${adbOptions} pull ${screenshot_path}/${screenshot}
1313}
1314
1315function startviewserver()
1316{
1317    local port=4939
1318    if [ $# -gt 0 ]; then
1319            port=$1
1320    fi
1321    adb shell service call window 1 i32 $port
1322}
1323
1324function stopviewserver()
1325{
1326    adb shell service call window 2
1327}
1328
1329function isviewserverstarted()
1330{
1331    adb shell service call window 3
1332}
1333
1334function key_home()
1335{
1336    adb shell input keyevent 3
1337}
1338
1339function key_back()
1340{
1341    adb shell input keyevent 4
1342}
1343
1344function key_menu()
1345{
1346    adb shell input keyevent 82
1347}
1348
1349function smoketest()
1350{
1351    if [ ! "$ANDROID_PRODUCT_OUT" ]; then
1352        echo "Couldn't locate output files.  Try running 'lunch' first." >&2
1353        return
1354    fi
1355    T=$(gettop)
1356    if [ ! "$T" ]; then
1357        echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
1358        return
1359    fi
1360
1361    (\cd "$T" && mmm tests/SmokeTest) &&
1362      adb uninstall com.android.smoketest > /dev/null &&
1363      adb uninstall com.android.smoketest.tests > /dev/null &&
1364      adb install $ANDROID_PRODUCT_OUT/data/app/SmokeTestApp.apk &&
1365      adb install $ANDROID_PRODUCT_OUT/data/app/SmokeTest.apk &&
1366      adb shell am instrument -w com.android.smoketest.tests/android.test.InstrumentationTestRunner
1367}
1368
1369# simple shortcut to the runtest command
1370function runtest()
1371{
1372    T=$(gettop)
1373    if [ ! "$T" ]; then
1374        echo "Couldn't locate the top of the tree.  Try setting TOP." >&2
1375        return
1376    fi
1377    ("$T"/development/testrunner/runtest.py $@)
1378}
1379
1380function godir () {
1381    if [[ -z "$1" ]]; then
1382        echo "Usage: godir <regex>"
1383        return
1384    fi
1385    T=$(gettop)
1386    if [[ ! -f $T/filelist ]]; then
1387        echo -n "Creating index..."
1388        (\cd $T; find . -wholename ./out -prune -o -wholename ./.repo -prune -o -type f > filelist)
1389        echo " Done"
1390        echo ""
1391    fi
1392    local lines
1393    lines=($(\grep "$1" $T/filelist | sed -e 's/\/[^/]*$//' | sort | uniq))
1394    if [[ ${#lines[@]} = 0 ]]; then
1395        echo "Not found"
1396        return
1397    fi
1398    local pathname
1399    local choice
1400    if [[ ${#lines[@]} > 1 ]]; then
1401        while [[ -z "$pathname" ]]; do
1402            local index=1
1403            local line
1404            for line in ${lines[@]}; do
1405                printf "%6s %s\n" "[$index]" $line
1406                index=$(($index + 1))
1407            done
1408            echo
1409            echo -n "Select one: "
1410            unset choice
1411            read choice
1412            if [[ $choice -gt ${#lines[@]} || $choice -lt 1 ]]; then
1413                echo "Invalid choice"
1414                continue
1415            fi
1416            pathname=${lines[$(($choice-1))]}
1417        done
1418    else
1419        pathname=${lines[0]}
1420    fi
1421    \cd $T/$pathname
1422}
1423
1424# Force JAVA_HOME to point to java 1.7 or java 1.6  if it isn't already set.
1425#
1426# Note that the MacOS path for java 1.7 includes a minor revision number (sigh).
1427# For some reason, installing the JDK doesn't make it show up in the
1428# JavaVM.framework/Versions/1.7/ folder.
1429function set_java_home() {
1430    # Clear the existing JAVA_HOME value if we set it ourselves, so that
1431    # we can reset it later, depending on the version of java the build
1432    # system needs.
1433    #
1434    # If we don't do this, the JAVA_HOME value set by the first call to
1435    # build/envsetup.sh will persist forever.
1436    if [ -n "$ANDROID_SET_JAVA_HOME" ]; then
1437      export JAVA_HOME=""
1438    fi
1439
1440    if [ ! "$JAVA_HOME" ]; then
1441      if [ -n "$LEGACY_USE_JAVA6" ]; then
1442        case `uname -s` in
1443            Darwin)
1444                export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
1445                ;;
1446            *)
1447                export JAVA_HOME=/usr/lib/jvm/java-6-sun
1448                ;;
1449        esac
1450      else
1451        case `uname -s` in
1452            Darwin)
1453                export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
1454                ;;
1455            *)
1456                export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
1457                ;;
1458        esac
1459      fi
1460
1461      # Keep track of the fact that we set JAVA_HOME ourselves, so that
1462      # we can change it on the next envsetup.sh, if required.
1463      export ANDROID_SET_JAVA_HOME=true
1464    fi
1465}
1466
1467# Print colored exit condition
1468function pez {
1469    "$@"
1470    local retval=$?
1471    if [ $retval -ne 0 ]
1472    then
1473        echo -e "\e[0;31mFAILURE\e[00m"
1474    else
1475        echo -e "\e[0;32mSUCCESS\e[00m"
1476    fi
1477    return $retval
1478}
1479
1480function make()
1481{
1482    local start_time=$(date +"%s")
1483    $MAKE_UTIL $@
1484    local ret=$?
1485    local end_time=$(date +"%s")
1486    local tdiff=$(($end_time-$start_time))
1487    local hours=$(($tdiff / 3600 ))
1488    local mins=$((($tdiff % 3600) / 60))
1489    local secs=$(($tdiff % 60))
1490    echo
1491    if [ $ret -eq 0 ] ; then
1492        echo -n -e "\e[0;32m#### make completed successfully "
1493    else
1494        echo -n -e "\e[0;31m#### make failed to build some targets "
1495    fi
1496    if [ $hours -gt 0 ] ; then
1497        printf "(%02g:%02g:%02g (hh:mm:ss))" $hours $mins $secs
1498    elif [ $mins -gt 0 ] ; then
1499        printf "(%02g:%02g (mm:ss))" $mins $secs
1500    elif [ $secs -gt 0 ] ; then
1501        printf "(%s seconds)" $secs
1502    fi
1503    echo -e " ####\e[00m"
1504    echo
1505    return $ret
1506}
1507
1508
1509
1510if [ "x$SHELL" != "x/bin/bash" ]; then
1511    case `ps -o command -p $$` in
1512        *bash*)
1513            ;;
1514        *)
1515            echo "WARNING: Only bash is supported, use of other shell would lead to erroneous results"
1516            ;;
1517    esac
1518fi
1519
1520# Execute the contents of any vendorsetup.sh files we can find.
1521for f in `test -d device && find device -maxdepth 4 -name 'vendorsetup.sh' 2> /dev/null` \
1522         `test -d vendor && find vendor -maxdepth 4 -name 'vendorsetup.sh' 2> /dev/null`
1523do
1524    echo "including $f"
1525    . $f
1526done
1527unset f
1528
1529addcompletions
1530