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