Android G1에서 root권한 및 cp와 같은 유틸리티 설치 하는 법

Add busybox

  1. download busybox by tapping and holding (long pressing) this file and choosing save link to your sd card (using android browser)
  2. remount system as read-write
    • mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system
  3. copy and rename busybox.asc to /system/bin/busybox
    • dd if=/sdcard/download/busybox.asc of=/system/bin/busybox
  4. make it executable
    • chmod 4755 /system/bin/busybox
  5. go there
    • cd /system/bin/
  6. this gives you cp (great for making more symlinks)
    • busybox cp -s busybox cp
  7. start sh (this is busybox sh and has more commands and is easier to use)
    • busybox sh

You will not need to create any more symlinks if you plan on installing any recent JF update as he has done this for you.

P.S. If you have adb running you can paste this in to do all of the previous commands at once (much faster).


1. mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system 
2. dd if=/sdcard/download/busybox.asc of=/system/bin/busybox 
3. chmod 4755 /system/bin/busybox 
4. cd /system/bin/ 
5. busybox cp -s busybox cp 
6. busybox sh




Login:

If you've read the previous posts, you should have Busybox running on the phone. That means a proper shell (Ash), and plenty of Unix utilities to play with. Good.
But that's still not quite what we are looking for. We'd like to be able to store our aliases in a 
.profile startup file. We'd like to add our own stuff to the startup process. We'd like to feel at $HOME on our Android.

So we're going to do just that ! But as we've seen already, Android is not built to do that out of the box : no/etc/passwd, no $HOME, and a strange startup script. Let's have a look.

Passwd and Group

First thing : we should add a passwd and a group file in /etc. The problem, as you might have noticed, is that etc is not in your ramdisk directory. It is not in ramdisk.img, but rather in system.img. Actually, /etc is just a symlink to /system/etc(talk about crazy file system hierarchy !). Since modifying system.img is a bit more difficult than building a cpio archive, we too are going to play the symlink game.

Let's put our files somewhere (I've chosen /usr/share), and symlink to them from /etc.

cd my_ramdisk_dir mkdir -p usr/share cd usr/share echo root::0:0:root:/home:/bin/ash > passwd echo root::0: > group cd ../.. find usr >> ramdisk_list

Modifying the Startup Script

In order to make all our symlinks, we have to modify the startup script. This script is called init.rc, and is part of the ramdisk. Let's edit this init.rc file. The % … % comments are mine, and I'll show you the context of my edits, so you can patch :

% Let's add a tmp and home directory. Home should be in a "permanent" storage place, in /data. /tmp should not. % # Backward compatibility symlink /system/etc /etc symlink /data/local /home symlink /cache /tmp % Modify these mount commands to have everything in rw, not ro % mount rootfs rootfs / rw remount mount yaffs2 mtd@system /system rw remount % Add this before the "on boot" block. This creates the symlinks % # add special persistent config files symlink /usr/share/passwd /system/etc/passwd symlink /usr/share/group /system/etc/group

An finally, let's create our own rc startup script, to be run at the end of all other scripts. At the end of the init.rc file, add this line :

service rc /bin/rc

Profiler

Android startup shell comes with some global variables that should be carried over to our shell. We should also configure$PATH. So we are going to create a profile file in /etc. In your ramdisk dir, in usr/share, create a file named profile with this content :

export ANDROID_ROOT=/system export LD_LIBRARY_PATH=/system/lib export PATH=/bin:/sbin:/system/sbin:/system/bin:/system/xbin export BOOTCLASSPATH=/system/framework/core.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar export ANDROID_BOOTLOGO=1 export ANDROID_ASSETS=/system/app export EXTERNAL_STORAGE=/sdcard export ANDROID_DATA=/data export ANDROID_PROPERTY_WORKSPACE=9,32768

Only PATH is important here. All the other variables were already set up in the Android shell (you can check by typing setafter connecting with adb shell). I've found that the network does not work if ANDROID_PROPERTY_WORKSPACE is not set up properly. Check that the number I give is the same as the one you have.
Then add a line in 
init.rc to create the symlink. And add usr/share/profile to ramdisk_list.

You will also be able to create your own .profile file in your $HOME directory on Android. You can strore your aliases and variables there, since /home has been symlinked to a /data subdirectory, and is persistent across reboots.

Testing

You can now rebuild the mydisk.img ramdisk, using cpio. Then start the emulator with this ramdisk. Log in with adb shell. If everything went fine, you should be able to login using /bin/login. The username is root, no password (you can change your /etc/passwd file if you want one).

Voila ! a real login shell, with properly set up variables and a $HOME to live in.





The Six Million Dollar LibC

AndroidToday, Gentle Reader, we will examine the Bionic library, a slim libc developed by Google for use in the Android mobile software platform. Bionic is clearly tailored for supporting the Android system, but it is interesting to see what might be done with it in other embedded system contexts.

Google's stated goals for Bionic include:

  1. BSD license: Android uses a Linux kernel, but they wanted to keep the GPL and LGPL out of user space.
  2. Small size: glibc is very large, and though uClibC is considerably smaller it is encumbered by the LGPL.
  3. Speed: designed for CPUs at relatively low clock frequencies, Bionic needs to be fast. In practice this seems to drive the decisions of what to leave out, rather than any special Google pixie dust to make code go fast.

In this article we'll delve into the Bionic libc via source inspection, retrieved from the git repository in October 2008. The library is written to support ARM CPUs, though some x86 support is also present. There is no support for other CPU architectures, which makes it a bit inconvenient as all of my current systems are PowerPC or MIPS. Nonetheless I'll concede that for the mobile phone market which Bionic targets, ARM is the only architecture which matters.

As one might expect for a BSD-licensed libc, a significant amount of code is sourced from OpenBSDNetBSD, and FreeBSD. Additional BSD-licensed bits come from Sun and public domain code like the time zone package. There is also a significant amount of new code written by Google, particularly in the pthread implementation.


 
C++ support

So what is different about the Bionic libc versus glibc? The most striking differences are in the C++ support, as detailed in the CAVEATS file:

  • The Bionic libc routines do not handle C++ exceptions. They neither throw exceptions themselves, nor will they pass exceptions from a called function back through to their caller. So for example, if the cmp() routine passed to qsort() throws an exception the caller of qsort() will not see it.
     
    Support for C++ exceptions adds significant overhead to function calls, even just to pass thrown exceptions back to the caller. As Android's primary programming language is Java, which handles exceptions entirely within the runtime package, the designers chose to omit the lower level exception support. C++ code can still use exceptions internally, so long as they do not cross a libc routine. In practice, it would be difficult to actually guarantee that exceptions never try to transit a library routine.
  • There is no C++ Standard Template Library included. Developers are free supply their own, such as the free SGI implementation.

Lack of exceptions is obviously a big deal for C++ programmers, but nonetheless we'll push on.


 
libpthread

The pthread implementation appears to be completely new and developed by Google specifically for Android. It is, quite deliberately, not a complete implementation of POSIX pthreads. It implements those features necessary to support threads in the Dalvik JVM, and only selectively thereafter.

In other embedded Linux environments, the pthread library is crucial. There are a large number of developers in this space from a vxWorks background, to whom threads are simply the way software should be written. So we'll spend a bit more time delving into libpthread.

  • Mutexes, rwlocks, condvars, etc are all implemented using kernel futexes, which makes the user space implementation impressively simple. It seems a little too simple actually, I intend to spend a bit more time studying the implementation and Ulrich Drepper's futex whitepaper.
  • There is no pthread_cancel(). Threads can exit, but can not be killed by another thread.
  • There is no pthread_atfork(). This routine is useful if you're going to fork from a threaded process, allowing cleanups of resources which should not be held in the child. I've mostly seen pthread_atfork() used to deal with mutex locking issues, and need to study how the use of futexes affects fork().
  • Thread local storage is implemented, with up to 64 keys handled. Android reserves several of these for its own use: the per-thread id and errno, as well as two variables related to OpenGL whose function I do not understand. Interestingly the ARM implementation places the TLS map at the magic address 0xffff0ff0 in all processes. This technique is presumably part of the Google performance enhancing pixie dust.
  • POSIX realtime thread extensions like pthread_attr_{set,get}inheritsched and pthread_attr_{set,get}scope are not implemented. Frankly I've never worked on a system which did implement these APIs and am completely unfamiliar with them, so I don't find their omission surprising.

I haven't drawn a final conclusion of the Bionic pthread implementation yet. It is pleasingly simple, but lack of pthread_atfork() is troublesome and use of a magic address for the TLS map may make porting to other architectures more difficult. I need to get this puppy running on a PowerPC system and see how well it works.


 
Miscellaneous notes

In the course of digging through the library I generated a number of other notes, which don't really clump into categories. So I'm simply going to dump it all upon the Gentle Reader, in hopes that some of it is useful.

  • The README says there is no libm, though the source for libm is present with a large number of math routines. I need to investigate further whether it really works, or whether the README is out of date.
  • There is no wchar_t and no LOCALE support. I think this is fine: wchar_t is an idea whose time has come... and gone. The world has moved on to Unicode with its various fixed and variable width encodings, which the wide character type is not particularly useful for. 
    I've used ICU in recent projects for internationalization support, and this is also what Google suggests in the README for Bionic.
  • There is a shared memory region of configuration properties. For example, DNS settings are stored in shared memory and not /etc/resolv.conf. The Android API also makes this shared memory configuration store available to applications via property_get() and property_set().
  • As one might expect, the stdio/stdlib/string/unistd implementation comes from OpenBSDNetBSD, and FreeBSD with minimal changes. The only change I noticed was to remove the LOCALE support from strtod() (i.e., is the decimal point a period or a comma? In the Bionic library it is always a period).
  • There is no openlog() or syslog() implementation. There is a __libc_android_log_print() routine, to support Android's own logging mechanism.
  • Bionic uses Doug Lea's malloc, dlmalloc. Bionic also provides a hash table to track allocations looking for leaks, in malloc_leak.c.
  • There is no pty support that I can find, and no openpty(). There are reports of people starting an SSH daemon on a jailbroken Android device, so presumably there is some pseudo-terminal implementation which I've missed.
  • There are no asynchronous AIO routines like aio_read() or aio_write().
  • Bionic contains an MD5 and SHA1 implementation, but no crypt(). Android uses OpenSSL for any cryptographic needs.
  • Android dispenses with most file-based Unix administration. Bionic does not implement getfsent, because there is no /etc/fstab. Somewhat incongruously there is a /var/run/utmp, and so getutent() is implemented.
  • Android implements its own account management, and does not use /etc/passwd. There is no getpwent(), and getpwnam()/getpwuid() are implemented as wrappers around an Android ID service. At present, the Android ID service consists of 25 hard-coded accounts in <android_filesystem_config.h>
  • Bionic isn't finished. getprotobyname(), for example, will simply print "FIX ME! implement getprotobyname() __FILE__:__LINE__"
  • There is no termios support (good riddance).

 
