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