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