Conclusion

Bionic is certainly interesting, and pleasingly small. It also represents a philosophical outlook of keeping the GPL some distance away from the application code.

Bionic is a BSD-based libc with support for Linux system calls and interfaces. If the lack of C++ exceptions or other limitations prove untenable, the syscall and pthread mutex implementation could be repurposed into the heavier FreeBSD/NetBSD/OpenBSD libc, though handling thread cancellation using the Bionic mutexes could require additional work.


 
Postscript

If you don't understand the reference in the title of this article, don't fret: you have simply not watched enough bad 1970's American television.

Update: In the comments, Ahmed Darwish points out another Android-related article discussing the kernel and power management interfaces Google added.

Update2: Embedded Alley is working on a MIPS port of the Android software.

Update3: In the comments Shuhrat Dehkanov points out an interview with David Turner, who works at Google on the Bionic implementation. Shuhrat also notes that you might have to log in to Google Groups to see the attachment. "Here is an overview by David Turner (though non-official) which answers some of the questions/unclear parts in your article."

Posted by kevino
,

Original Post: 
http://i-miss-erin.blogspot.com/2009/04/android-trace-radio-interface-layer-ril.html

[android] trace radio interface layer (RIL) by two emulators

I study android from this week and my entry point is based on my related GSM network experiences. Yeah! Let's start it from code tracing: how to register to the network, how to receive/dial a phone call, how to send/receive a SMS message...etc...

A. Set up the working environment: my machine is ubuntu 8.10, kernel is 2.6.27-11-generic.

1. download Android SDK
unzip the file, and you will see theses two tools ( emulator & adb) we need.

2. download Android source code 
just follow the steps, and type 'make', then i get it all done. (yes, i'm a lucky person!)

B. Let's have fun with multiple emulator:
1. prepare two terminals:

terminal A: $emulator -skin HVGA-P -data lib/images/userdata.img -debug modem,radio -scale 0.5
terminal B: $emulator -skin HVGA-L -data lib/images/userdata2.img -debug modem,radio -scale 0.5

2. it would come out with two emulators: (I changed one of them to use iPhone skin!)

3. When both of them camp to the 'Android' network, use Dialer in emulator-5554 and dial '5556', then it would display an incoming call in emulator-5556. (5554 and 5556 are their port number)
 

4. Answer the incoming call in emulator-5556 and then hang up in emulator-5554. (You will receive different events if you hang up in emulator-5556.)

5. DONE! Let's get the log date from both of them.

$adb -s emulator-5554 logcat -b radio -d > radio.5554
$adb -s emulator-5556 logcat -b radio -d > radio.5556
$adb -s emulator-5554 logcat *:D -d > debugall.5554
$adb -s emulator-5556 logcat *:D -d > debugall.5556


C. Check the RIL process by these photos



D. How to dial out a call in Android? I traced the radio log and make sure the whole procedure and the source code.
DIAL out a phone call: (MO call)

from top UI to bottom,
[App] Phone Application ---> [App Framework] Telephony Manager (GSM)  --->
[App Framework] Telephony Manager (RIL) ---> [Libraries]  Telephony Manager
---> [Libraries] rild    ---> [Libraries] libril.so ---> [Kernel Driver] Baseband

RIL
:  /hardware/ril/reference-ril/refereince-ril.c
AT
:   /hardware/ril/reference-ril/atchannel.c
RILD
: /hardware/ril/rild/rild.c
RILC
: /hardware/ril/libril/ril.cpp
RILJ
: /frameworks/base/telephony/java/com/android/internal/telephony/gsm/RIL.java
GSM
:  /frameworks/base/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java

D
/RILJ    (   85): [0053]> DIAL
D
/RIL     (   22): onRequest: DIAL
D
/AT      (   22): AT> ATD5556;
D
/AT      (   22): AT< OK

D
/GSM     (   85): [GSMConn] update: parent=DIALING, hasNewParent=false, wasConnectingInOrOut=true,
wasHolding
=false, isConnectingInOrOut=true, changed=false
D
/RILJ    (   85): [UNSL]< CALL_STATE_CHANGED
D
/AT      (   22): AT< RING
D
/RILJ    (   85): [UNSL]< CALL_STATE_CHANGED
D
/RILJ    (   85): [0059]> SET_MUTE false
D
/RIL     (   22): onRequest: SET_MUTE
D
/RILJ    (   85): [0059]< SET_MUTE error: com.android.internal.telephony.gsm.CommandException:
REQUEST_NOT_SUPPORTED
D
/RILJ    (   85): [0060]> GET_CURRENT_CALLS
D
/RIL     (   22): onRequest: GET_CURRENT_CALLS
D
/AT      (   22): AT> AT+CLCC
D
/AT      (   22): AT< +CLCC: 1,0,3,0,0,"5556",129
D
/AT      (   22): AT< OK

D
/RILJ    (   85): [0124]< GET_CURRENT_CALLS  [id=1,mo,ACTIVE,voice,norm,129,0]
D
/GSM     (   85): [GSMConn] update: parent=ACTIVE, hasNewParent=false, wasConnectingInOrOut=
false, wasHolding=false, isConnectingInOrOut=false, changed=false
D
/RILJ    (   85): WAKE_LOCK_TIMEOUT  mReqPending=0 mRequestList=1
D
/RILJ    (   85): 0: [14] SET_NETWORK_SELECTION_AUTOMATIC
D
/GSM     (   85): [CallTracker] hangupForegroundResumeBackground
D
/RILJ    (   85): [0125]> HANGUP_FOREGROUND_RESUME_BACKGROUND
D
/RIL     (   22): onRequest: HANGUP_FOREGROUND_RESUME_BACKGROUND
D
/AT      (   22): AT> AT+CHLD=1
D
/AT      (   22): AT< OK


PS. Above logs are all from emulator-5554! ATD: dial command in modem, AT+CLCC: List current calls, AT+CHLD: Releases all active calls
Posted by kevino
,

원 주소: http://jovechia.blogspot.com/2009/04/how-to-use-gdbserver-on-android.html

How to use gdbserver on android

How to debug c++ library by gdbserver.

1. get and build cupcake
Any issues, please refer sources.android.com

2. make you library debugable (add -g options in makefile)
modify your Android.mk add below command "LOCAL_CPPFLAGS += -g" for C++ files and "LOCAL_CFLAGS += -G" FOR C files.
rebuild your library and system image

3. redirect debug port
$ telnet localhost 5554
redir add tcp:1234:1234
exit
current release will fail if you redirect in this step, hope final cupcake will fix it.
you can start emulator by below command with debug port redirected.
./emulator @jove -qemu -redir udp:1234::1234

4. push gdbserver to emulator
adb push ./out/target/product/generic/obj/EXECUTABLES/gdbserver_intermediates/gdbserver /data/local


5. run /data/local/gdbserver 10.0.2.2:1234 --attach your-desired-pid

6. run ./prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin/arm-eabi-gdb ./out/target/product/generic/symbols/system/bin/app_process
set solib-search-path out/target/product/generic/symbols/system/lib
target remote localhost:1234
b xxx.cpp:xx
7. enjoy debuging and life :)
Posted by kevino
,
  • 경제토론 [윤상원]◆아마겟돈! 이렇게 오고있다! 
  • 부화뇌동 youngwo**** 부화뇌동님프로필이미지
  • 번호 785161 | 09.10.04 09:25 IP 119.194.***.125
  • 조회 2839 주소복사

이런 한정된 시간과 지면에 35년 이상을 부동산으로 바닥을 긁어 부동산으로 일어난 나의 느낌과 경험을 어찌다 설명을 할 수 있을 지 모르겠다.

 

나도 경제학부를 전공하고 졸업 후에도 경제학에 심취되어, 만사 팽겨 치고 도서관에 틀여 박혀 1년 반 이상을 경제학만 연구 했던 시절이 있었던 사람이다. 그러다 휴게실에서 어느 잡지를 뒤적이다가 “경제는 심리” 라는 문구에, 아무리 내가 경제학의 대가가 된다 손 치더라도 “경제는 심리” 인 이상 그것은 사기꾼 이상은 될 수가 없다는 판단에 때려 치고 말았단다.

여기 경제학도 에게는 미안한 말이지만 경제학의 대가가 되면, 자본주의 체제하에서는 재벌, 금융자본가 들의 딱가리가 안 되고서는 절대 출세 할 수가 없다는 걸 알아야 한다. 마치 미국의 가이트너, 버냉키, 한국의 정운찬, 강만수, 윤증현 같이.....

 

인생 두 번도 아니고, 한 번 사는 것인데 상기한 인간들 같이 딱가리 짓 하다가 죽어서 흡혈귀가 될 수는 없는 것 아니겠나? 그래서 때려 친 것이지. 단 하루를 살더라도 주인공으로 살다 가야지. 이 사회의 진실 그 자체인 서민대중의 피 같은 돈을 저들에게 토끼몰이 하듯 몰아주는 대가로 손에 팥고물 묻히려고 아등바등 대며 살 바에는, 차라리 안 살고 말지. 그래서 때려 친 것이지. 그래서 부동산으로 길을 바꾼 것이지.

 

• 경제는 흐름(대세)이다.

 

그래서 하는 말인데, 상기한 딱가리 들은 흐름(대세, 거시경제)을, 수시로 뱀의 혓바닥을 놀려(미시경제) 착시 현상을 일으키려고 수작 부리는 것이 저들의 주특기지. 그 때마다 자산시장이(주식, 부동산) 요동치게 되는 것이지. 고로 루비니 같은 현자는 절대 미시경제는 언급하지 않고 늘 거시경제만 언급 하는 것이지.

