1#!/bin/sh
2#
3# Copyright (C) 2010 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18# This wrapper script is used to launch a native debugging session
19# on a given NDK application. The application must be debuggable, i.e.
20# its android:debuggable attribute must be set to 'true' in the
21# <application> element of its manifest.
22#
23# See docs/NDK-GDB.TXT for usage description. Essentially, you just
24# need to launch ndk-gdb from your application project directory
25# after doing ndk-build && ant install && <start-application-on-device>
26#
27PROGDIR=`dirname $0`
28PROGDIR=`cd $PROGDIR && pwd -P`
29
30# Check if absolute NDK path contain space
31#
32case $PROGDIR in
33    *\ *) echo "ERROR: NDK path cannot contain space"
34          exit 1
35        ;;
36esac
37
38NDK_BUILDTOOLS_PATH=$PROGDIR/build/tools
39. $PROGDIR/build/tools/prebuilt-common.sh
40. $PROGDIR/build/tools/ndk-common.sh
41
42force_32bit_binaries
43
44# Find if a given shell program is available.
45# We need to take care of the fact that the 'which <foo>' command
46# may return either an empty string (Linux) or something like
47# "no <foo> in ..." (Darwin). Also, we need to redirect stderr
48# to /dev/null for Cygwin
49#
50# $1: program name
51# Out: program path, or empty string
52# Return: 0 on success, != 0 on error
53#
54find_program ()
55{
56    local PROG RET
57    PROG=$(which "$1" 2>/dev/null)
58    RET=$?
59    if [ $RET != 0 ]; then
60        PROG=
61    fi
62    echo "$PROG"
63    return $RET
64}
65
66quote_spaces ()
67{
68    echo "$@" | sed -e 's! !\ !g'
69}
70
71# If ADB_CMD is not defined, try to find a program named 'adb'
72# in our path.
73ADB_CMD=${ADB_CMD:-$(find_program adb)}
74ADB_FLAGS=${ADB_FLAGS:-}
75DEVICE_SERIAL=
76
77JDB_CMD=${JDB_CMD:-$(find_program jdb)}
78
79AWK_CMD=${AWK_CMD:-$(find_program awk)}
80
81DEBUG_PORT=5039
82JDB_PORT=65534
83
84UNKNOWN_ABI=$(find_ndk_unknown_archs)
85
86# Delay in seconds between launching the activity and attaching gdbserver on it.
87# This is needed because there is no way to know when the activity has really
88# started, and sometimes this takes a few seconds.
89DELAY=2
90
91PARAMETERS=
92OPTION_HELP=no
93OPTION_PROJECT=
94OPTION_FORCE=no
95OPTION_ADB=
96OPTION_EXEC=
97OPTION_START=no
98OPTION_LAUNCH=
99OPTION_LAUNCH_LIST=no
100OPTION_DELAY=
101OPTION_WAIT="-D"
102
103check_parameter ()
104{
105    if [ -z "$2" ]; then
106        echo "ERROR: Missing parameter after option '$1'"
107        exit 1
108    fi
109}
110
111check_adb_flags ()
112{
113    if [ -n "$ADB_FLAGS" ] ; then
114        echo "ERROR: Only one of -e, -d or -s <serial> can be used at the same time!"
115        exit 1
116    fi
117}
118
119get_build_var ()
120{
121    if [ -z "$GNUMAKE" ] ; then
122        GNUMAKE=make
123    fi
124    $GNUMAKE --no-print-dir -f $ANDROID_NDK_ROOT/build/core/build-local.mk -C $PROJECT DUMP_$1 | tail -1
125}
126
127get_build_var_for_abi ()
128{
129    if [ -z "$GNUMAKE" ] ; then
130        GNUMAKE=make
131    fi
132    $GNUMAKE --no-print-dir -f $ANDROID_NDK_ROOT/build/core/build-local.mk -C $PROJECT DUMP_$1 APP_ABI=$2 | tail -1
133}
134
135# Used to run an awk script on the manifest
136run_awk_manifest_script ()
137{
138    $AWK_CMD -f $AWK_SCRIPTS/$1 $PROJECT/$MANIFEST
139}
140
141if [ "$HOST_OS" = "cygwin" ] ; then
142# Return native path representation from cygwin one
143# $1: a cygwin-compatible path (e.g. /cygdrive/c/some/thing)
144# Return: path in host windows representation, e.g. C:/some/thing
145#
146# We use mixed mode (i.e. / as the directory separator) because
147# all the tools we use recognize it properly, and it avoids lots
148# of escaping nonsense associated with "\"
149#
150native_path ()
151{
152    cygpath -m $1
153}
154else # HOST_OS != windows
155native_path ()
156{
157    echo "$1"
158}
159fi # HOST_OS != windows
160
161# We need to ensure the ANDROID_NDK_ROOT is absolute, otherwise calls
162# to get_build_var, get_build_var_for_abi and run_awk_manifest_script
163# might fail, e.g. when invoked with:
164#
165#   cd $NDKROOT
166#   ./ndk-gdb --project=/path/to/project
167#
168path_is_absolute ()
169{
170    local P P2
171    P=$1       # copy path
172    P2=${P#/}  # remove / prefix, if any
173    [ "$P" != "$P2" ]
174}
175
176if ! path_is_absolute "$ANDROID_NDK_ROOT"; then
177    ANDROID_NDK_ROOT=$(pwd)/$ANDROID_NDK_ROOT
178fi
179
180
181VERBOSE=no
182while [ -n "$1" ]; do
183    opt="$1"
184    optarg=`expr "x$opt" : 'x[^=]*=\(.*\)'`
185    case "$opt" in
186        --help|-h|-\?)
187            OPTION_HELP=yes
188            ;;
189        --verbose)
190            VERBOSE=yes
191            ;;
192        -s)
193            check_parameter $1 $2
194            check_adb_flags
195            ADB_FLAGS=" -s"
196            DEVICE_SERIAL=$2
197            shift
198            ;;
199        -s*)
200            check_adb_flags
201            optarg=`expr -- "$opt" : '-s\(.*\)'`
202            ADB_FLAGS=" -s"
203            DEVICE_SERIAL=$optarg
204            ;;
205        -p)
206            check_parameter $1 $2
207            OPTION_PROJECT="$2"
208            shift
209            ;;
210        -p*)
211            optarg=`expr -- "$opt" : '-p\(.*\)'`
212            OPTION_PROJECT="$optarg"
213            ;;
214        --exec=*)
215            OPTION_EXEC="$optarg"
216            ;;
217        -x)
218            check_parameter $1 $2
219            OPTION_EXEC="$2"
220            shift
221            ;;
222        -x*)
223            optarg=`expr -- "$opt" : '-x\(.*\)'`
224            OPTION_EXEC="$optarg"
225            ;;
226        -e)
227            check_adb_flags
228            ADB_FLAGS=" -e"
229            ;;
230        -d)
231            check_adb_flags
232            ADB_FLAGS=" -d"
233            ;;
234        --adb=*) # specify ADB command
235            OPTION_ADB="$optarg"
236            ;;
237        --awk=*)
238            AWK_CMD="$optarg"
239            ;;
240        --project=*)
241            OPTION_PROJECT="$optarg"
242            ;;
243        --port=*)
244            DEBUG_PORT="$optarg"
245            ;;
246        --force)
247            OPTION_FORCE="yes"
248            ;;
249        --launch-list)
250            OPTION_LAUNCH_LIST="yes"
251            ;;
252        --launch=*)
253            OPTION_LAUNCH="$optarg"
254            ;;
255        --start)
256            OPTION_START=yes
257            ;;
258        --delay=*)
259            OPTION_DELAY="$optarg"
260            ;;
261        --nowait)
262            JDB_PORT=
263            OPTION_WAIT=
264            ;;
265        -*) # unknown options
266            echo "ERROR: Unknown option '$opt', use --help for list of valid ones."
267            exit 1
268        ;;
269        *)  # Simply record parameter
270            if [ -z "$PARAMETERS" ] ; then
271                PARAMETERS="$opt"
272            else
273                PARAMETERS="$PARAMETERS $opt"
274            fi
275            ;;
276    esac
277    shift
278done
279
280if [ -z "$JDB_CMD" ] && [ -n "$OPTION_WAIT" ]; then
281    echo "ERROR: 'jdb' not found; you must either install the JDK, or specify --nowait"
282    exit 1
283fi
284if [ -n "$JDB_PORT" ] && [ "$JDB_PORT" = "$DEBUG_PORT" ]; then
285    echo "ERROR: --port specified cannot be $JDB_PORT without --nowait"
286    exit 1
287fi
288
289if [ "$OPTION_HELP" = "yes" ] ; then
290    echo "Usage: $PROGNAME [options]"
291    echo ""
292    echo "Setup a gdb debugging session for your Android NDK application."
293    echo "Read $$NDK/docs/NDK-GDB.TXT for complete usage instructions."
294    echo ""
295    echo "Valid options:"
296    echo ""
297    echo "    --help|-h|-?      Print this help"
298    echo "    --verbose         Enable verbose mode"
299    echo "    --force           Kill existing debug session if it exists"
300    echo "    --nowait          Don't have application wait for debugger to attach"
301    echo "                         (This might cause you to miss some early JNI breakpoints)"
302    echo "    --start           Launch application instead of attaching to existing one"
303    echo "    --launch=<name>   Same as --start, but specify activity name (see below)"
304    echo "    --launch-list     List all launchable activity names from manifest"
305    echo "    --delay=<secs>    Delay in seconds between activity start and gdbserver attach."
306    echo "    --project=<path>  Specify application project path"
307    echo "    -p <path>         Same as --project=<path>"
308    echo "    --port=<port>     Use tcp:localhost:<port> to communicate with gdbserver [$DEBUG_PORT]"
309    echo "    --exec=<file>     Execute gdb initialization commands in <file> after connection"
310    echo "    -x <file>         Same as --exec=<file>"
311    echo "    --adb=<file>      Use specific adb command [$ADB_CMD]"
312    echo "    --awk=<file>      Use specific awk command [$AWK_CMD]"
313    echo "    -e                Connect to single emulator instance"
314    echo "    -d                Connect to single target device"
315    echo "    -s <serial>       Connect to specific emulator or device"
316    echo ""
317    exit 0
318fi
319
320log "Android NDK installation path: $ANDROID_NDK_ROOT"
321
322if [ -n "$OPTION_EXEC" ] ; then
323    if [ ! -f "$OPTION_EXEC" ]; then
324        echo "ERROR: Invalid initialization file: $OPTION_EXEC"
325        exit 1
326    fi
327fi
328
329if [ -n "$OPTION_DELAY" ] ; then
330    DELAY="$OPTION_DELAY"
331fi
332
333# Check ADB tool version
334if [ -n "$OPTION_ADB" ] ; then
335    ADB_CMD=$OPTION_ADB
336    log "Using specific adb command: $ADB_CMD"
337else
338    if [ -z "$ADB_CMD" ] ; then
339        echo "ERROR: The 'adb' tool is not in your path."
340        echo "       You can change your PATH variable, or use"
341        echo "       --adb=<executable> to point to a valid one."
342        exit 1
343    fi
344    log "Using default adb command: $ADB_CMD"
345fi
346
347ADB_CMD=$(quote_spaces $ADB_CMD)
348ADB_VERSION=$("$ADB_CMD" version 2>/dev/null)
349if [ $? != 0 ] ; then
350    echo "ERROR: Could not run ADB with: $ADB_CMD"
351    exit 1
352fi
353log "ADB version found: $ADB_VERSION"
354
355if [ "x$DEVICE_SERIAL" = "x" ]; then
356    log "Using ADB flags: $ADB_FLAGS"
357else
358    log "Using ADB flags: $ADB_FLAGS" \"$DEVICE_SERIAL\"
359fi
360
361JDB_CMD=$(quote_spaces $JDB_CMD)
362log "Using JDB command: $JDB_CMD"
363
364# Run an ADB command with the right ADB flags
365# $1+: adb command parameter
366adb_cmd ()
367{
368    if [ "x$DEVICE_SERIAL" = "x" ]; then
369        "$ADB_CMD" $ADB_FLAGS "$@"
370    else
371        # NOTE: We escape $ADB_CMD and $DEVICE_SERIAL in case they contains spaces.
372        "$ADB_CMD" $ADB_FLAGS "$DEVICE_SERIAL" "$@"
373    fi
374}
375
376# Used internally by adb_var_shell and adb_var_shell2.
377# $1: 1 to redirect stderr to $1, 0 otherwise.
378# $2: Variable name that will contain the result
379# $3+: Command options
380_adb_var_shell ()
381{
382    # We need a temporary file to store the output of our command
383    local CMD_OUT RET OUTPUT VARNAME REDIRECT_STDERR
384    REDIRECT_STDERR=$1
385    VARNAME=$2
386    shift; shift;
387    CMD_OUT=`mktemp /tmp/ndk-gdb-cmdout-XXXXXX`
388    # Run the command, while storing the standard output to CMD_OUT
389    # and appending the exit code as the last line.
390    if [ "$REDIRECT_STDERR" != 0 ]; then
391        adb_cmd shell "$@" ";" echo \$? | sed -e 's![[:cntrl:]]!!g' > $CMD_OUT 2>&1
392    else
393        adb_cmd shell "$@" ";" echo \$? | sed -e 's![[:cntrl:]]!!g' > $CMD_OUT
394    fi
395    # Get last line in log, which contains the exit code from the command
396    RET=`sed -e '$!d' $CMD_OUT`
397    # Get output, which corresponds to everything except the last line
398    OUT=`sed -e '$d' $CMD_OUT`
399    rm -f $CMD_OUT
400    eval $VARNAME=\"\$OUT\"
401    return $RET
402}
403
404# Run a command through 'adb shell' and captures its standard output
405# into a variable. The function's exit code is the same than the command's.
406#
407# This is required because there is a bug where "adb shell" always returns
408# 0 on the host, even if the command fails on the device.
409#
410# $1: Variable name (e.g. FOO)
411# On exit, $FOO is set to the command's standard output
412#
413# The return status will be 0 (success) if the command succeeded
414# or 1 (failure) otherwise.
415adb_var_shell ()
416{
417    _adb_var_shell 0 "$@"
418}
419
420# A variant of adb_var_shell that stores both stdout and stderr in the output
421# $1: Variable name
422adb_var_shell2 ()
423{
424    _adb_var_shell 1 "$@"
425}
426
427# Return the PID of a given package or program, or 0 if it doesn't run
428# $1: Package name ("com.example.hellojni") or program name ("/lib/gdbserver")
429# Out: PID number, or 0 if not running
430get_pid_of ()
431{
432    adb_cmd shell ps | $AWK_CMD -f $AWK_SCRIPTS/extract-pid.awk -v PACKAGE="$1"
433}
434
435# Check the awk tool
436AWK_SCRIPTS=$ANDROID_NDK_ROOT/build/awk
437AWK_TEST=`$AWK_CMD -f $AWK_SCRIPTS/check-awk.awk`
438if [ $? != 0 ] ; then
439    echo "ERROR: Could not run '$AWK_CMD' command. Do you have it installed properly?"
440    exit 1
441fi
442if [ "$AWK_TEST" != "Pass" ] ; then
443    echo "ERROR: Your version of 'awk' is obsolete. Please use --awk=<file> to point to Nawk or Gawk!"
444    exit 1
445fi
446
447# Name of the manifest file
448MANIFEST=AndroidManifest.xml
449
450# Find the root of the application project.
451if [ -n "$OPTION_PROJECT" ] ; then
452    PROJECT=$OPTION_PROJECT
453    log "Using specified project path: $PROJECT"
454    if [ ! -d "$PROJECT" ] ; then
455        echo "ERROR: Your --project option does not point to a directory!"
456        exit 1
457    fi
458    if [ ! -f "$PROJECT/$MANIFEST" ] ; then
459        echo "ERROR: Your --project does not point to an Android project path!"
460        echo "       It is missing a $MANIFEST file."
461        exit 1
462    fi
463else
464    # Assume we are in the project directory
465    if [ -f "$MANIFEST" ] ; then
466        PROJECT=.
467    else
468        PROJECT=
469        CURDIR=`pwd`
470        while [ "$CURDIR" != "/" ] ; do
471            if [ -f "$CURDIR/$MANIFEST" ] ; then
472                PROJECT="$CURDIR"
473                break
474            fi
475            CURDIR=`dirname $CURDIR`
476        done
477        if [ -z "$PROJECT" ] ; then
478            echo "ERROR: Launch this script from an application project directory, or use --project=<path>."
479            exit 1
480        fi
481    fi
482    log "Using auto-detected project path: $PROJECT"
483fi
484
485# Extract the package name from the manifest
486PACKAGE_NAME=`run_awk_manifest_script extract-package-name.awk`
487log "Found package name: $PACKAGE_NAME"
488if [ $? != 0 -o "$PACKAGE_NAME" = "<none>" ] ; then
489    echo "ERROR: Could not extract package name from $PROJECT/$MANIFEST."
490    echo "       Please check that the file is well-formed!"
491    exit 1
492fi
493
494# If --launch-list is used, list all launchable activities, and be done with it
495if [ "$OPTION_LAUNCH_LIST" = "yes" ] ; then
496    log "Extracting list of launchable activities from manifest:"
497    run_awk_manifest_script extract-launchable.awk
498    exit 0
499fi
500
501APP_ABIS=`get_build_var APP_ABI`
502if [ "$APP_ABIS" != "${APP_ABIS%%all*}" ] ; then
503# replace first "all" with all available ABIs
504  ALL_ABIS=`get_build_var NDK_ALL_ABIS`
505  APP_ABIS_FRONT="${APP_ABIS%%all*}"
506  APP_ABIS_BACK="${APP_ABIS#*all}"
507  APP_ABIS="${APP_ABIS_FRONT}${ALL_ABIS}${APP_ABIS_BACK}"
508fi
509log "ABIs targetted by application: $APP_ABIS"
510
511# Check the ADB command, and that we can connect to the device/emulator
512ADB_TEST=`adb_cmd shell ls`
513if [ $? != 0 ] ; then
514    echo "ERROR: Could not connect to device or emulator!"
515    echo "       Please check that an emulator is running or a device is connected"
516    echo "       through USB to this machine. You can use -e, -d and -s <serial>"
517    echo "       in case of multiple ones."
518    exit 1
519fi
520
521# Check that the device is running Froyo (API Level 8) or higher
522#
523adb_var_shell API_LEVEL getprop ro.build.version.sdk
524if [ $? != 0 -o -z "$API_LEVEL" ] ; then
525    echo "ERROR: Could not find target device's supported API level!"
526    echo "ndk-gdb will only work if your device is running Android 2.2 or higher."
527    exit 1
528fi
529log "Device API Level: $API_LEVEL"
530if [ "$API_LEVEL" -lt "8" ] ; then
531    echo "ERROR: ndk-gdb requires a target device running Android 2.2 (API level 8) or higher."
532    echo "The target device is running API level $API_LEVEL!"
533    exit 1
534fi
535
536# Get the target device's supported ABI(s)
537# And check that they are supported by the application
538#
539COMPAT_ABI=none
540adb_var_shell CPU_ABI1 getprop ro.product.cpu.abi
541adb_var_shell CPU_ABI2 getprop ro.product.cpu.abi2
542
543# Both CPU_ABI1 and CPU_ABI2 may contain multiple comma-delimited abis.
544# Concatanate CPU_ABI1 and CPU_ABI2 and replace all ',' with space.
545# Add trailing space to ease whole-word matching of APP_ABI.
546CPU_ABIS="$CPU_ABI1,$CPU_ABI2"
547CPU_ABIS=$(echo $CPU_ABIS | tr ',' ' ')
548log "Device CPU ABIs: $CPU_ABIS"
549
550APP_ABIS=$APP_ABIS" "
551
552adb_var_shell BCFILES run-as $PACKAGE_NAME /system/bin/sh -c "ls lib/*.bc"
553if [ $? == 0 ]; then
554    COMPAT_ABI="$UNKNOWN_ABI"
555else
556    for CPU_ABI in $CPU_ABIS; do
557        if [ "$APP_ABIS" != "${APP_ABIS%$CPU_ABI *}" ] ; then
558            COMPAT_ABI=$CPU_ABI
559            break
560        fi
561    done
562fi
563if [ "$COMPAT_ABI" = none ] ; then
564    echo "ERROR: The device does not support the application's targetted CPU ABIs!"
565    echo "       Device supports:  $CPU_ABIS"
566    echo "       Package supports: $APP_ABIS"
567    exit 1
568fi
569log "Compatible device ABI: $COMPAT_ABI"
570
571# Get information from the build system
572GDBSETUP_INIT=`get_build_var_for_abi NDK_APP_GDBSETUP $COMPAT_ABI`
573log "Using gdb setup init: $GDBSETUP_INIT"
574
575# Find the prefix for gdb-client
576if [ "$COMPAT_ABI" != "$UNKNOWN_ABI" ]; then
577    TOOLCHAIN_PREFIX=`get_build_var_for_abi TOOLCHAIN_PREFIX $COMPAT_ABI`
578else
579    TOOLCHAIN_ABI=$(echo $CPU_ABIS | awk '{print $NF}')
580    TOOLCHAIN_PREFIX=`get_build_var_for_abi TOOLCHAIN_PREFIX $TOOLCHAIN_ABI`
581fi
582log "Using toolchain prefix: $TOOLCHAIN_PREFIX"
583
584APP_OUT=`get_build_var_for_abi TARGET_OUT $COMPAT_ABI`
585log "Using app out directory: $APP_OUT"
586
587# Check that the application is debuggable, or nothing will work
588DEBUGGABLE=`run_awk_manifest_script extract-debuggable.awk`
589log "Found debuggable flag: $DEBUGGABLE"
590if [ $? != 0 -o "$DEBUGGABLE" != "true" ] ; then
591    # If gdb.setup exists, then we built with 'ndk-build NDK_DEBUG=1' and it's
592    # ok to not have android:debuggable set to true in the original manifest.
593    # However, if this is not the case, then complain!!
594    if [ -f $PROJECT/libs/$COMPAT_ABI/gdb.setup ] ; then
595        log "Found gdb.setup under libs/$COMPAT_ABI, assuming app was built with NDK_DEBUG=1"
596    else
597        echo "ERROR: Package $PACKAGE_NAME is not debuggable ! You can fix that in two ways:"
598        echo ""
599        echo "  - Rebuilt with the NDK_DEBUG=1 option when calling 'ndk-build'."
600        echo ""
601        echo "  - Modify your manifest to set android:debuggable attribute to \"true\","
602        echo "    then rebuild normally."
603        echo ""
604        echo "After one of these, re-install to the device!"
605        exit 1
606    fi
607else
608    # DEBUGGABLE is true in the manifest. Let's check that the user didn't change the
609    # debuggable flag in the manifest without calling ndk-build afterwards.
610    if [ ! -f $PROJECT/libs/$COMPAT_ABI/gdb.setup ] ; then
611        echo "ERROR: Could not find gdb.setup under $PROJECT/libs/$COMPAT_ABI"
612        echo "       This usually means you modified your AndroidManifest.xml to set"
613        echo "       the android:debuggable flag to 'true' but did not rebuild the"
614        echo "       native binaries. Please call 'ndk-build' to do so,"
615        echo "       *then* re-install to the device!"
616        exit 1
617    fi
618fi
619
620# Find the <dataDir> of the package on the device
621adb_var_shell2 DATA_DIR run-as $PACKAGE_NAME /system/bin/sh -c pwd
622if [ $? != 0 -o -z "$DATA_DIR" ] ; then
623    echo "ERROR: Could not extract package's data directory. Are you sure that"
624    echo "       your installed application is debuggable?"
625    exit 1
626fi
627log "Found data directory: '$DATA_DIR'"
628
629# Let's check that 'gdbserver' is properly installed on the device too. If 'gdbserver'
630# is not there, push 'gdbserver' found in prebuilt.
631#
632DEVICE_GDBSERVER=$DATA_DIR/lib/gdbserver
633adb_var_shell2 GDBSERVER_RESULT ls $DEVICE_GDBSERVER
634if [ $? != 0 ]; then
635
636    # Figure out what's the target-arch and find gdbserver in prebuilt.
637    TARGET_ARCH=none
638
639    for ANDROID_ARCH in $ANDROID_NDK_ROOT/prebuilt/android-*; do
640        ANDROID_ARCH=${ANDROID_ARCH#*android-}
641        if [ x"$CPU_ABIS" != x"${CPU_ABIS#$ANDROID_ARCH*}" ]; then
642            TARGET_ARCH=$ANDROID_ARCH
643            break;
644        fi
645    done
646
647    if [ $TARGET_ARCH != "none" ]; then
648        DEVICE_GDBSERVER=/data/local/tmp/gdbserver
649
650        adb shell mkdir -p /data/local/tmp
651        adb push ${ANDROID_NDK_ROOT}/prebuilt/android-${TARGET_ARCH}/gdbserver/gdbserver \
652                 $DEVICE_GDBSERVER
653        log "Push gdbserver in device"
654    else
655        echo "ERROR: Non-debuggable application installed on the target device."
656        echo "       Please re-install the debuggable version!"
657        exit 1
658    fi
659fi
660log "Found device gdbserver: $DEVICE_GDBSERVER"
661
662# Launch the activity if needed
663if [ "$OPTION_START" = "yes" ] ; then
664    # If --launch is used, ignore --start, otherwise extract the first
665    # launchable activity name from the manifest and use it as if --launch=<name>
666    # was used instead.
667    #
668    if [ -z "$OPTION_LAUNCH" ] ; then
669        OPTION_LAUNCH=`run_awk_manifest_script extract-launchable.awk | sed 2q`
670        if [ $? != 0 ] ; then
671            echo "ERROR: Could not extract name of launchable activity from manifest!"
672            echo "       Try to use --launch=<name> directly instead as a work-around."
673            exit 1
674        fi
675        log "Found first launchable activity: $OPTION_LAUNCH"
676        if [ -z "$OPTION_LAUNCH" ] ; then
677            echo "ERROR: It seems that your Application does not have any launchable activity!"
678            echo "       Please fix your manifest file and rebuild/re-install your application."
679            exit 1
680        fi
681    fi
682fi
683
684if [ -n "$OPTION_LAUNCH" ] ; then
685    log "Launching activity: $PACKAGE_NAME/$OPTION_LAUNCH"
686    run adb_cmd shell am start $OPTION_WAIT -n $PACKAGE_NAME/$OPTION_LAUNCH
687    if [ $? != 0 ] ; then
688        echo "ERROR: Could not launch specified activity: $OPTION_LAUNCH"
689        echo "       Use --launch-list to dump a list of valid values."
690        exit 1
691    fi
692    # Sleep a bit, it sometimes take one second to start properly
693    # Note that we use the 'sleep' command on the device here.
694    run adb_cmd shell sleep $DELAY
695fi
696
697# Find the PID of the application being run
698PID=$(get_pid_of "$PACKAGE_NAME")
699log "Found running PID: $PID"
700if [ $? != 0 -o "$PID" = "0" ] ; then
701    echo "ERROR: Could not extract PID of application on device/emulator."
702    if [ -n "$OPTION_LAUNCH" ] ; then
703        echo "       Weird, this probably means one of these:"
704        echo ""
705        echo "         - The installed package does not match your current manifest."
706        echo "         - The application process was terminated."
707        echo ""
708        echo "       Try using the --verbose option and look at its output for details."
709    else
710        echo "       Are you sure the application is already started?"
711        echo "       Consider using --start or --launch=<name> if not."
712    fi
713    exit 1
714fi
715
716# Check that there is no other instance of gdbserver running
717GDBSERVER_PID=$(get_pid_of lib/gdbserver)
718if [ "$GDBSERVER_PID" != "0" ]; then
719    if [ "$OPTION_FORCE" = "no" ] ; then
720        echo "ERROR: Another debug session running, Use --force to kill it."
721        exit 1
722    fi
723    log "Killing existing debugging session"
724    run adb_cmd shell kill -9 $GDBSERVER_PID
725fi
726
727# Launch gdbserver now
728DEBUG_SOCKET=debug-socket
729run adb_cmd shell run-as $PACKAGE_NAME $DEVICE_GDBSERVER +$DEBUG_SOCKET --attach $PID &
730if [ $? != 0 ] ; then
731    echo "ERROR: Could not launch gdbserver on the device?"
732    exit 1
733fi
734log "Launched gdbserver succesfully."
735
736# Setup network redirection
737log "Setup network redirection"
738run adb_cmd forward tcp:$DEBUG_PORT localfilesystem:$DATA_DIR/$DEBUG_SOCKET
739if [ $? != 0 ] ; then
740    echo "ERROR: Could not setup network redirection to gdbserver?"
741    echo "       Maybe using --port=<port> to use a different TCP port might help?"
742    exit 1
743fi
744
745# Get the app_server binary from the device
746APP_PROCESS=$APP_OUT/app_process
747run adb_cmd pull /system/bin/app_process `native_path $APP_PROCESS`
748log "Pulled app_process from device/emulator."
749
750run adb_cmd pull /system/bin/linker `native_path $APP_OUT/linker`
751log "Pulled linker from device/emulator."
752
753run adb_cmd pull /system/lib/libc.so `native_path $APP_OUT/libc.so`
754log "Pulled libc.so from device/emulator."
755
756# Setup JDB connection, for --start or --launch
757if [ "$OPTION_START" = "yes" ] || [ -n "$OPTION_LAUNCH" ] ; then
758    if [ -n "$JDB_PORT" ]; then
759        log "Setup JDB connection"
760        run adb_cmd forward tcp:$JDB_PORT jdwp:$PID
761        sleep 1
762        $JDB_CMD -connect com.sun.jdi.SocketAttach:hostname=localhost,port=$JDB_PORT &
763        sleep 1
764    fi
765fi
766
767# If we are debugging UNKNOWN_ABI, download compiled *.so from device.
768#
769if [ $COMPAT_ABI == $UNKNOWN_ABI ]; then
770    for bc in $BCFILES; do
771        log "Pulled $(basename $bc .bc).so from device/emulator."
772        adb pull $DATA_DIR/lib/$(basename $bc .bc).so $PROJECT/obj/local/$UNKNOWN_ABI/
773    done
774fi
775
776# Now launch the appropriate gdb client with the right init commands
777#
778GDBCLIENT=${TOOLCHAIN_PREFIX}gdb
779GDBSETUP=$APP_OUT/gdb.setup
780cp -f $GDBSETUP_INIT $GDBSETUP
781#uncomment the following to debug the remote connection only
782#echo "set debug remote 1" >> $GDBSETUP
783echo "file `native_path $APP_PROCESS`" >> $GDBSETUP
784echo "target remote :$DEBUG_PORT" >> $GDBSETUP
785if [ -n "$OPTION_EXEC" ] ; then
786    cat $OPTION_EXEC >> $GDBSETUP
787fi
788$GDBCLIENT -x `native_path $GDBSETUP`
789