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