한번 잡힌 대세는 절대로 완벽한 대가를 치루기 전에는 멈출 수가 없는 것이란다.

마치 노무현이가 부동산 값을 잡으려고 별의별 정책을 다 써도 결국에는 폭등하고 말았듯이,.....

 

역으로 말해서 거품 그 자체로 대통이 된 멍바기가 아무리 용을 써도 세계 부동산의 대세가 폭락세로 돌아선 이상에는 한국도 폭락할 수밖에 없다는 말이지.

내가 자꾸 아파트를 까대기 치는 것은, 이왕 폭탄돌리기에 물린 사람은 버린 자식이고, 순진한 실수요자들이라도 더 이상 어마어마한 아파트 왕거품의 폭팔로 인한 피해를 막고자 함이지.

 

외국의 경우 전부 단독 주택 위주인데도 40%~50% 이상 꼬라박혔거든? 그런데 울 나라 단독 주택은 거의 미동이 없거든? 강남 일대 단독 주택 시장을 보아도 약 3~ 5% 정도 밖에 하락을 안했거든? 그런데 아파트는 약 20%~30% 정도 하락 한 것으로, 정체 상태로 들어갔다가 요 며칠 새 다시 하락세로 돌아섰거든? 주상복합은 40%~ 55% 정도 폭락 했지만....

http://bbs1.agora.media.daum.net/gaia/do/debate/read?bbsId=D125&articleId=143090&hisBbsId=best&pageIndex=1&sortKey=&limitDate=-30&lastLimitDate=

 

  그렇다면 net work 세계 경제 체제에 발 맞춰, 울 나라 단독 주택도 40% 정도 하락 한다면 아파트는 얼마나 핵 폭락 할까? 계산은 여러분들이 직접 함 해보도록......

내가 단언 하건데 아파트 까라는 이번 금융위기 내에 3토막은 필수고, 2012~2014년 안으로 아파트 과잉공급+인구감소+고층아파트 재건축 사례로 오는 아파트 트라우마 발발= 4~5토막 정도는 선택이 될게 확실 하단다. 즉 아파트는 중산층이 아닌, 선진각국의 예처럼, 아파트의 애초 탄생 목적인, 서민 대중들이 얼마든지 만만하게 소유할 수 있을 정도의 값으로 회귀 할 수밖에 없다는 말이란다. 이는 멍바기, 찌라시, 토건족, 들이 아무리 몸부림쳐도 절대 막을 수 없는 “원심력의 법칙” “회귀 본능의 법칙” 이란다.

 

• 경제는 함정이다.

두고 봐라 주식시장이 어떻게 무너질 것인 지를, 주식 시장은 원래 개미들을 함정에 빠뜨려 그들의 피를 먹고사는 캐 막장 시장이란다. 옛날 현자였던 타고르가 "동방의 불빛, 해뜨는 나라" 라고 칭송했던 한국이 “해뜨는 나라 그 자체” 이기 때문에, 맬 맬 주식시장이 세계 최초로 열리는 관계로, 국제자본인 노란 토깽이 푸른 토깽이 들의 작전 개시장으로 활용되고 있단다. 이런 지경(地經)학적인 취약점이 있는데도 멍청한 놈들이 주식시장에 40조 원씩이나 유동성을 추가로 풀어 놓은 데다가, 환율 조작까지 해 놨으니, 외국인 뱀의 혓 바닥들이 수시로 “세계에서 젤 먼저 금융위기에서 빠져 나올 나라가 한국” 이라고 음흉하게 알랑 방귀 뀌며, 쥐 닭 잡아먹듯이 똥집 먼저 야금야금 파먹고 있단다.

 

경제의 경자도 모르는 멍바기는, 뭔 G20 갖다 올 때마다 그들의 음흉한 알랑방귀에 뿅가서 헬렐레 하고 있지만 서두

 

내년 경제 성장률이 3% 까지 치고 올라 갈 것이라며 바람 잡고 있지만....

 

이 말도 앞 토막 뒷 토막 다 잘라먹고 가운데 토막만 낼름거리는 수작질이란다. 올해 울나라 경제가 마이너스 5% 만 잡고, 대비 3% 성장이라면 내년에도 -3.5% 성장이란다.→기저효과란 말은 쏘~ 옥 뺀채 쌩까는 것이지.

경제성장률은 GDP 성장률을 말한단다. GDP는 국내 재화 총생산의 합계를 뜻한단다. 그렇다면 세계 각국의 물가는 디플레이션으로 떨어졌는데 유일하게 우리나라만 물가가 폭등했자나! 나의 느낌으로는 최하 40% 이상 물가가 폭등한 것 같은데, 그렇다면 울 나라 재화의 총생산도, 즉 GDP, 다시 말해서 재화생산의 총합계인 경제성장률도 40% 는 돼야지 되는 것 아닌가? 그런데 마이너스 3.5% 성장뿐 이라면 얼마나 살 떨리는 일인지 상상을 할 수 조차 없네 그려 zzz

 

원래 나 열 받으면 과잉 표현도 서슴치 않고 하는 성격이란다. 왜? 이 에는 이 눈 에는 눈 이니까. 또 이런 기질이 없이는 노가다 왕초 노릇을 해 먹지도 못했을 게야. 그러니까 살 떨리는 성장률이라고 말한 것은 걍 참조로만 활용 하시게나.

이런 수법은 찌라시들, 삐,뀌 내각한테 배운 것이 거든?, 그러나 난 항상 진실을 바탕으로 과잉 표현 방법을 아주 가끔씩 써먹지만 서두. 주야장창 쌩으로 까는 놈들 하고는 차원이 틀리지 안 그래? zzz

 

이나 저나 내년이 참으로 걱정되는구먼?

 

올해 최고로 실적이 좋은 삼성전자 영업이익이 시가 총액 대비 0.7%. 0.7% 라는 영업이익은 단군 이래 최저 수준인 우리나라 기준금리의 1/3 밖에 안 되는 상황이고, 그것도 영업이익 아닌, 경상이익으로 파고 들어가면 엄청난 적자를 낸 것으로 추정되는 삼성전자가 올해 최고의 기업이라면 나머지는 생각 할 것도 없이 전멸 그 자체 일 것은 뻔할 뻔자 인데...

이참에 내 컴에 저장된 09년 4월 현재 울 나라 10대 재벌 기업 그룹 군의 재무 구조를 한 번 살펴보자꾸나. 6개월이 지난 지금은 더 악화 됐을 게야, 이들 기업은 지난 환란을 거치면서 뼈아픈 구조조정으로, 07년 당시까지 만 해도 부채 비율이 80% 전후였는데, 지금 리먼 사태를 거치면서 이들 재무구조는 한마디로 빚을 내어 빚으로 지탱한 흔적이 여실히 드러나고 있단다.

그래도 가장 신빙성이 있다는 공정위와 경제개혁연대 자료를 인용했다. 부채 비율이 200% 넘기는 순간 외국에서는 정크 펀드 수준으로 취급 받는 기업들 중 몇 개만 추려 보겠다.

 

삼성테스코 941%, 지엠대우 741%, 대우조선해양 632%, 현대중공업 324%, 대한전선 248%, 동양 244%, 한진 243%, 동부 237%, 코오롱 228%, 두산 204%, STX 202%, 금호아시아나 269%........ → 이중 금호아시아나는 간당간당, 지엠대우와 대우조선해양은 산소호흡기로 간신히 안락사 준비 중... 나머지는?

매분기 수천억 원~수조 원 이상의 적자를 내면서, 빚 투바기로 변한 이들 기업, 지금까지는 사내 유보금과, 고금리 급전인 회사채 발행으로 연명해온 이들 기업의 임계점은 올 하반기~내년 상반기 이상은 넘길 수 없을 것이라는 게 나의 감각인데. 여러분의 감각도 비슷 하겠지 그치? 여기 삐, 뀌들은 워낙에 낙천적이고 싶은 척 하는 사람들이니까. 제외하고,

그렇다면~

내년에는 어쩔 수 없이 끔찍한 구조조정의 해가 될 것이고,→ 이로 인해 2차 폭락이 개시 될 것이며→ 이로 인해 아파트 담보가치의 추가 하락으로 한국판 서브가 발발 될 것이며→ 이로 인해 3차 폭락이 개시 될 것이며→ 이로 인해, 외국인 백마들의 대탈출이 시작 되는 해가 될 것이며,→ 이로 인해 아마겟돈의 핵 폭락 시대가 도래 할 가능성이 거의 99% 란다.

만일 이런 피할 수 없는 절차를 멍바기가 강제로 봉쇄 한다면? ㅋㅋㅋ

피를 절절히 흘리면서 자기 팔, 다리 자르는 처절한 구조조정을 끝낸 노란 토끼, 푸른 토끼들이 우리를 통째로 잡아먹으러 달려 올 것이란다. 이런 사태가 온다면 핵 폭락이 아니라 광(光) 폭락 하고 말 것이란다.

 

고로 다른 나라가 자산의 디플레이션 상태에 들어갈 때 우리도 같이 자산의 디플레이션 상태로 따라 들어가 줘야지만 살아남는 유일한 방법인데, 조옷도 모르는 놈이, 아는 것이라고는 거품 밖에 없는 놈이. 게다가 주어까지 없는 놈이, 경제를 떡 주무르듯이 하고 있으니.... 훤하다 훤해

 

실수요자 여러분! 아시는 분은 아시겠지만 지금의 상황은 꼭! 89년도 일본의 상황과 판박이입니다.

1985년 미국의 무역적자 해소를 위해 미국과 일본이 뉴욕 플라자 호텔에서, 플라자 협약 체결, 엔화 강세 유지→ 엔화가치 상승으로 수출 실적 대 하강→수출 대기업 돕기 위해 기준금리 대폭 낮춤→ 저 금리로 1986년부터 버블 발생시작→ 1989년 1차 버블 붕괴로 약 30% 폭락→ 일본정부 붕괴를 막기 위해 제로금리 실시, 모든 부동산 규제 철폐, 그 당시 일본의 1년 치 GDP 에 해당하는, 무려 현행 환율로 2000조원 투입 → 정확히 24개월 동안 소강상태 진행→ 1991년 2차 대폭락 개시! 이후 무려 4차에 걸친 대 폭락을 거쳐 일본 부동산이 평균 87% 핵 폭락!→ 막대한 재정 적자와 인구 감소로 그 후 20년 동안 계속 하락

 

