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