이게 다 멍바기와 같은 토건 족 출신인 다나까 수상 작품이었거든? 하여간에 우리는 영원한 일본의 데자뷰 라니까 그러네...

 

어떻습니까? 일본의 89년 상황과 판박이 아닙니까? 우리가 역사를 왜 배우겠습니까?. 그건 역사는 반복되기 때문이죠?

 

은행아! 니들 지금 떨고 있지 그치? 구조조정이라 하지 마라 통곡 소리라고 해라!!

 

세상에 꽁짜가 어디 있노? 원고료 추천으로 내놔!!

 

-윤상원-


Posted by kevino
,

[First written by Steve Guo, please keep the mark if forwarding.]

http://letsgoustc.spaces.live.com/?_c11_BlogPart_BlogPart=blogview&_c=BlogPart&partqs=amonth%3d8%26ayear%3d2009


Assume your target board's IP address is 192.168.1.101. Your host dev machine's IP address is 192.168.1.100. Your Android source code is in ~/mydroid.

In the target board, you should do the following things.

1. Make sure you have replaced libc.so with the version containing symbol information. (You should copy ~/mydroid/out/target/XXX/symbols/system/lib/libc.so), otherwise you will met issue when debugging multi-thread app. Because libthread_db.so depends on a _thread_created_hook symbol in libc.so.

2. Copy ~/mydroid/prebuilt/android-arm/gdbserver/gdbserver into board rootfs.

3. You can launch gdbserver by the following two commands:

#gdbserver 192.168.1.101:5544 --attach $(PID)

#gdbserver 192.168.1.101:5544 $(YOUR_APP)

The first command is to debug an already run process, the second command is to debug a new process. 5544 is a random port you can use any.

In the host develop machine, you should do the following things.

1. Add ~/mydroid/prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin into $PATH so that you can directly use arm-eabi-gdb.

$export PATH=$PATH:~/mydroid/prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin

2. launch arm-eabi-gdb and in the gdb shell environment, type the following commands:

(gdb) set solib-search-path ~/mydroid/out/target/product/avlite/symbols/system/lib:~/mydroid/out/target/product/avlite/symbols/system/bin

(gdb) target remote 192.168.1.101:5544

3. The remaining things is how you use gdb, it's not covered in this topic.

Note:

There are the following know issues now:

1. n and s does not work now for multi-thread app.

2. p does not work correctly for C++ symbol.

Posted by kevino
,
How to debug linux application on beagle board using single com port 
------------------------------------------------------------- 

1. Install the compiler for arm linux 
===================================== 
ARM Linux GCC - codesourcery tool chain (Select GNU/Linux and download 
version 2007q3) 
download from: http://www.codesourcery.com/gnu_toolchains/arm/portal/release313 
297209683 Aug 11 11:08 arm-2007q3.tar.bz2 
and install 
so you could compile using the arm compiler using the command line: 
"arm-none-linux-gnueabi-gcc" 
(complete info at: http://code.google.com/p/beagleboard/wiki/BeagleSoftCompile

2. u-boot 
========= 

You need u-boot to be automated, for that recompile the u-boot after 
doing the following changes in 
the file ./include/configs/omap3530beagle.h 

        #define CONFIG_BOOTCOMMAND "mmcinit;fatload mmc 0 0x80300000 
uImage;fatload mmc 0 0x81600000 rd-ext2.bin;bootm 0x80300000;\0" 

        #define CONFIG_BOOTARGS "setenv bootargs console=ttyS1,115200n8 
ramdisk_size=8192 root=/dev/ram0 rw rootfstype=ext2 
initrd=0x81600000,8M nohz=off" 

and from /board/omap3530beagle/omap3530beagle.c 
comment the following two lines at the end of the function 
misc_init_r() 
        //      dss_init(); 
        //      audio_init(); 

Compile the u-boot to generate the u-boot.bin file 
        make CROSS_COMPILE=arm-none-linux-gnueabi- distclean 
        make CROSS_COMPILE=arm-none-linux-gnueabi- omap3530beagle_config 
        make CROSS_COMPILE=arm-none-linux-gnueabi- 

more info at: 
http://code.google.com/p/beagleboard/wiki/BeagleSoftCompile 

3. MLO 
====== 
MMC is the first step of the MMC based bootloader 
I did not bother to compile it, just downloaded it from: 
http://code.google.com/p/beagleboard/wiki/BeagleSourceCode (and rename 
MLO_revb to MLO) 

4. Kernel 
========= 
Download kernel from same place as above: Linux Kernel 2.6.22.18 
and compile it using: 
        make CROSS_COMPILE=arm-none-linux-gnueabi- distclean 
        make CROSS_COMPILE=arm-none-linux-gnueabi- omap3_beagle_defconfig 
        make CROSS_COMPILE=arm-none-linux-gnueabi- uImage 
or just use the compiled one from: 
http://code.google.com/p/beagleboard/wiki/BeagleSourceCode  (don't 
forget to rename it, if needed, to: uImage) 

5. The RAM files system (busybox) 
================================= 

download BusyBox (ramdisk) File System from the same place as above. 
filename: rd-ext2-8M.bin and rename it to rd-ext2.bin 

Changing the ramdisk to have it autostart the gdbserver: 
        cat rd-ext2-8M.bin | gunzip > myimagem 
        mkdir /mnt/tmp 
        mount myimage /mnt/tmp -t ext2 -o loop=/dev/loop3 

Now the full image is under /mnt/tmp, do the following changes there: 
change inside /mnt/tmp/etc/inittab 
from: 
        ::askfirst:-/bin/sh 
to: 
        ::respawn:-/bin/sh 
this is to avoid asking for the prompt "press..." on boot 

and at the end of the file /mnt/tmp/etc/profile add: 
        mount -t vfat /dev/mmcblk0p1 /mnt/mmc/ 
        cd /mnt/mmc 
        ./ycomarm /dev/ttyS2 
        ./gdbserver /dev/ttyS2 hello2 
This is to mount the mmc, and run gdbserver and have it ready to debug 
the hello2.c program 

Now pack the image back, and create a new rd-ext2.bin file 
        umount myimage  (before doing that, do cd to a different location) 
        cp myimage qqq 
        gzip qqq 
        rm rd-ext2.bin 
        mv qqq.gz rd-ext2.bin 

6. compiling the gdbserver and gdb for arm 
========================================== 

download the latest gdb-6.7.1.tar 
wget -c ftp://ftp.gnu.org/gnu/gdb/gdb-6.7.1.tar.bz2 

Place the downloaded file in /usr/src directory of your system. 
Under /usr/src, create a debug directory and extract the gdb package 
in this 
(/usr/src/debug) directory. 

[root at localhost]# cd /usr/src/debug 
[root at localhost]# tar jxf ../gdb-6.7.1.tar.bz2 

Build gdb debugger 

The debugger must be built into directories separate from the source. 
Thus, 
create a directory for gdb within the /usr/src/debug directory. 

[root at localhost]# mkdir /usr/src/debug/build_gdb 

Chose the prefix for the new debugger. This is a directory where the 
binary 
and other debugger files resides. This application report uses /opt/ 
gdebug 
for the new debugger. The directory is created by the installation of 
the 
tools. Go to the /usr/src/debug/gdb-6.3 directory to configure and 
then 
build the binary and other debugger files with the commands shown 
below. 

[root at localhost]# cd /usr/src/debug/build_gdb 
[root at localhost]# ../gdb-6.7.1/configure --target=arm-linux -- 
prefix=/opt/gdebug 
[root at localhost]# make 
[root at localhost]# make install 

The binary generated resides in /opt/gdebug and is fairly large. This 
is why 
the gdb binary can't be used as-is on the target and the gdbserver is 
used 
instead. 

Build gdb server 

The gdb server wasn't built earlier because it has to be cross- 
compiled for 
the target using the appropriate tools. To do so, create a directory 
to 
build the gdb server, move to it and build the gdb server: 

[root at localhost]# mkdir /usr/src/debug/build_gdbserver 
[root at localhost]# cd /usr/src/debug/build_gdbserver 
[root at localhost]# CC=arm-none-linux-gnueabi-gcc ../gdb-6.7.1/gdb/ 
gdbserver/configure 
--host=arm-linux --prefix=/opt/gdebug/arm-linux 
[root at localhost]# make 
[root at localhost]# make install 

The gdb server binary, 'gdbserver', has now been installed in your 
/opt/gdebug/arm-linux/bin directory. 

Once built, copy gdbserver to the MMC 

7. utility to setup the serial port 
=================================== 
compile ycom.c for both ARM and your PC using: 
arm-none-linux-gnueabi-gcc -o ycomarm ycom.c 
gcc -o ycom ycom.c 

This utility is used to setup the proper serial configuration BEFORE 
running gdb or gdbserver, and you can download it from: 
http://www.magniel.com/yuli/ycom.c 

8. Compiling the demo program hello2.c 
===================================== 
arm-none-linux-gnueabi-gcc -o hello2 hello2.c 
You can download it from: http://www.magniel.com/yuli/hello2.c 

9. Booting from MMC 
=================== 
Format MMC to FAT32 (use: HP MMC/SD Disk Format Tool) SP27213.exe 
Copy the following files to the MMC: 
MLO 
u-boot.bin   (the one that you modified) 
uImage 
rd-ext2.bin  (the one that you modified) 
ycomarm 
hello2.c 
hello2 
gdbserver 

Connect NULL modem cable to a PC, run hyperterminal: 115200,N,8,1 
Turn power to beagle, while pressing the 'USER' button 
It should run u-boot, and then execute the kernel, and at the end it 
should write: "TEST To send123" 

Connect the cable to a linux machine, login as root. 
Initialize the serial port for the proper speed, then envoke the gdb: 
        ./ycom /dev/ttyUSB1 
        /opt/gdebug/bin/arm-linux-gdbtui helloa 
and inside the gdb write: 
        target remote /dev/ttyUSB1 

you might use different serial port connection, so instead of ttyUSB1, 
the serial for your computer might be ttyS0 or similar. 
You can use the command "dmesg | grep tty" to display all available 
installed serial ports. 

10. Using the visual debugger ddd 
================================= 

download it, compile it, and use the following command line when 
running it: 
        ddd --debugger "/opt/gdebug/bin/arm-linux-gdb" 

Now power up beagle, wait a little (to ensure that the boot finished, 
and that gdbserver started to run), and then on the linux side start 
the debugger: 
        ./ycom /dev/ttyUSB1 
        ddd --debugger "/opt/gdebug/bin/arm-linux-gdb" 
and inside the gdb write: 
        target remote /dev/ttyUSB1 
        file hello2 

The file hello2 should be copied into the mmc. 

Yuli 
yk (at) magniel (dot) com 


Posted by kevino
,
(현재 계속 공사중)

별다른 언급이 없는 한 여기서 언급되는 개발환경은 다음을 의미한다.

호스트 머신: Linux Ubuntu 8.10( VMWARE에서 동작되는 환경 포함)

기본적인 환경은 android cupcake소스가 성공적으로 컴파일되는 것을 가정한다. 이러한 상황이 갖춰지지 않았을 때는 다음을 참조(아직 공사중)

1. 위의 조건하에서 HTC dream폰에 새로운 안드로이드 이미지를 올리기 위한 과정은 다음과 같다.

Step 1: 기본 안드로이드에서 제공되는 기본 명령어를 사용하기 위해 진행되어야 하는 과정
 
export ANDROID_HOME=(안드로이드 소스가 설치되어 있는 루트 디렉토리)
cd $(ANDROID_HOME)
. build/envsetup.sh
lunch htc_dream-eng 또는
lunch generic-eng

--> 여기까지 하면 gdb와 gdbclient와 같은 명령어를 사용할 수 있슴

Step 2:  안드로이드 소스를 이용해 HTC-dream 용 이미지를 만드는 법(cupcake,donut 둘 다 적용 가능)
필요조건: Step1

과정:
cd $(ANDROID_HOME)
make

특정 파일이 없다고 에러가 발생할 경우 HTC-dream 단말기를 USB로 연결한 상태에서
cd vendor/htc/dream-open
./extract-files.sh

-> 여기까지 실행하면 vendor/htc/dream-open/proprietary 폴더에 HTC용으로 컴파일하기 위해 필요한 파일들을 실제 폰으로부터 빼내어 저장하게 된다. 필요한 파일이 모두 받아졌으면 완전한 컴파일을 진행할 수 있다.(간혹 안되는 경우가 있기도 했지만 어떡하든 방법을 찾아서라도 진행해라)
make

--> 여기까지 하면 안드로이드 구동에 필요한 모든 파일이 생성됨

Step 3:  HTC-dream 이미지를 굽는 방법
필요조건: Step1, step2

과정:
A. HTC dream폰의 부트로더를 fastboot가 가능한 버전인지 확인할 것 - 관련 정보 참조(공사중)
B. 전원이 꺼진  드림폰을 이전키를 누른 상태에서 전원을 키면 부트 모드로 전환되고 이상태에서 USB 케이블을 누르고 이전키 또는 카메라키를 누르면 화면에 fastboot모드로 진입했음을 알려주는 내용이 표시된다.
C. 다음을 실행: fastboot flashall
D. 이미지가 다 써지고 자동으로 리부팅되면 원하는 내용으로 적용됨을 확인할 수 있다.



Posted by kevino
,
  • 경제토론 [with윤상원]◆강남구 역삼동 근생빌딩 입찰내역서 공개합니다. [4]
  • 부화뇌동youngwo****부화뇌동님프로필이미지
  • 번호 780011 | 09.09.25 00:04 IP 119.194.***.125
  • 조회 665 주소복사

 출처: https://www.howbuild.com/

 

 

 

 

지하 5237 ㎡ (1587평)

지상 8972  (2719평)

총 13개 업체 입찰

최저가 142억 (지상 평당 522 만원)

최고가 179억 (지상 평당 658 만원)

 

신삥,지하주차장 포함 가격임

 

이상 강남구 역삼동 14층 근생빌딩 2009년 9월 10일 실제 완료된

입찰내역서 공개합니다.

 

 

--------------이하 윤상원님의 주장--------------

 

어떻게 평당 2억 이상을 호가하는 근린 상업지역에 지어진 건물보다, 평당 1700만 원을 호가하는, 일반 주거지에 지은 아파트가 더 비쌀 수 있겠는가? 더구나 사무실 건축비는 아파트 건축비 보다 45% 정도 비용이 더 들어 간단다. 왜?

 

❶ 아파트 골조는 최하층 두께가 18센티에서 시작하여(하중 문제로) 최상층 골조 두께는 15센티로 줄어 든단다. 그러나 근생은 평균 20센티 이상 두께라야 만 한단다. (그 이유는 이하 생략.)

 

❷ 아파트 층간 높이는 2m 80, 슬라브 천장 덴조 마감 후 천장 높이는 2m30 전후(함 재볼 것) 그러나 근생 높이는 3m 40 이상 이란다.

 

❸ 더욱 기가 막힌 것은 아파트는 알 콘크리트로 걍 수성 페인트 마감이란다.(외국은 최하 에나멜 코팅으로 법적 강제 돼있음)→ 산성화된 빗물의 공격으로부터 콘크리트 부식을 철저히 방지 함.

 

 

 

 




Posted by kevino
,

Android Debugging

From OMAPpedia

Jump to: navigation, search

Contents

[hide]

[edit] Eclipse ADT

[edit] Debugging on Zoom2 with Eclipse ADT

The Android Development Tools (ADT) plugin for Eclipse adds powerful extensions to the Eclipse integrated development environment. It allows you to create and debug Android applications easier and faster. Details on ADT can be obtained from http://developer.android.com/guide/developing/eclipse-adt.html.

It is assumed that ADT plugin has already been setup to work with Eclipse environment as described http://developer.android.com/sdk/1.1_r1/installing.html#installingplugin.


Step 1: Unpon installing the ADT plugin for eclipse, Dalvik Debug Monitor Service (DDMS) should have been setup. DDMS configuration should be changed as in below:

 Click on Window->Preferences; Select Android -> DDMS
 Change - ADB debugger base port: 8700; Logging Level: Verbose
 Click on Apply

Step 2: DDMS perspective can now be opened from the eclipse menu via:

 Window -> Open Perspective -> Other -> DDMS; 
 Click on OK

Step 3: Get Eclipse to attach to your Zoom2 board.

 Bootup the zoom2 board and find the IP address of the board. NOTE: If you boot via NFS, then uboot will typically print out the board's IP address to console. 
 Alternatively, from the command shell this can be gathered from /system/bin/netcfg utility.

On the host machine run the following commands from terminal shell:

  export ADBHOST=<IP_ADDRESS_OF_YOUR_ZOOM2_BOARD>
  adb kill-server
  adb start-server

Check if you are now connected to the Zoom2 device by running the following command on the Host Terminal console:

  adb devices

It should output something like:

  emulator-5554 device

This confirms that Zoom2 board is connected. With this setup, you should be able to use Android Debug Bridge, Logcat, DDMS and other tools directly from Eclipse ADT environment for creating your applications for Android on Zoom2.

Step 4: Troubleshooting:

ADB is not in the path, where should I find it?

ADB command line tool is found at: <MYDROID_PATH>/out/host/linux-x86/bin/


[edit] Debugging with GDB and DDD

The user space programs can be debugged using various debug commands). Here are some gnu apps that can be used to ease the debugging of binary files on the android platform. GDB, allows you to see what is going on `inside' another program while it executes -- or what another program was doing at the moment it crashed.


[edit] GDB (the GNU Debugger)

Following are the instructions to enable GDB on Android:

1. Obtain the IP address of the target. This can be found by adding “ip=dhcp” in the bootargs, which will obtain and print the IP automatically during boot. Alternatively if you have the busybox command line tools available on the target you can type "ifconfig eth0" to obtain the IP address of the target.

2. On the host, perform the following (once per new console window): Go to mydroid directory and run

       source build/envsetup.sh
       setpaths
       export ADBHOST=<ip addr of target obtained above>

Ensure that above setup works by running

       adb kill-server ; adb shell

You should see a command prompt of the target on your host. Verify this by running "ps" or similar commands. Exit the adb shell by typing “exit”

3. Start GDB using the following command

       gdbclient <executable name> <port number> <task name>
       executable name: file name in system/bin dir
       port number: default is :5039 (need the colon before the number)
       task name: obtained by running "ps" on the target. GDB uses it to identify the PID internally.

E.g. for video playback, use (note the space after mediaserver and colon):

       gdbclient mediaserver :5039 mediaserver

Then you can run commands like “info threads”, “break”, “step” etc.

For a full listing of GDB commands refer to: http://www.yolinux.com/TUTORIALS/GDB-Commands.html


You may have to run the following after each target reboot:

       adb kill-server


[edit] DDD (Data Display Debugger)

DDD is a graphical front-end for GDB and other command-line debuggers like GDB.

Following are the instructions to enable DDD on Android:

Image:DDD.jpg

The steps are almost same as GDB:

1. Obtain the IP address of the target. This can be found by adding "ip=dhcp" in the bootargs, which will obtain and print the IP automatically during boot. Alternatively if you have the busybox command line tools available on the target you can type "ifconfig eth0" to obtain the IP address of the target.

2. Install DDD: in the shell run:

  sudo apt-get install ddd3

3. Add the following function to build/envsetup.sh:

function dddclient()
{
  local OUT_ROOT=$(get_abs_build_var PRODUCT_OUT)
  local OUT_SYMBOLS=$(get_abs_build_var TARGET_OUT_UNSTRIPPED)
  local OUT_SO_SYMBOLS=$(get_abs_build_var TARGET_OUT_SHARED_LIBRARIES_UNSTRIPPED)
  local OUT_EXE_SYMBOLS=$(get_abs_build_var TARGET_OUT_EXECUTABLES_UNSTRIPPED)
  local PREBUILTS=$(get_abs_build_var ANDROID_PREBUILTS)
  if "$OUT_ROOT" -a "$PREBUILTS"?; then
      local EXE="$1"
      if "$EXE"? ; then
          EXE=$1
      else
          EXE="app_process"
      fi
      local PORT="$2"
      if "$PORT"? ; then
          PORT=$2
      else
          PORT=":5039"
      fi
      local PID
      local PROG="$3"
      if "$PROG"? ; then
          PID=`pid $3`
          adb forward "tcp$PORT" "tcp$PORT"
          adb shell gdbserver $PORT --attach $PID &
          sleep 2
      else
              echo ""
              echo "If you haven't done so already, do this first on the device:"
              echo "    gdbserver $PORT /system/bin/$EXE"
                  echo " or"
              echo "    gdbserver $PORT --attach $PID"
              echo ""
      fi
      echo >|"$OUT_ROOT/gdbclient.cmds" "set solib-absolute-prefix $OUT_SYMBOLS"
      echo >>"$OUT_ROOT/gdbclient.cmds" "set solib-search-path $OUT_SO_SYMBOLS"
      echo >>"$OUT_ROOT/gdbclient.cmds" "target remote $PORT"
      echo >>"$OUT_ROOT/gdbclient.cmds" ""
      ddd --debugger arm-eabi-gdb -x "$OUT_ROOT/gdbclient.cmds" "$OUT_EXE_SYMBOLS/$EXE"
 else
      echo "Unable to determine build system output dir."
  fi
}

4. On the host, perform the following (once per new console window): Go to mydroid directory and run

       source build/envsetup.sh
       setpaths
       export ADBHOST=<ip addr of target obtained above>

Ensure that above setup works by running

       adb kill-server ; adb shell

You should see a command prompt of the target on your host. Verify this by running "ps" or similar commands. Exit the adb shell by typing “exit”

5. Start DDD using the following command

       dddclient <executable name> <port number> <task name>
       executable name: file name in system/bin dir
       port number: default is :5039 (need the colon before the number)
       task name: obtained by running "ps" on the target. GDB uses it to identify the PID internally.

E.g. for video playback, use (note the space after mediaserver and colon):

       dddclient mediaserver :5039 mediaserver

For the DDD manual, refer to: http://www.gnu.org/manual/ddd/html_mono/ddd.html

You may have to run the following after each target reboot:

       adb kill-server


[edit] Lauterbach Trace32

Lauterbach could be used to debug bootloaders, kernel and user space. Instructions on using Lauterbach Trace32 for debugging on Zoom2:


Install Lauterbach Trace 32 software on your PC (the below screenshot is from Oct 10 2008 release). Connect emulator cable to J5 (20 pin header) on Zoom2 debug board and power the emulator. Connect USB cable from the emulator to PC



Run zoom2_startup.cmm script to select your target as OMAP3430 and attach from File -> Run Batchfile. If the script is not run, some of the settings will have to be manually selected from CPU -> System Settings

Ensure that the emulator is “running” by the green status indicator (seen at the bottom of the below screenshot) before exercising any use cases that need to be debugged.



Run the use case (ex: audio/video playback) Halt the processor by clicking on the “pause” button and view registers (View -> Registers), list source (View -> List Source) etc.



Make sure to load the symbols for files that you’re interested in debugging and set source path recursively for source code correlation to work correctly. Also you may have to ensure that options such as –g is added during compiling your code to generate symbolic debugging directives. In some instances consider reducing the level of optimization used as the compiler will re-arrange instructions and hence it may be difficult to match the order of execution in the source code.

Examples of setting the source search path and loading symbols:

        symbol.SOURCEPATH.SETRECURSEDIR "V:\mydroid\kernel\"
        data.load.elf V:\mydroid\kernel\vmlinux /nocode 

These commands can be directly entered from either the debugger command prompt or by using a *.cmm script.

For user space debugging, T32 needs some help as it needs to be told where some of the modules you're interested in debugging are loaded. To do this you will have to run "ps" on the target and get PIDs for the application.

Then run "cat /proc/PID/maps > logfile" where PID is the process ID retrieved from "ps" in the above step. There is an avplayback_symbols.cmm file attached that exhibits how to do this. Below screenshot demonstrates being halted in user space during running of an AV playback use case.




zoom2_startup.cmm
avplayback_symbols.cmm

[edit] CodeComposer

This could be used to debug bootloaders. Previous versions of CCS (v3.3 and older) did not contain Linux awareness but it is currently being added to CCSv4 which is in the beta phase. It should be possible to debug the kernel and user space once CCSv4 is released. See Linux_Aware_Debug for more information.


[edit] Oprofile

OProfile is a system-wide profiler for Linux systems, capable of profiling all running code at low overhead. It consists of a kernel driver and a daemon for collecting sample data, and several post-profiling tools for turning data into information

OProfile is optional component during KERNEL build. It may have been enabled by default. You can confirm that the kernel has OProfile support, by looking for following lines in the <mydroid_folder>/kernel/.config file

       CONFIG_OPROFILE_OMAP_GPTIMER=y
       CONFIG_OPROFILE=y
       CONFIG_HAVE_OPROFILE=y

Hardware Configuration
The Hardware Configuration required to execute the test cases includes:

       Linux machine (can be with your favorite distro)
       TCP/IP configuration on Zoom2 board
       Zoom2 Board

Software Configuration
The Software Configuration required to execute the test cases includes:

       Tera Term (or any terminal program)
       Graphviz on Linux machine (Use this command on Host terminal  
       $ sudo apt-get install graphviz

       GPROF2DOT python script (Copy the script to any location in your path (e.g. in ~/bin of your Linux machine); 
       Ensure that ~/bin is exported in the PATH
      
       Run the following command -
       $ cd ~/bin && chmod 777 gprof2dot.py

Installation
This step should be done after the android file system has been built.

$MYDROID is the location where the android SDK is installed. eg: export MYDROID=/home/$user/Lxx.x/mydroid


Edit the $MYDROID/external/oprofile/opimport_pull script as follows:

  Remove the python version number from the first line eg. change
      #!/usr/bin/python2.4 -E
  to
      #!/usr/bin/python -E

  Append the following lines at the end of the file to generate cpuloads.txt and callgraph.png for further analysis 
      os.system(oprofile_event_dir + "/bin/opreport --session-dir=. >> cpuloads.txt") 
      os.system(oprofile_event_dir + "/bin/opreport --session-dir=. -p $OUT/symbols -l -t 0.1 >> cpuloads.txt") 
      os.system(oprofile_event_dir + "/bin/opreport -cg --session-dir=. -p $OUT/symbols > callgraph.txt") 
      os.system("cat callgraph.txt | gprof2dot.py -s -w -f oprofile -n 1 -e 1 | dot -Tpng -o callgraph.png") 
  
  Since we perform the post-processing on host, we don't need the actual vmlinux file (~40 MB) on target. Make sure that you create a dummy file named "vmlinux" in the root directory to satisfy opcontrol arguments.
  #echo 0 > /vmlinux

Execution

Set-up OProfile directories

      Make sure that you have created an empty file and named it vmlinux as described in above section. Run the following command on the target
      # opcontrol --setup
      By default there should be no output. 
      In case you see, "Cannot create directory /dev/oprofile: File exists do_setup failed#", it means that, OProfile is not built in the Kernel. Verify that you have selected OProfile in make menuconfig step of Kernel build (Refer Configuration Section)

Initialize the OProfile daemon

      The kernel range start and end addresses need to be verified on the setup for each release using:
          # grep " _text" /proc/kallsyms 
          c0030000 T _text
          # grep " _etext" /proc/kallsyms 
          c03e1000 A _etext
      
      Note: You need busybox installed for this command to work. Refer here if you havent set-up busybox

      Using the above addresses, run the following command
      # opcontrol --vmlinux=/vmlinux --kernel-range=0xC0030000,0xC03e1000 --event=CPU_CYCLES:64

      You should see the following output on your terminal
          Cannot open /dev/oprofile/1/enabled: No such file or directory 
          Cannot open /dev/oprofile/2/enabled: No such file or directory 
          Using 2.6+ OProfile kernel interface. Reading module info. 
          Using log file /data/oprofile/samples/oprofiled.log 
          # init: untracked pid 914 exited

      Increase the Back trace depth, so that more details can be captured in the log
          # echo 16 > /dev/oprofile/backtrace_depth
      To ensure that everything is ready, you can run the following command
          # opcontrol --status
      The following output should be seen. Note that the PID will change depending on your system.
          Driver directory: /dev/oprofile 
          Session directory: /data/oprofile 
      Counter 0: 
          name: CPU_CYCLES 
          count: 64 
      Counter 1 disabled 
      Counter 2 disabled 
      oprofiled pid: 915 profiler is not running  
          0 samples received 
          0 samples lost overflow

Starting and Stopping the profiler

      Run the following command to start the profiler
          # opcontrol --start
      and use the command below to stop the profiler
          # opcontrol --stop

Generating the Results
We need to run the following steps on the Host machine (that has android SDK/build) to generate the results.

      On command prompt of Host machine (that has android SDK/build), do the following 
          $ cd $MYDROID 
          $ source build/envsetup.sh 
          $ setpaths 
          $ export ADBHOST=<ip address of ZOOM2 board>

      The IP address of the ZOOM2 board can be found during boot-up phase
          e.g. : IP-Config: Got DHCP answer from 0.0.0.0, my address is 128.247.79.152

Post-process OProfile results

      This needs to be done from the PC where Android SDK is installed. Go to the terminal on host PC and do the following: 
          $ cd $MYDROID/external/oprofile/ 
          $ ln -s $MYDROID/kernel/android-2.6.27/vmlinux $OUT/symbols/vmlinux 
          $ opimport_pull <new_dir_to_store_dump_and_results_on_Linux_machine> 

      The following files and the Callgraph image can be referred for OProfile results. They will be generated in the <new_dir_to_store_dump_and_results_on_Linux_machine> in step above
           cpuloads.txt
           callgraph.txt


Posted by kevino
,


Android Native Development Using the Android Open Source Project

Part Four of a Series of Posts about Android Mobile Application Development.

In three prior blog posts, Developing An Android Mobile Application , Android Software Development Tools – What Do I Need? and  Android Native Development on Ubuntu 9.04 (Jaunty Jackalope), I discussed our approach for choosing Android as the next platform for our company’s mobile application, Aton Connect.  Once I identified which platform was most suitable, I needed to decide on development tools that would allow us to develope our mobile application rapidly. Because the Aton Connect software architecture combines native and managed code, I am looking for ways to include native C/C++ code in our Android version.

Tools for Native Code Development

There are now two primary sets of tools that can be used to develop Android applications that include native C/C++ native code.  The original, and still unsupported way, is to leverage the tools built into the Android Open Source Project to build Android applications.  The intent of the Android Open Source Project is to provide the means to port the Android operating system to hardware devices, ranging from cell phones, to netbooks, to set top boxes, etc.

Developing Android applications that include native code by using the Android Open Source Project allows the developer full access to every aspect of the operating system.  Because the operating system is currently under development, the Android team will be changing various aspects of the operating system source.  If you develop an Android application that happens to utilize one of the features that have changed, then your application may very well break when run on a device with a newer release of Android.

For this reason, the Android team has recently released the Android NDK or Android Native Development Kit.  The goal of the NDK is to allow native code libraries to be incorporated into an Android Java application.  A secondary goal is to limit access of native code to selected API’s and libraries that are considered mature, and thus are guaranteed to be supported in future releases of the Android OS.  The Android NDK is available here: http://developer.android.com/sdk/ndk/1.5_r1/index.html.

In this post, I will be working with the Android Open Source Project (OSP) to build Android applications that utilize native code.  In a later post, I will address the NDK, with its advantages and limitations.  Using the OSP is useful where you are building applications for a custom port of Android.  It is also helpful if you need access to API’s and libraries that are not included in the current release of the NDK and you are willing to accept that those API’s and libraries may change in future releases of the Android OS.

A Simple, Pure Native Code Application for Android

As our first example, I will build a non-trivial, but still simple C language application that does not involve Java.  I will do this by cloning the classic “ping” application used to test TCP/IP connectivity in Android.

It is important to note that using the OSP for native development requires that I respect the file structure of the OSP.  To do otherwise can generate a prohibitive amount of work to get the build system to perform properly.

In this discussion I will be referring to the environment variable $ANDROID_HOME, which is based on the instructions I presented in previous posts is equivalent to $HOME/mydroid.  The descriptions below are for Ubuntu 9.04.

Applications that support the OS, such as “ping” reside in the folder  $ANDROID_HOME/external.  To avoid collisions with the rest of the OSP, I will create a folder for our native applications at $ANDROID_HOME/external/myapps.

The  first step is to copy the folder and contents $ANDROID_HOME/external/ping to $ANDROID_HOME/external/myapps/ping.  Then, to identify our modified code and to avoid  overwriting the original ping command files, rename the folder $ANDROID_HOME/external/myapps/ping to $ANDROID_HOME/external/myapps/myping.  In this folder, rename ping.c to my_ping.c and ping_common.h to my_ping_common.h.  Use a text editor to change ping_common.h to my_ping_common.h in the #include statement in “my_ping.c”.  You should also change “ping” to “my_ping” in the  text prompt and error message strings to help identify the output as  actually coming  from this modified application.

Finally I need to adjust the Android.mk file in the folder $ANDROID_HOME/external/myapps/myping to reflect our other changes here.  Note that this file is quite compact, reflecting only differences from the standard make procedures buried in the Android OS build system.  The build system is very powerful and elegant, but quite complex if you choose to burrow into the details of how it actually works.

In the Android.mk file, make the following edits.

Change the line LOCAL_SRC_FILES:= ping.c to LOCAL_SRC_FILES:= my_ping.c.

Change the line LOCAL_MODULE := ping to LOCAL_MODULE := my_ping.

Note that the  existing  Android.mk  file specifies static libraries with this line:

LOCAL_STATIC_LIBRARIES := libcutils libc

Next, open a terminal window and change the directory to $ANDROID_HOME/external/myapps/myping.

To setup the build environment use this command:   source $ANDROID_HOME/build/envsetup.sh

Then enter the command “mm”.  This simple command initiates a complex set of events that will build the application “my_ping” in about a minute.  The terminal session output  will look something  like this:

cawilde@android:~$ cd $ANDROID_HOME/external/myapps/myping
cawilde@android:~/mydroid/external/myapps/myping$ source $ANDROID_HOME/build/envsetup.sh
cawilde@android:~/mydroid/external/myapps/myping$ mm
make: Entering directory `/home/cawilde/mydroid'
build/core/product_config.mk:261: WARNING: adding test OTA key
============================================
TARGET_PRODUCT=generic
TARGET_BUILD_VARIANT=eng
TARGET_SIMULATOR=
TARGET_BUILD_TYPE=release
TARGET_ARCH=arm
HOST_ARCH=x86
HOST_OS=linux
HOST_BUILD_TYPE=release
BUILD_ID=
============================================
target thumb C: my_ping <= /home/cawilde/mydroid/external/myapps/myping/my_ping.c
/home/cawilde/mydroid/external/myapps/myping/my_ping.c: In function 'fill':
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:136: warning: pointer targets in initialization differ in signedness
/home/cawilde/mydroid/external/myapps/myping/my_ping.c: In function '__schedule_exit':
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:315: warning: comparison betIen signed and unsigned
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:320: warning: comparison betIen signed and unsigned
/home/cawilde/mydroid/external/myapps/myping/my_ping.c: In function 'setup':
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:533: warning: pointer targets in initialization differ in signedness
/home/cawilde/mydroid/external/myapps/myping/my_ping.c: In function 'gather_statistics':
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:725: warning: comparison betIen signed and unsigned
/home/cawilde/mydroid/external/myapps/myping/my_ping.c: At top level:
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:958: warning: missing initializer
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:958: warning: (near initialization for 'cmsg.ipi.ipi_spec_dst')
/home/cawilde/mydroid/external/myapps/myping/my_ping.c: In function 'receive_error_msg':
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:1017: warning: comparison betIen signed and unsigned
/home/cawilde/mydroid/external/myapps/myping/my_ping.c: In function 'parse_reply':
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:1179: warning: comparison betIen signed and unsigned
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:1183: warning: comparison betIen signed and unsigned
/home/cawilde/mydroid/external/myapps/myping/my_ping.c: In function 'main':
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:2038: warning: comparison betIen signed and unsigned
/home/cawilde/mydroid/external/myapps/myping/my_ping.c:2046: warning: comparison betIen signed and unsigned
target Executable: my_ping (out/target/product/generic/obj/EXECUTABLES/my_ping_intermediates/LINKED/my_ping)
target Non-prelinked: my_ping (out/target/product/generic/symbols/system/bin/my_ping)
target Strip: my_ping (out/target/product/generic/obj/EXECUTABLES/my_ping_intermediates/my_ping)
Install: out/target/product/generic/system/bin/my_ping
Finding NOTICE files: out/target/product/generic/obj/NOTICE_FILES/hash-timestamp
Combining NOTICE files: out/target/product/generic/obj/NOTICE.html
gzip -c out/target/product/generic/obj/NOTICE.html > out/target/product/generic/obj/NOTICE.html.gz
make: Leaving directory `/home/cawilde/mydroid'
cawilde@android:~/mydroid/external/myapps/myping$

The build lists a number of warnings related to signed/unsigned variable mismatches which exist in the source file.  These can be ignored for purposes of this demonstration. The build listing also describes where the various types of build outputs are located.  These are close to the end of the session:

target Executable: my_ping (out/target/product/generic/obj/EXECUTABLES/my_ping_intermediates/LINKED/my_ping) (61 KB)
target Non-prelinked: my_ping (out/target/product/generic/symbols/system/bin/my_ping)  (61 KB)
target Strip: my_ping (out/target/product/generic/obj/EXECUTABLES/my_ping_intermediates/my_ping)   (27 KB)
Install: out/target/product/generic/system/bin/my_ping  (27 KB)

The build  outputs of interest are described by the lines:

Install: out/target/product/generic/system/bin/my_ping  (no symbols)
target Executable: out/target/product/generic/obj/EXECUTABLES/my_ping_intermediates/LINKED/my_ping  (includes debug symbols)

These lines mean the build outputs are located at $ANDROID_HOME at the paths given above.

Start a new terminal window and point it to the Android SDK development tools directory, located where you installed it.  For example:

$HOME/android-sdk-linux_x86-1.5_r2/tools.  

You may have a different location or SDK revision number.

You can determine the names of the emulator skins or AVD instances by using the command: “android list avds”.  If you have not set up your AVD, refer to this page for instructions: http://developer.android.com/guide/developing/tools/avd.html

You can then start the emulator with this command: emulator -avd <avd_name> where avd_name is the name you gave the AVD when you created it, and is listed by the command: “android list avds”.  Note that the “.avd” extension is not included as part of <avd_name>.

Once the Android emulator has booted up, you can try out your new my_ping application using the following procedure:

  1. Start up a new terminal window.  Start a remote shell session using the following command:  
    adb shell
    .
  2. This will reflect the input/output from a shell running as root in the emulator into the workstation terminal session window.
  3. Create a temporary folder in the /data folder on the emulator: 
    mkdir /data/tmp
  4. Then push a copy of your my_ping executable to the temporary directory using the following command in another terminal session:
    adb push $ANDROID_HOME/out/target/product/generic/system/bin/my_ping   /data/tmp.
  5. The push command responds with this type of output:
    654 KB/s (26628 bytes in 0.039s).
  6. Finally, you can execute the code (my_ping localhost) using the remote shell session you previously used to create the temporary data folder as follows:
    # /data/tmp/my_ping  localhost

After a few pings on localhost are executed, type control C into the shell session to terminate the ping  command.  The output of my_ping in the  shell session should  look like this:

PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=1.79 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.166 ms
64 bytes from localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.153 ms
64 bytes from localhost (127.0.0.1): icmp_seq=4 ttl=64 time=0.151 ms
^C
--- localhost my_ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3026
msrtt min/avg/max/mdev = 0.151/0.566/1.794/0.709 ms

If you want to make a change to Android.mk, for example to change a compilation or link option, you need to use the “touch my_ping.c” command to cause the rebuild to occur.  If I do not touch a source file, the build system thinks nothing is to be done, even though I modified the Android.mk file.

So, how do you install a pure native application into the Android phone?

If you are a device manufacturer, you can build it into the full Android image for your device.  Otherwise, you need a Java application as a wrapper.  The Java wrapper application will provide the AndroidManifest.xml file and META-INF folder required by the Android package installer.  There are other good reasons to use a Java wrapper, including access to framework libraries and easy design of GUI elements.

The use of a pure native application is also useful for debugging native shared libraries used with Java applications.  I will describe this in a later post.

Android Native Development Debugging Techniques

The next step is to debug your native application.  I do not have the assistance of the Eclipse CDT GUI here, so I need to work with the classic GDB  command line debug tool.  I could build and load a version of GDB directly onto the Android platform and operate it through a terminal window, but this approach has problems.  A major issue is building and debugging GDB itself on the Android platform.  GDB is a fairly large program and  resources on Android are limited. So, a better approach is to use a remote debugging  strategy.

Because I am debugging on a different platform from our workstation I need a tool on the Android platform that will interact with the GDB debugger running on the workstation.  This tool is named gdbserver, and is included in the Android 1.5 emulator in the folder “/system/bin”.

The setup and use of gdb with gdbserver is a bit complex.  There is a function named gdbclient in the shell library $ANDROID_HOME/build/envsetup.sh which is used to startup both gdbserver and then gdb itself.  I have adapted the gdbclient function into a shell script used for debugging our my_ping application instead of its original purpose of debugging the Android kernel code.  This adaptation is covered by the Android license (Apache) as shown here: http://www.apache.org/licenses/LICENSE-2.0.

Create a shell file named “debug” in the myping folder that contains this text:

source $ANDROID_HOME/build/envsetup.sh

setpaths

OUT_ROOT=$ANDROID_HOME/$(get_build_var PRODUCT_OUT)

echo “OUT_ROOT = $OUT_ROOT”

OUT_SYMBOLS=$ANDROID_HOME/$(get_build_var TARGET_OUT_UNSTRIPPED)

echo “OUT_SYMBOLS = $OUT_SYMBOLS”

OUT_SO_SYMBOLS=$ANDROID_HOME/$(get_build_var TARGET_OUT_SHARED_LIBRARIES_UNSTRIPPED)

echo “OUT_SO_SYMBOLS = $OUT_SO_SYMBOLS”

OUT_EXE_SYMBOLS=$ANDROID_HOME/$(get_build_var TARGET_OUT_EXECUTABLES_UNSTRIPPED)

echo “OUT_EXE_SYMBOLS = $OUT_EXE_SYMBOLS”

PREBUILTS=$ANDROID_HOME/$(get_build_var ANDROID_PREBUILTS)

echo “PREBUILTS = $PREBUILTS”

LOCAL_EXE=”$1″

if [ -z "$LOCAL_EXE" ] ; then

echo “usage: debug local_exe remote_exe arguments”

exit

fi

REM_EXE=”$2″

if [ -z "$REM_EXE" ] ; then

echo “usage: debug local_exe remote_exe arguments”

exit

fi

ARG_LIST=”$3″

if [ -z "$ARG_LIST" ] ; then

echo “usage: debug local_exe remote_exe arguments”

exit

fi

PORT=”:5039″

adb forward “tcp$PORT” “tcp$PORT”

echo “PORT = $PORT, LOCAL_EXE = $LOCAL_EXE, REM_EXE = $REM_EXE, ARG_LIST = $ARG_LIST”

adb shell gdbserver $PORT $REM_EXE $ARG_LIST &

sleep 2

echo >|”$OUT_ROOT/gdbclient.cmds” “set solib-absolute-prefix $OUT_SYMBOLS”

echo >>”$OUT_ROOT/gdbclient.cmds” “set solib-search-path $OUT_SO_SYMBOLS”

echo >>”$OUT_ROOT/gdbclient.cmds” “target remote $PORT”

echo >>”$OUT_ROOT/gdbclient.cmds” “”

arm-eabi-gdb -silent -x “$OUT_ROOT/gdbclient.cmds” “$OUT_EXE_SYMBOLS/$LOCAL_EXE”

To use this for debugging “my_ping” you will need to recompile my_ping using the appropriate debugger options.  Add this line to Android.mk immediately after the “LOCAL_SRC_FILES:= my_ping.c” line:

LOCAL_CFLAGS:=-O0  –g

The –O0 option disables GCC compiler optimizations and the –g option outputs additional debug information into the linked output.  Without these two options, the GDB debugger operation can be very erratic.  As mentioned above, you need to use the “touch my_ping.c” command to cause the rebuild to occur.  If I do not touch a source file, the build system thinks nothing is to be done, even though I modified the Android.mk file.  The rebuilt outputs are somewhat bigger, reflecting the reduced optimization and additional debug information.

Next, start up the emulator as described above.

You can then start the emulator with this command: emulator -avd <avd_name> where avd_name is the name you gave the AVD when you created it, and is listed by the command: “android list avds”.  Note that the “.avd” extension is not included as part of <avd_name>.

With the emulator started, you can copy the build outputs to the correct locations.  Use this command to copy the “symbols stripped” output to the emulator:

adb push $ANDROID_HOME/out/target/product/generic/system/bin/my_ping /data/tmp

Then, use this command to copy the output with symbols to the local folder for use by the GDB debugger:

cp $ANDROID_HOME/out/target/product/generic/obj/EXECUTABLES/my_ping_intermediates/LINKED/my_ping  ./

Now you are ready to initiate a debug session using GDB on your workstation communicating with gdbserver on the Android emulator:

./debug my_ping /data/tmp/my_ping localhost

The initial  output of the  debug session looks like this:

OUT_ROOT = /home/cawilde/mydroid/out/target/product/generic

OUT_SYMBOLS = /home/cawilde/mydroid/out/target/product/generic/symbols

OUT_SO_SYMBOLS = /home/cawilde/mydroid/out/target/product/generic/symbols/system/lib

OUT_EXE_SYMBOLS = /home/cawilde/mydroid/out/target/product/generic/symbols/system/bin

PREBUILTS = /home/cawilde/mydroid/prebuilt/linux-x86

PORT = :5039, LOCAL_EXE = my_ping, REM_EXE = /data/tmp/my_ping, ARG_LIST = localhost

Process /data/tmp/my_ping created; pid = 695

Listening on port 5039

Remote debugging from host 127.0.0.1

gdb: Unable to get location for thread creation breakpoint: requested event is not supported

__dl__start () at bionic/linker/arch/arm/begin.S:35

35                           mov       r0, sp

gdb: Unable to get location for thread creation breakpoint: requested event is not supported

Current language:  auto; currently asm

(gdb)

The  debug session starts the Android loader for /data/tmp/my_ping and the initial debug location is in the Android loader, not our application.  The loader is not configured to operate with GDB and so errors are displayed.  Single stepping at this point will simply walk through the assembly code rendition of the Android loader.  It is much more useful to set a breakpoint at the beginning of our application and then continue to the breakpoint, as follows:

(gdb) b my_ping.c:main

Breakpoint 1 at 0xe120: file /home/cawilde/mydroid/external/myapps/myping/my_ping.c, line 1673.

(gdb) c

Continuing.

warning: .dynamic section for “/home/cawilde/mydroid/out/target/product/generic/symbols/system/lib/libc.so” is not at the expected address (wrong library or version mismatch?)

[New Thread 695]

warning: .dynamic section for “/home/cawilde/mydroid/out/target/product/generic/symbols/system/lib/libstdc++.so” is not at the expected address (wrong library or version mismatch?)

warning: .dynamic section for “/home/cawilde/mydroid/out/target/product/generic/symbols/system/lib/libm.so” is not at the expected address

warning: difference appears to be caused by prelink, adjusting expectations

warning: .dynamic section for “/home/cawilde/mydroid/out/target/product/generic/symbols/system/lib/liblog.so” is not at the expected address

warning: difference appears to be caused by prelink, adjusting expectations

warning: .dynamic section for “/home/cawilde/mydroid/out/target/product/generic/symbols/system/lib/libcutils.so” is not at the expected address (wrong library or version mismatch?)

[Switching to Thread 695]

Breakpoint 1, main (argc=2, argv=0xbeaead84)

at /home/cawilde/mydroid/external/myapps/myping/my_ping.c:1673

1673       {

Current language:  auto; currently c

(gdb) l

1668       “            [ -T timestamp option ] [ -Q tos ] [hop1 ...] destinationn”);

1669                       exit(2);

1670       }

1671

1672       int main(int argc, char *argv[])

1673       {

1674                       struct hostent *hp;

1675                       int ch, hold, packlen;

1676                       int socket_errno;

1677                       u_char *packet;

(gdb) l

1678                       char *target, hnamebuf[MAXHOSTNAMELEN];

1679                       char rspace[3 + 4 * NROUTES + 1];            /* record route space */

1680

1681                       icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);

1682                       socket_errno = errno;

1683

1684                       /* if I Ire setuid root, undo that */

1685                       if (setuid(getuid())) return -1;

1686

1687                       source.sin_family = AF_INET;

I can then single step code and examine variables in the usual GDB fashion:

(gdb) n

1681                       icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);

(gdb) n

1682                       socket_errno = errno;

(gdb) p socket_errno

$1 = 32768

(gdb) n

1685                       if (setuid(getuid())) return -1;

(gdb) n

1687                       source.sin_family = AF_INET;

(gdb) n

1689                       preload = 1;

(gdb) p preload

$2 = 0

(gdb) n

1690                       while ((ch = getopt(argc, argv, COMMON_OPTSTR “bRT:”)) != EOF) {

(gdb) p preload

$3 = 1

(gdb) n

1769                       argc -= optind;

… etc ….

If you are not familiar with the GDB debugging tool, there are many references available on the Internet and a condensed guide is available here:http://www.yolinux.com/TUTORIALS/GDB-Commands.html.

My preference is using an integrated GUI development environment, and the command line GDB, although quite useful, is a long way from that.  Ideally the CDT add-on for Eclipse could  be reconciled with the  Android OSP  build environment.  This would take more  development time to accomplish than I have available, so I will continue to use GDB for Android native debugging  tasks.

In the next post, I will detail how to build native shared libraries for use with a Java wrapper or Java GUI application.

* * * * * * * *

With 20+ years as a top software and firmware developer, Charles Wilde has acquired a combination of proven business smarts, mobile development skills and device engineering expertise that is hard to match. Charles is available to consult with you and your team about native code development in Android, Windows Mobile or Windows CE. Just email him at AtonMail@aton.com.

Posted by kevino
,