8 sum+=i;
9 }
10 return sum;
11 }
12
13
14 main()
15 {
16 int i;
17 long result = 0;
18 for(i=1; i<=100; i++)
19 {
20 result += i;
21 }
22
23 printf("result[1-100] = %d \n", result );
24 printf("result[1-250] = %d \n", func(250) );
25 }
編譯生成執行文件:(Linux下)
hchen/test> cc -g tst.c -o tst
使用GDB調試:
hchen/test> gdb tst <---------- 啟動GDB
GNU gdb 5.1.1
Copyright 2002 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-suse-linux"...
(gdb) l <-------------------- l命令相當于list,從第一行開始例出原碼。
1 #include
2
3 int func(int n)
4 {
5 int sum=0,i;
6 for(i=0; i 7 {
8 sum+=i;
9 }
10 return sum;
(gdb) <-------------------- 直接回車表示,重復上一次命令
11 }
12
13
14 main()
15 {
16 int i;
17 long result = 0;
18 for(i=1; i<=100; i++)
19 {
20 result += i;
(gdb) break 16 <-------------------- 設置斷點,在源程序第16行處。
Breakpoint 1 at 0x8048496: file tst.c, line 16.
(gdb) break func <-------------------- 設置斷點,在函數func()入口處。
Breakpoint 2 at 0x8048456: file tst.c, line 5.
(gdb) info break <-------------------- 查看斷點信息。
Num Type Disp Enb Address What
1 breakpoint keep y 0x08048496 in main at tst.c:16
2 breakpoint keep y 0x08048456 in func at tst.c:5
(gdb) r <--------------------- 運行程序,run命令簡寫
Starting program: /home/hchen/test/tst
Breakpoint 1, main () at tst.c:17 <---------- 在斷點處停住。
17 long result = 0;
(gdb) n <--------------------- 單條語句執行,next命令簡寫。
18 for(i=1; i<=100; i++)
(gdb) n
20 result += i;
(gdb) n
18 for(i=1; i<=100; i++)
(gdb) n
20 result += i;
(gdb) c <--------------------- 繼續運行程序,continue命令簡寫。
Continuing.
result[1-100] = 5050 <----------程序輸出。
Breakpoint 2, func (n=250) at tst.c:5
5 int sum=0,i;
(gdb) n
6 for(i=1; i<=n; i++)
(gdb) p i <--------------------- 打印變量i的值,print命令簡寫。
$1 = 134513808
(gdb) n
8 sum+=i;
(gdb) n
6 for(i=1; i<=n; i++)
(gdb) p sum
$2 = 1
(gdb) n
8 sum+=i;
(gdb) p i
$3 = 2
(gdb) n
6 for(i=1; i<=n; i++)
(gdb) p sum
$4 = 3
(gdb) bt <--------------------- 查看函數堆棧。
#0 func (n=250) at tst.c:5
#1 0x080484e4 in main () at tst.c:24
#2 0x400409ed in __libc_start_main () from /lib/libc.so.6
(gdb) finish <--------------------- 退出函數。
Run till exit from #0 func (n=250) at tst.c:5
0x080484e4 in main () at tst.c:24
24 printf("result[1-250] = %d \n", func(250) );
Value returned is $6 = 31375
(gdb) c <--------------------- 繼續運行。
Continuing.
result[1-250] = 31375 <----------程序輸出。
Program exited with code 027. <--------程序退出,調試結束。
(gdb) q <--------------------- 退出gdb。
hchen/test>
好了,有了以上的感性認識,還是讓我們來系統地認識一下gdb吧。
使用GDB
————
一般來說GDB主要調試的是C/C++的程序。要調試C/C++的程序,首先在編譯時,我們必
須要把調試信息加到可執行文件中。使用編譯器(cc/gcc/g++)的 -g 參數可以做到這一點。
如:
> cc -g hello.c -o hello
> g++ -g hello.cpp -o hello
如果沒有-g,你將看不見程序的函數名、變量名,所代替的全是運行時的內存地址。當你用
-g把調試信息加入之后,并成功編譯目標代碼以后,讓我們來看看如何用gdb來調試他。
啟動GDB的方法有以下幾種:
1、gdb
program也就是你的執行文件,一般在當然目錄下。
2、gdb core
用gdb同時調試一個運行程序和core文件,core是程序非法執行后core dump后產生的文件。
3、gdb
如果你的程序是一個服務程序,那么你可以指定這個服務程序運行時的進程ID。gdb會自
動attach上去,并調試他。program應該在PATH環境變量中搜索得到。
GDB啟動時,可以加上一些GDB的啟動開關,詳細的開關可以用gdb -help查看。我在下
面只例舉一些比較常用的參數:
-symbols
-s
從指定文件中讀取符號表。
-se file
從指定文件中讀取符號表信息,并把他用在可執行文件中。
-core
-c
調試時core dump的core文件。
-directory
-d
加入一個源文件的搜索路徑。默認搜索路徑是環境變量中PATH所定義的路徑。
GDB的命令概貌
———————
啟動gdb后,就你被帶入gdb的調試環境中,就可以使用gdb的命令開始調試程序了,gdb
的命令可以使用help命令來查看,如下所示:
/home/hchen> gdb
GNU gdb 5.1.1
Copyright 2002 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-suse-linux".
(gdb) help
List of classes of commands:
aliases -- Aliases of other commands
breakpoints -- Making program stop at certain points
data -- Examining data
files -- Specifying and examining files
internals -- Maintenance commands
obscure -- Obscure features
running -- Running the program
stack -- Examining the stack
status -- Status inquiries
support -- Support facilities
tracepoints -- Tracing of program execution without stopping the program
user-defined -- User-defined commands
Type "help" followed by a class name for a list of commands in that class.
Type "help" followed by command name for full documentation.
Command name abbreviations are allowed if unambiguous.
(gdb)
gdb的命令很多,gdb把之分成許多個種類。help命令只是例出gdb的命令種類,如果要看
種類中的命令,可以使用help 命令,如:help breakpoints,查看設置斷點的所有命令。也
可以直接help 來查看命令的幫助。
gdb中,輸入命令時,可以不用打全命令,只用打命令的前幾個字符就可以了,當然,命令
的前幾個字符應該要標志著一個唯一的命令,在Linux下,你可以敲擊兩次TAB鍵來補齊
命令的全稱,如果有重復的,那么gdb會把其例出來。
示例一:在進入函數func時,設置一個斷點。可以敲入break func,或是直接就是b func
(gdb) b func
Breakpoint 1 at 0x8048458: file hello.c, line 10.
示例二:敲入b按兩次TAB鍵,你會看到所有b打頭的命令:
(gdb) b
backtrace break bt
(gdb)
示例三:只記得函數的前綴,可以這樣:
(gdb) b make_ <按TAB鍵>
(再按下一次TAB鍵,你會看到:)
make_a_section_from_file make_environ
make_abs_section make_function_type
make_blockvector make_pointer_type
make_cleanup make_reference_type
make_command make_symbol_completion_list
(gdb) b make_
GDB把所有make開頭的函數全部例出來給你查看。
示例四:調試C++的程序時,有可以函數名一樣。如:
(gdb) b 'bubble( M-?
bubble(double,double) bubble(int,int)
(gdb) b 'bubble(
你可以查看到C++中的所有的重載函數及參數。(注:M-?和“按兩次TAB鍵”是一個意思)
要退出gdb時,只用發quit或命令簡稱q就行了。
GDB中運行UNIX的shell程序
————————————
在gdb環境中,你可以執行UNIX的shell的命令,使用gdb的shell命令來完成:
shell
調用UNIX的shell來執行,環境變量SHELL中定義的UNIX的shell將會被用來執行,如
果SHELL沒有定義,那就使用UNIX的標準shell:/bin/sh。(在Windows中使用Command.com
或cmd.exe)
還有一個gdb命令是make:
make
可以在gdb中執行make命令來重新build自己的程序。這個命令等價于“shell make ”。
在GDB中運行程序
————————
當以gdb 方式啟動gdb后,gdb會在PATH路徑和當前目錄中搜索的源文件。如要確認gdb
是否讀到源文件,可使用l或list命令,看看gdb是否能列出源代碼。
在gdb中,運行程序使用r或是run命令。程序的運行,你有可能需要設置下面四方面的事。
1、程序運行參數。
set args 可指定運行時參數。(如:set args 10 20 30 40 50)
show args 命令可以查看設置好的運行參數。
2、運行環境。
path
可設定程序的運行路徑。
show paths 查看程序的運行路徑。
set environment varname [=value] 設置環境變量。如:set env USER=hchen
show environment [varname] 查看環境變量。
3、工作目錄。
cd
相當于shell的cd命令。
pwd 顯示當前的所在目錄。
4、程序的輸入輸出。
info terminal 顯示你程序用到的終端的模式。
使用重定向控制程序輸出。如:run > outfile
tty命令可以指寫輸入輸出的終端設備。如:tty /dev/ttyb
調試已運行的程序
————————
兩種方法:
1、在UNIX下用ps查看正在運行的程序的PID(進程ID),然后用gdb PID格式掛接正在
運行的程序。
2、先用gdb 關聯上源代碼,并進行gdb,在gdb中用attach命令來掛接進程的PID。并用
detach來取消掛接的進程。
暫停 / 恢復程序運行
—————————
調試程序中,暫停程序運行是必須的,GDB可以方便地暫停程序的運行。你可以設置程序
的在哪行停住,在什么條件下停住,在收到什么信號時停往等等。以便于你查看運行時的變
量,以及運行時的流程。
當進程被gdb停住時,你可以使用info program 來查看程序的是否在運行,進程號,被暫停
的原因。
在gdb中,我們可以有以下幾種暫停方式:斷點(BreakPoint)、觀察點(WatchPoint)、捕
捉點(CatchPoint)、信號(Signals)、線程停止(Thread Stops)。如果要恢復程序運行,可
以使用c或是continue命令。
一、設置斷點(BreakPoint)
我們用break命令來設置斷點。正面有幾點設置斷點的方法:
break
在進入指定函數時停住。C++中可以使用class::function或function(type,type)格式來指定函
數名。
break
在指定行號停住。
break +offset
break -offset
在當前行號的前面或后面的offset行停住。offiset為自然數。
break filename:linenum
在源文件filename的linenum行處停住。
break filename:function
在源文件filename的function函數的入口處停住。
break *address
在程序運行的內存地址處停住。
break
break命令沒有參數時,表示在下一條指令處停住。
break ... if
...可以是上述的參數,condition表示條件,在條件成立時停住。比如在循環境體中,可以設
置break if i=100,表示當i為100時停住程序。
查看斷點時,可使用info命令,如下所示:(注:n表示斷點號)
info breakpoints [n]
info break [n]
二、設置觀察點(WatchPoint)
觀察點一般來觀察某個表達式(變量也是一種表達式)的值是否有變化了,如果有變化,馬
上停住程序。我們有下面的幾種方法來設置觀察點:
watch
為表達式(變量)expr設置一個觀察點。一量表達式值有變化時,馬上停住程序。
rwatch
當表達式(變量)expr被讀時,停住程序。
awatch
當表達式(變量)的值被讀或被寫時,停住程序。
info watchpoints
列出當前所設置了的所有觀察點。
三、設置捕捉點(CatchPoint)
你可設置捕捉點來補捉程序運行時的一些事件。如:載入共享庫(動態鏈接庫)或是C++
的異常。設置捕捉點的格式為:
catch
當event發生時,停住程序。event可以是下面的內容:
1、throw 一個C++拋出的異常。(throw為關鍵字)
2、catch 一個C++捕捉到的異常。(catch為關鍵字)
3、exec 調用系統調用exec時。(exec為關鍵字,目前此功能只在HP-UX下有用)
4、fork 調用系統調用fork時。(fork為關鍵字,目前此功能只在HP-UX下有用)
5、vfork 調用系統調用vfork時。(vfork為關鍵字,目前此功能只在HP-UX下有用)
6、load 或 load 載入共享庫(動態鏈接庫)時。(load為關鍵字,目前此功能只在HP-UX
下有用)
7、unload 或 unload 卸載共享庫(動態鏈接庫)時。(unload為關鍵字,目前此功能只在
HP-UX下有用)
tcatch
只設置一次捕捉點,當程序停住以后,應點被自動刪除。
四、維護停止點
上面說了如何設置程序的停止點,GDB中的停止點也就是上述的三類。在GDB中,如果你
覺得已定義好的停止點沒有用了,你可以使用delete、clear、disable、enable這幾個命令來
進行維護。
clear
清除所有的已定義的停止點。
clear
clear
清除所有設置在函數上的停止點。
clear
clear
清除所有設置在指定行上的停止點。
delete [breakpoints] [range...]
刪除指定的斷點,breakpoints為斷點號。如果不指定斷點號,則表示刪除所有的斷點。range
表示斷點號的范圍(如:3-7)。其簡寫命令為d。
比刪除更好的一種方法是disable停止點,disable了的停止點,GDB不會刪除,當你還需要
時,enable即可,就好像回收站一樣。
disable [breakpoints] [range...]
disable所指定的停止點,breakpoints為停止點號。如果什么都不指定,表示disable所有的
停止點。簡寫命令是dis.
enable [breakpoints] [range...]
enable所指定的停止點,breakpoints為停止點號。
enable [breakpoints] once range...
enable所指定的停止點一次,當程序停止后,該停止點馬上被GDB自動disable。
enable [breakpoints] delete range...
enable所指定的停止點一次,當程序停止后,該停止點馬上被GDB自動刪除。
五、停止條件維護
前面在說到設置斷點時,我們提到過可以設置一個條件,當條件成立時,程序自動停止,這
是一個非常強大的功能,這里,我想專門說說這個條件的相關維護命令。一般來說,為斷點
設置一個條件,我們使用if關鍵詞,后面跟其斷點條件。并且,條件設置好后,我們可以
用condition命令來修改斷點的條件。(只有break和watch命令支持if,catch目前暫不支持
if)
condition
修改斷點號為bnum的停止條件為expression。
condition
清除斷點號為bnum的停止條件。
還有一個比較特殊的維護命令ignore,你可以指定程序運行時,忽略停止條件幾次。
ignore
表示忽略斷點號為bnum的停止條件count次。
六、為停止點設定運行命令
我們可以使用GDB提供的command命令來設置停止點的運行命令。也就是說,當運行的
程序在被停止住時,我們可以讓其自動運行一些別的命令,這很有利行自動化調試。對基于
GDB的自動化調試是一個強大的支持。
commands [bnum]
... command-list ...
end
為斷點號bnum指寫一個命令列表。當程序被該斷點停住時,gdb會依次運行命令列表中的
命令。
例如:
break foo if x>0
commands
printf "x is %d\n",x
continue
end
斷點設置在函數foo中,斷點條件是x>0,如果程序被斷住后,也就是,一旦x的值在foo
函數中大于0,GDB會自動打印出x的值,并繼續運行程序。
如果你要清除斷點上的命令序列,那么只要簡單的執行一下commands命令,并直接在打個
end就行了。
七、斷點菜單
在C++中,可能會重復出現同一個名字的函數若干次(函數重載),在這種情況下,break 不
能告訴GDB要停在哪個函數的入口。當然,你可以使用break 也就是把函數的參數類型告
訴GDB,以指定一個函數。否則的話,GDB會給你列出一個斷點菜單供你選擇你所需要的
斷點。你只要輸入你菜單列表中的編號就可以了。如:
(gdb) b String::after
[0] cancel
[1] all
[2] file:String.cc; line number:867
[3] file:String.cc; line number:860
[4] file:String.cc; line number:875
[5] file:String.cc; line number:853
[6] file:String.cc; line number:846
[7] file:String.cc; line number:735
> 2 4 6
Breakpoint 1 at 0xb26c: file String.cc, line 867.
Breakpoint 2 at 0xb344: file String.cc, line 875.
Breakpoint 3 at 0xafcc: file String.cc, line 846.
Multiple breakpoints were set.
Use the "delete" command to delete unwanted
breakpoints.
(gdb)
可見,GDB列出了所有after的重載函數,你可以選一下列表編號就行了。0表示放棄設置
斷點,1表示所有函數都設置斷點。
八、恢復程序運行和單步調試
當程序被停住了,你可以用continue命令恢復程序的運行直到程序結束,或下一個斷點到來。
也可以使用step或next命令單步跟蹤程序。
continue [ignore-count]
c [ignore-count]
fg [ignore-count]
恢復程序運行,直到程序結束,或是下一個斷點到來。ignore-count表示忽略其后的斷點次
數。continue,c,fg三個命令都是一樣的意思。
step
單步跟蹤,如果有函數調用,他會進入該函數。進入函數的前提是,此函數被編譯有debug
信息。很像VC等工具中的step in。后面可以加count也可以不加,不加表示一條條地執行,
加表示執行后面的count條指令,然后再停住。
next
同樣單步跟蹤,如果有函數調用,他不會進入該函數。很像VC等工具中的step over。后面
可以加count也可以不加,不加表示一條條地執行,加表示執行后面的count條指令,然后
再停住。
set step-mode
set step-mode on
打開step-mode模式,于是,在進行單步跟蹤時,程序不會因為沒有debug信息而不停住。
這個參數有很利于查看機器碼。
set step-mod off
關閉step-mode模式。
finish
運行程序,直到當前函數完成返回。并打印函數返回時的堆棧地址和返回值及參數值等信息。
until 或 u
當你厭倦了在一個循環體內單步跟蹤時,這個命令可以運行程序直到退出循環體。
stepi 或 si
nexti 或 ni
單步跟蹤一條機器指令!一條程序代碼有可能由數條機器指令完成,stepi和nexti可以單步
執行機器指令。與之一樣有相同功能的命令是“display/i $pc” ,當運行完這個命令后,單
步跟蹤會在打出程序代碼的同時打出機器指令(也就是匯編代碼)
九、信號(Signals)
信號是一種軟中斷,是一種處理異步事件的方法。一般來說,操作系統都支持許多信號。尤
其是UNIX,比較重要應用程序一般都會處理信號。UNIX定義了許多信號,比如SIGINT
表示中斷字符信號,也就是Ctrl+C的信號,SIGBUS表示硬件故障的信號;SIGCHLD表示
子進程狀態改變信號;SIGKILL表示終止程序運行的信號,等等。信號量編程是UNIX下
非常重要的一種技術。
GDB有能力在你調試程序的時候處理任何一種信號,你可以告訴GDB需要處理哪一種信
號。你可以要求GDB收到你所指定的信號時,馬上停住正在運行的程序,以供你進行調試。
你可以用GDB的handle命令來完成這一功能。
handle
在GDB中定義一個信號處理。信號可以以SIG開頭或不以SIG開頭,可以用定義一個要處
理信號的范圍(如:SIGIO-SIGKILL,表示處理從SIGIO信號到SIGKILL的信號,其中包
括SIGIO,SIGIOT,SIGKILL三個信號),也可以使用關鍵字all來標明要處理所有的信號。
一旦被調試的程序接收到信號,運行程序馬上會被GDB停住,以供調試。其可以是以下幾
種關鍵字的一個或多個。
nostop
當被調試的程序收到信號時,GDB不會停住程序的運行,但會打出消息告訴你收到這種信
號。
stop
當被調試的程序收到信號時,GDB會停住你的程序。
print
當被調試的程序收到信號時,GDB會顯示出一條信息。
noprint
當被調試的程序收到信號時,GDB不會告訴你收到信號的信息。
pass
noignore
當被調試的程序收到信號時,GDB不處理信號。這表示,GDB會把這個信號交給被調試程
序會處理。
nopass
ignore
當被調試的程序收到信號時,GDB不會讓被調試程序來處理這個信號。
info signals
info handle
查看有哪些信號在被GDB檢測中。
十、線程(Thread Stops)
如果你程序是多線程的話,你可以定義你的斷點是否在所有的線程上,或是在某個特定的線
程。GDB很容易幫你完成這一工作。
break thread
break thread if ...
linespec指定了斷點設置在的源程序的行號。threadno指定了線程的ID,注意,這個ID是
GDB分配的,你可以通過“info threads”命令來查看正在運行程序中的線程信息。如果你
不指定thread 則表示你的斷點設在所有線程上面。你還可以為某線程指定斷點條件。如:
(gdb) break frik.c:13 thread 28 if bartab > lim
當你的程序被GDB停住時,所有的運行線程都會被停住。這方便你你查看運行程序的總體
情況。而在你恢復程序運行時,所有的線程也會被恢復運行。那怕是主進程在被單步調試時。
查看棧信息
—————
當程序被停住了,你需要做的第一件事就是查看程序是在哪里停住的。當你的程序調用了一
個函數,函數的地址,函數參數,函數內的局部變量都會被壓入“棧”(Stack)中。你可以
用GDB命令來查看當前的棧中的信息。
下面是一些查看函數調用棧信息的GDB命令:
backtrace
bt
打印當前的函數調用棧的所有信息。如:
(gdb) bt
#0 func (n=250) at tst.c:6
#1 0x08048524 in main (argc=1, argv=0xbffff674) at tst.c:30
#2 0x400409ed in __libc_start_main () from /lib/libc.so.6
從上可以看出函數的調用棧信息:__libc_start_main --> main() --> func()
backtrace
bt
n是一個正整數,表示只打印棧頂上n層的棧信息。
backtrace <-n>
bt <-n>
-n表一個負整數,表示只打印棧底下n層的棧信息。
如果你要查看某一層的信息,你需要在切換當前的棧,一般來說,程序停止時,最頂層的棧
就是當前棧,如果你要查看棧下面層的詳細信息,首先要做的是切換當前棧。
frame
f
n是一個從0開始的整數,是棧中的層編號。比如:frame 0,表示棧頂,frame 1,表示棧的
第二層。
up
表示向棧的上面移動n層,可以不打n,表示向上移動一層。
down
表示向棧的下面移動n層,可以不打n,表示向下移動一層。
上面的命令,都會打印出移動到的棧層的信息。如果你不想讓其打出信息。你可以使用這三
個命令:
select-frame 對應于 frame 命令。
up-silently 對應于 up 命令。
down-silently 對應于 down 命令。
查看當前棧層的信息,你可以用以下GDB命令:
frame 或 f
會打印出這些信息:棧的層編號,當前的函數名,函數參數值,函數所在文件及行號,函數
執行到的語句。
info frame
info f
這個命令會打印出更為詳細的當前棧層的信息,只不過,大多數都是運行時的內內地址。比
如:函數地址,調用函數的地址,被調用函數的地址,目前的函數是由什么樣的程序語言寫
成的、函數參數地址及值、局部變量的地址等等。如:
(gdb) info f
Stack level 0, frame at 0xbffff5d4:
eip = 0x804845d in func (tst.c:6); saved eip 0x8048524
called by frame at 0xbffff60c
source language c.
Arglist at 0xbffff5d4, args: n=250
Locals at 0xbffff5d4, Previous frame's sp is 0x0
Saved registers:
ebp at 0xbffff5d4, eip at 0xbffff5d8
info args
打印出當前函數的參數名及其值。
info locals
打印出當前函數中所有局部變量及其值。
info catch
打印出當前的函數中的異常處理信息。
查看源程序
—————
一、顯示源代碼
GDB 可以打印出所調試程序的源代碼,當然,在程序編譯時一定要加上-g的參數,把源程
序信息編譯到執行文件中。不然就看不到源程序了。當程序停下來以后,GDB會報告程序
停在了那個文件的第幾行上。你可以用list命令來打印程序的源代碼。還是來看一看查看源
代碼的GDB命令吧。
list
顯示程序第linenum行的周圍的源程序。
list
顯示函數名為function的函數的源程序。
list
顯示當前行后面的源程序。
list -
顯示當前行前面的源程序。
一般是打印當前行的上5行和下5行,如果顯示函數是是上2行下8行,默認是10行,當
然,你也可以定制顯示的范圍,使用下面命令可以設置一次顯示源程序的行數。
set listsize
設置一次顯示源代碼的行數。
show listsize
查看當前listsize的設置。
list命令還有下面的用法:
list ,
顯示從first行到last行之間的源代碼。
list ,
顯示從當前行到last行之間的源代碼。
list +
往后顯示源代碼。
一般來說在list后面可以跟以下這們的參數:
行號。
<+offset> 當前行號的正偏移量。
<-offset> 當前行號的負偏移量。
哪個文件的哪一行。
函數名。
哪個文件中的哪個函數。
<*address> 程序運行時的語句在內存中的地址。
二、搜索源代碼
不僅如此,GDB還提供了源代碼搜索的命令:
forward-search
search
向前面搜索。
reverse-search
全部搜索。
其中,就是正則表達式,也主一個字符串的匹配模式,關于正則表達式,我就不在這里講了,
還請各位查看相關資料。
三、指定源文件的路徑
某些時候,用-g編譯過后的執行程序中只是包括了源文件的名字,沒有路徑名。GDB提供
了可以讓你指定源文件的路徑的命令,以便GDB進行搜索。
directory
dir
加一個源文件路徑到當前路徑的前面。如果你要指定多個路徑,UNIX下你可以使用“:”,
Windows下你可以使用“;”。
directory
清除所有的自定義的源文件搜索路徑信息。
show directories
顯示定義了的源文件搜索路徑。
四、源代碼的內存
你可以使用info line命令來查看源代碼在內存中的地址。info line后面可以跟“行號”,“函
數名”,“文件名:行號”,“文件名:函數名”,這個命令會打印出所指定的源碼在運行時的內
存地址,如:
(gdb) info line tst.c:func
Line 5 of "tst.c" starts at address 0x8048456 and ends at 0x804845d .
還有一個命令(disassemble)你可以查看源程序的當前執行時的機器碼,這個命令會把目前
內存中的指令dump出來。如下面的示例表示查看函數func的匯編代碼。
(gdb) disassemble func
Dump of assembler code for function func:
0x8048450 : push %ebp
0x8048451 : mov %esp,%ebp
0x8048453 : sub $0x18,%esp
0x8048456 : movl $0x0,0xfffffffc(%ebp)
0x804845d : movl $0x1,0xfffffff8(%ebp)
0x8048464 : mov 0xfffffff8(%ebp),%eax
0x8048467 : cmp 0x8(%ebp),%eax
0x804846a : jle 0x8048470
0x804846c : jmp 0x8048480
0x804846e : mov %esi,%esi
0x8048470 : mov 0xfffffff8(%ebp),%eax
0x8048473 : add %eax,0xfffffffc(%ebp)
0x8048476 : incl 0xfffffff8(%ebp)
0x8048479 : jmp 0x8048464
0x804847b : nop
0x804847c : lea 0x0(%esi,1),%esi
0x8048480 : mov 0xfffffffc(%ebp),%edx
0x8048483 : mov %edx,%eax
0x8048485 : jmp 0x8048487
0x8048487 : mov %ebp,%esp
0x8048489 : pop %ebp
0x804848a : ret
End of assembler dump.
查看運行時數據
———————
在你調試程序時,當程序被停住時,你可以使用print命令(簡寫命令為p),或是同義命令
inspect來查看當前程序的運行數據。print命令的格式是:
print
print /
是表達式,是你所調試的程序的語言的表達式(GDB可以調試多種編程語言),是輸出的格
式,比如,如果要把表達式按16進制的格式輸出,那么就是/x。
一、表達式
print和許多GDB的命令一樣,可以接受一個表達式,GDB會根據當前的程序運行的數據
來計算這個表達式,既然是表達式,那么就可以是當前程序運行中的const常量、變量、函
數等內容。可惜的是GDB不能使用你在程序中所定義的宏。
表達式的語法應該是當前所調試的語言的語法,由于C/C++是一種大眾型的語言,所以,本
文中的例子都是關于C/C++的。(而關于用GDB調試其它語言的章節,我將在后面介紹)
在表達式中,有幾種GDB所支持的操作符,它們可以用在任何一種語言中。
@
是一個和數組有關的操作符,在后面會有更詳細的說明。
::
指定一個在文件或是一個函數中的變量。
{}
表示一個指向內存地址的類型為type的一個對象。
二、程序變量
在GDB中,你可以隨時查看以下三種變量的值:
1、全局變量(所有文件可見的)
2、靜態全局變量(當前文件可見的)
3、局部變量(當前Scope可見的)
如果你的局部變量和全局變量發生沖突(也就是重名),一般情況下是局部變量會隱藏全局
變量,也就是說,如果一個全局變量和一個函數中的局部變量同名時,如果當前停止點在函
數中,用print顯示出的變量的值會是函數中的局部變量的值。如果此時你想查看全局變量
的值時,你可以使用“::”操作符:
file::variable
function::variable
可以通過這種形式指定你所想查看的變量,是哪個文件中的或是哪個函數中的。例如,查看
文件f2.c中的全局變量x的值:
gdb) p 'f2.c'::x
當然,“::”操作符會和C++中的發生沖突,GDB能自動識別“::” 是否C++的操作符,所
以你不必擔心在調試C++程序時會出現異常。
另外,需要注意的是,如果你的程序編譯時開啟了優化選項,那么在用GDB調試被優化過
的程序時,可能會發生某些變量不能訪問,或是取值錯誤碼的情況。這個是很正常的,因為
優化程序會刪改你的程序,整理你程序的語句順序,剔除一些無意義的變量等,所以在GDB
調試這種程序時,運行時的指令和你所編寫指令就有不一樣,也就會出現你所想象不到的結
果。對付這種情況時,需要在編譯程序時關閉編譯優化。一般來說,幾乎所有的編譯器都支
持編譯優化的開關,例如,GNU的C/C++編譯器GCC,你可以使用“-gstabs”選項來解決
這個問題。關于編譯器的參數,還請查看編譯器的使用說明文檔。
三、數組
有時候,你需要查看一段連續的內存空間的值。比如數組的一段,或是動態分配的數據的大
小。你可以使用GDB的“@”操作符,“@”的左邊是第一個內存的地址的值,“@”的右
邊則你你想查看內存的長度。例如,你的程序中有這樣的語句:
int *array = (int *) malloc (len * sizeof (int));
于是,在GDB調試過程中,你可以以如下命令顯示出這個動態數組的取值:
p *array@len
@的左邊是數組的首地址的值,也就是變量array所指向的內容,右邊則是數據的長度,其
保存在變量len中,其輸出結果,大約是下面這個樣子的:
(gdb) p *array@len
$1 = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40}
如果是靜態數組的話,可以直接用print數組名,就可以顯示數組中所有數據的內容了。
四、輸出格式
一般來說,GDB會根據變量的類型輸出變量的值。但你也可以自定義GDB的輸出的格式。
例如,你想輸出一個整數的十六進制,或是二進制來查看這個整型變量的中的位的情況。要
做到這樣,你可以使用GDB的數據顯示格式:
x 按十六進制格式顯示變量。
d 按十進制格式顯示變量。
u 按十六進制格式顯示無符號整型。
o 按八進制格式顯示變量。
t 按二進制格式顯示變量。
a 按十六進制格式顯示變量。
c 按字符格式顯示變量。
f 按浮點數格式顯示變量。
(gdb) p i
$21 = 101
(gdb) p/a i
$22 = 0x65
(gdb) p/c i
$23 = 101 'e'
(gdb) p/f i
$24 = 1.41531145e-43
(gdb) p/x i
$25 = 0x65
(gdb) p/t i
$26 = 1100101
五、查看內存
你可以使用examine命令(簡寫是x)來查看內存地址中的值。x命令的語法如下所示:
x/
n、f、u是可選的參數。
n 是一個正整數,表示顯示內存的長度,也就是說從當前地址向后顯示幾個地址的內容。
f 表示顯示的格式,參見上面。如果地址所指的是字符串,那么格式可以是s,如果地十是
指令地址,那么格式可以是i。
u 表示從當前地址往后請求的字節數,如果不指定的話,GDB默認是4個bytes。u參數可
以用下面的字符來代替,b表示單字節,h表示雙字節,w表示四字節,g表示八字節。當
我們指定了字節長度后,GDB會從指內存定的內存地址開始,讀寫指定字節,并把其當作
一個值取出來。
表示一個內存地址。
n/f/u三個參數可以一起使用。例如:
命令:x/3uh 0x54320 表示,從內存地址0x54320讀取內容,h表示以雙字節為一個單位,3
表示三個單位,u表示按十六進制顯示。
六、自動顯示
你可以設置一些自動顯示的變量,當程序停住時,或是在你單步跟蹤時,這些變量會自動顯
示。相關的GDB命令是display。
display
display/
display/
expr是一個表達式,fmt表示顯示的格式,addr表示內存地址,當你用display設定好了一
個或多個表達式后,只要你的程序被停下來,GDB會自動顯示你所設置的這些表達式的值。
格式i和s同樣被display支持,一個非常有用的命令是:
display/i $pc
$pc是GDB的環境變量,表示著指令的地址,/i則表示輸出格式為機器指令碼,也就是匯
編。于是當程序停下后,就會出現源代碼和機器指令碼相對應的情形,這是一個很有意思的
功能。
下面是一些和display相關的GDB命令:
undisplay
delete display
刪除自動顯示,dnums意為所設置好了的自動顯式的編號。如果要同時刪除幾個,編號可以
用空格分隔,如果要刪除一個范圍內的編號,可以用減號表示(如:2-5)
disable display
enable display
disable和enalbe不刪除自動顯示的設置,而只是讓其失效和恢復。
info display
查看display設置的自動顯示的信息。GDB會打出一張表格,向你報告當然調試中設置了多
少個自動顯示設置,其中包括,設置的編號,表達式,是否enable。
七、設置顯示選項
GDB中關于顯示的選項比較多,這里我只例舉大多數常用的選項。
set print address
set print address on
打開地址輸出,當程序顯示函數信息時,GDB會顯出函數的參數地址。系統默認為打開的,
如:
(gdb) f
#0 set_quotes (lq=0x34c78 "<<", rq=0x34c88 ">>")
at input.c:530
530 if (lquote != def_lquote)
set print address off
關閉函數的參數地址顯示,如:
(gdb) set print addr off
(gdb) f
#0 set_quotes (lq="<<", rq=">>") at input.c:530
530 if (lquote != def_lquote)
show print address
查看當前地址顯示選項是否打開。
set print array
set print array on
打開數組顯示,打開后當數組顯示時,每個元素占一行,如果不打開的話,每個元素則以逗
號分隔。這個選項默認是關閉的。與之相關的兩個命令如下,我就不再多說了。
set print array off
show print array
set print elements
這個選項主要是設置數組的,如果你的數組太大了,那么就可以指定一個來指定數據顯示的
最大長度,當到達這個長度時,GDB就不再往下顯示了。如果設置為0,則表示不限制。
show print elements
查看print elements的選項信息。
set print null-stop
如果打開了這個選項,那么當顯示字符串時,遇到結束符則停止顯示。這個選項默認為off。
set print pretty on
如果打開printf pretty這個選項,那么當GDB顯示結構體時會比較漂亮。如:
$1 = {
next = 0x0,
flags = {
sweet = 1,
sour = 1
},
meat = 0x54 "Pork"
}
set print pretty off
關閉printf pretty這個選項,GDB顯示結構體時會如下顯示:
$1 = {next = 0x0, flags = {sweet = 1, sour = 1}, meat = 0x54 "Pork"}
show print pretty
查看GDB是如何顯示結構體的。
set print sevenbit-strings
設置字符顯示,是否按“\nnn”的格式顯示,如果打開,則字符串或字符數據按\nnn顯示,
如“\065”。
show print sevenbit-strings
查看字符顯示開關是否打開。
set print union
設置顯示結構體時,是否顯式其內的聯合體數據。例如有以下數據結構:
typedef enum {Tree, Bug} Species;
typedef enum {Big_tree, Acorn, Seedling} Tree_forms;
typedef enum {Caterpillar, Cocoon, Butterfly}
Bug_forms;
struct thing {
Species it;
union {
Tree_forms tree;
Bug_forms bug;
} form;
};
struct thing foo = {Tree, {Acorn}};
當打開這個開關時,執行 p foo 命令后,會如下顯示:
$1 = {it = Tree, form = {tree = Acorn, bug = Cocoon}}
當關閉這個開關時,執行 p foo 命令后,會如下顯示:
$1 = {it = Tree, form = {...}}
show print union
查看聯合體數據的顯示方式
set print object
在C++中,如果一個對象指針指向其派生類,如果打開這個選項,GDB會自動按照虛方法
調用的規則顯示輸出,如果關閉這個選項的話,GDB就不管虛函數表了。這個選項默認是
off。
show print object
查看對象選項的設置。
set print static-members
這個選項表示,當顯示一個C++對象中的內容是,是否顯示其中的靜態數據成員。默認是
on。
show print static-members
查看靜態數據成員選項設置。
set print vtbl
當此選項打開時,GDB將用比較規整的格式來顯示虛函數表時。其默認是關閉的。
show print vtbl
查看虛函數顯示格式的選項。
八、歷史記錄
當你用GDB的print查看程序運行時的數據時,你每一個print都會被GDB記錄下來。GDB
會以$1, $2, $3 .....這樣的方式為你每一個print命令編上號。于是,你可以使用這個編號訪問
以前的表達式,如$1。這個功能所帶來的好處是,如果你先前輸入了一個比較長的表達式,
如果你還想查看這個表達式的值,你可以使用歷史記錄來訪問,省去了重復輸入。
九、GDB環境變量
你可以在GDB的調試環境中定義自己的變量,用來保存一些調試程序中的運行數據。要定
義一個GDB的變量很簡單只需。使用GDB的set命令。GDB的環境變量和UNIX一樣,
也是以$起頭。如:
set $foo = *object_ptr
使用環境變量時,GDB會在你第一次使用時創建這個變量,而在以后的使用中,則直接對
其賦值。環境變量沒有類型,你可以給環境變量定義任一的類型。包括結構體和數組。
show convenience
該命令查看當前所設置的所有的環境變量。
這是一個比較強大的功能,環境變量和程序變量的交互使用,將使得程序調試更為靈活便捷。
例如:
set $i = 0
print bar[$i++]->contents
于是,當你就不必,print bar[0]->contents, print bar[1]->contents地輸入命令了。輸入這樣的
命令后,只用敲回車,重復執行上一條語句,環境變量會自動累加,從而完成逐個輸出的功
能。
十、查看寄存器
要查看寄存器的值,很簡單,可以使用如下命令:
info registers
查看寄存器的情況。(除了浮點寄存器)
info all-registers
查看所有寄存器的情況。(包括浮點寄存器)
info registers
查看所指定的寄存器的情況。
寄存器中放置了程序運行時的數據,比如程序當前運行的指令地址(ip),程序的當前堆棧
地址(sp)等等。你同樣可以使用print命令來訪問寄存器的情況,只需要在寄存器名字前
加一個$符號就可以了。如:p $eip。
改變程序的執行
———————
一旦使用GDB掛上被調試程序,當程序運行起來后,你可以根據自己的調試思路來動態地
在GDB中更改當前被調試程序的運行線路或是其變量的值,這個強大的功能能夠讓你更好
的調試你的程序,比如,你可以在程序的一次運行中走遍程序的所有分支。
一、修改變量值
修改被調試程序運行時的變量值,在GDB中很容易實現,使用GDB的print命令即可完成。
如:
(gdb) print x=4
x=4這個表達式是C/C++的語法,意為把變量x的值修改為4,如果你當前調試的語言是
Pascal,那么你可以使用Pascal的語法:x:=4。
在某些時候,很有可能你的變量和GDB中的參數沖突,如:
(gdb) whatis width
type = double
(gdb) p width
$4 = 13
(gdb) set width=47
Invalid syntax in expression.
因為,set width是GDB的命令,所以,出現了“Invalid syntax in expression”的設置錯誤,
此時,你可以使用set var命令來告訴GDB,width不是你GDB的參數,而是程序的變量名,
如:
(gdb) set var width=47
另外,還可能有些情況,GDB并不報告這種錯誤,所以保險起見,在你改變程序變量取值
時,最好都使用set var格式的GDB命令。
二、跳轉執行
一般來說,被調試程序會按照程序代碼的運行順序依次執行。GDB提供了亂序執行的功能,
也就是說,GDB可以修改程序的執行順序,可以讓程序執行隨意跳躍。這個功能可以由GDB
的jump命令來完:
jump
指定下一條語句的運行點。可以是文件的行號,可以是file:line格式,可以是+num這種偏
移量格式。表式著下一條運行語句從哪里開始。
jump
這里的
是代碼行的內存地址。
注意,jump命令不會改變當前的程序棧中的內容,所以,當你從一個函數跳到另一個函數
時,當函數運行完返回時進行彈棧操作時必然會發生錯誤,可能結果還是非常奇怪的,甚至
于產生程序Core Dump。所以最好是同一個函數中進行跳轉。
熟悉匯編的人都知道,程序運行時,有一個寄存器用于保存當前代碼所在的內存地址。所以,
jump命令也就是改變了這個寄存器中的值。于是,你可以使用“set $pc”來更改跳轉執行
的地址。如:
set $pc = 0x485
三、產生信號量
使用singal命令,可以產生一個信號量給被調試的程序。如:中斷信號Ctrl+C。這非常方便
于程序的調試,可以在程序運行的任意位置設置斷點,并在該斷點用GDB產生一個信號量,
這種精確地在某處產生信號非常有利程序的調試。
語法是:signal ,UNIX的系統信號量通常從1到15。所以取值也在這個范圍。
single命令和shell的kill命令不同,系統的kill命令發信號給被調試程序時,是由GDB截
獲的,而single命令所發出一信號則是直接發給被調試程序的。
四、強制函數返回
如果你的調試斷點在某個函數中,并還有語句沒有執行完。你可以使用return命令強制函數
忽略還沒有執行的語句并返回。
return
return
使用return命令取消當前函數的執行,并立即返回,如果指定了,那么該表達式的值會被認
作函數的返回值。
五、強制調用函數
call
表達式中可以一是函數,以此達到強制調用函數的目的。并顯示函數的返回值,如果函數返
回值是void,那么就不顯示。
另一個相似的命令也可以完成這一功能——print,print后面可以跟表達式,所以也可以用他
來調用函數,print和call的不同是,如果函數返回void,call則不顯示,print則顯示函數返
回值,并把該值存入歷史數據中。
在不同語言中使用GDB
——————————
GDB支持下列語言:C, C++, Fortran, PASCAL, Java, Chill, assembly, 和 Modula-2。一般說
來,GDB會根據你所調試的程序來確定當然的調試語言,比如:發現文件名后綴為“.c”
的,GDB會認為是C程序。文件名后綴為“.C, .cc, .cp, .cpp, .cxx, .c++”的,GDB會認為是
C++程序。而后綴是“.f, .F”的,GDB會認為是Fortran程序,還有,后綴為如果是“.s, .S”
的會認為是匯編語言。
也就是說,GDB會根據你所調試的程序的語言,來設置自己的語言環境,并讓GDB的命令
跟著語言環境的改變而改變。比如一些GDB命令需要用到表達式或變量時,這些表達式或
變量的語法,完全是根據當前的語言環境而改變的。例如C/C++中對指針的語法是*p,而在
Modula-2中則是p^。并且,如果你當前的程序是由幾種不同語言一同編譯成的,那到在調
試過程中,GDB也能根據不同的語言自動地切換語言環境。這種跟著語言環境而改變的功
能,真是體貼開發人員的一種設計。
下面是幾個相關于GDB語言環境的命令:
show language
查看當前的語言環境。如果GDB不能識為你所調試的編程語言,那么,C語言被認為是默
認的環境。
info frame
查看當前函數的程序語言。
info source
查看當前文件的程序語言。
如果GDB沒有檢測出當前的程序語言,那么你也可以手動設置當前的程序語言。使用set
language命令即可做到。
當set language命令后什么也不跟的話,你可以查看GDB所支持的語言種類:
(gdb) set language
The currently understood settings are:
local or auto Automatic setting based on source file
c Use the C language
c++ Use the C++ language
asm Use the Asm language
chill Use the Chill language
fortran Use the Fortran language
java Use the Java language
modula-2 Use the Modula-2 language
pascal Use the Pascal language
scheme Use the Scheme language
于是你可以在set language后跟上被列出來的程序語言名,來設置當前的語言環境。
后記
——
GDB是一個強大的命令行調試工具。大家知道命令行的強大就是在于,其可以形成執行序
列,形成腳本。UNIX下的軟件全是命令行的,這給程序開發提代供了極大的便利,命令行
軟件的優勢在于,它們可以非常容易的集成在一起,使用幾個簡單的已有工具的命令,就可
以做出一個非常強大的功能。
于是UNIX下的軟件比Windows下的軟件更能有機地結合,各自發揮各自的長處,組合成
更為強勁的功能。而Windows下的圖形軟件基本上是各自為營,互相不能調用,很不利于
各種軟件的相互集成。在這里并不是要和Windows做個什么比較,所謂“寸有所長,尺有
所短”,圖形化工具還是有不如命令行的地方。(看到這句話時,希望各位千萬再也不要認為
我就是“鄙視圖形界面”,和我抬杠了 )
我是根據版本為5.1.1的GDB所寫的這篇文章,所以可能有些功能已被修改,或是又有更
為強勁的功能。而且,我寫得非常倉促,寫得比較簡略,并且,其中我已經看到有許多錯別
字了(我用五筆,所以錯字讓你看不懂),所以,我在這里對我文中的差錯表示萬分的歉意。
文中所羅列的GDB的功能時,我只是羅列了一些帶用的GDB的命令和使用方法,其實,
我這里只講述的功能大約只占GDB所有功能的60%吧,詳細的文檔,還是請查看GDB的
幫助和使用手冊吧,或許,過段時間,如果我有空,我再寫一篇GDB的高級使用。
我個人非常喜歡GDB的自動調試的功能,這個功能真的很強大,試想,我在UNIX下寫個
腳本,讓腳本自動編譯我的程序,被自動調試,并把結果報告出來,調試成功,自動checkin
源碼庫。一個命令,編譯帶著調試帶著checkin,多爽啊。只是GDB對自動化調試目前支持
還不是很成熟,只能實現半自動化,真心期望著GDB的自動化調試功能的成熟。
TIFF全名 tag image file format,是一種基于標志域的圖形。
TIFF圖像是靠指針連接來組織數據的,文件頭和數據可以任意數據的存儲。TIFF由四種類型:TIFF-B,二色;TIFF-G,黑白灰度;TIFF-P,帶調色板的彩色圖形;TIFF-R,適合RGB色彩的圖形。
TIFF一般來說由四部分組成:文件頭、文件目錄、目錄內容、圖像數據;如下圖,下面具體說明。
文件頭部分有8個字節,格式為:
0 2 4
II/MM(表示字節序) |
42(版本號) |
文件目錄在整個文件的偏移量,是一個指針,指向IFD的開始部分 |
5 8
注意這里的值不一定就是緊接頭后的
0 2 14
IFD的總項數 |
項1(12個字節) |
項2。。。。(12個字節) |
|
下一個IFD的開始地址(用于保存多個文件) |
每個項的12個字節,其是連續的,有前兩個字節說明其項的總數。對于不同的TIFF格式文件,這里的不同。
每個目錄項由12個字節組成,格式如下:
TAG(2個字節) |
TAG的數據類型 |
數據長度 |
|
數據值或值的偏移(文件范圍) |
TAG的值由TIFF標準定義;不同的TAG表示不同的意思,例如0X0100表示圖像的寬度。
TAG的數據類型表示數據值的類型;例如使用long類型來表示寬度。
數據長度是以數據類型為單位的,真正的數據長度是:數據長度*sizeof(數據類型)
數據值或值的偏移:如果數據長度小于4個字節,一般直接以該字段來表示其值,如果其值大于4個字節,就指定一個文件范圍的偏移地址,從那里開始的“數據長度*sizeof(數據類型)”個字節表示該標志的值。
緊接上面數據之后就是圖像數據了;圖像數據的存儲形式有不同的形式,有以像素位來存儲的,也有以顏色面來存儲的;具體的存儲方式在目錄項中定義。
TAG值 |
說明 |
|
十進制 |
16進制 |
|
256 |
100 |
圖像寬度 |
257 |
101 |
圖像高度 |
258 |
102 |
BitsPerSample,對于RGB是8,8,8,通過偏移來表示 |
259 |
103 |
壓縮方式(1/2/32773),1為不壓縮 |
262 |
106 |
光度滴定,對于RGB圖,該值是2 |
273 |
111 |
帶的偏移,每個帶是不同的 |
277 |
115 |
每像素的顏色成分,對于RGB這個值一般是3,如果需要其他有ExtraSamples標志 |
278 |
116 |
每帶的行數 |
279 |
117 |
每帶中壓縮之后的數據字節常長度 |
284 |
|
每個分量(R,G,B)是怎么存儲的,1表示按照RGBRGB的順序來存儲 |
296 |
128 |
Xresolution和Yresolution的單位 |
更多的參考TIFF標準
在arm-linux環境下運行可執行程序mocp,在加載動態庫libdecoder.so時,卻總是報錯:File not found。在代碼中添加很多printf,找到是在dlopen時報錯。最初以為,是函數dlopen找不到lib_decoder.so文件。那么就認為有以下幾種可能:
1,動態庫給的搜索路徑不對;
2,編譯生成動態庫的編譯工具和程序的運行環境不同;
3,交叉編譯環境不能識別dlopen(當然這個可能性是瞎猜的)。
于是寫了個測試程序并交叉編譯,自己創建一個動態庫libabc.so,并用dlopen加載它。
1,更改動態庫的存放路徑,結果是在任何路徑下都可以找到;
2,用這個正確的測試程序加載libdecoder.so,結果是不管什么路徑,就是找不到;
3,在mocp運行時加載libabd.so,能找到;
結論:只要給了dlopen函數一個路徑,它就能到這個路徑下去尋找指定的庫;都是用arm-linux-uclibc-編譯的,編譯環境相同。那么就是libdecoder.so這個庫本身的問題。
于是將命令從Makefile中抽出來,在shell中單獨運行命令生成這個庫,結果還是找不到。然后把命令簡化,去掉各種選項,比如鏈接選項,僅僅用
arm-linux-uclibc-gcc -fpic -shared snow.c rain.c -o libdecoder.so
生成庫后,測試發現能找到了。添加一個鏈接選項-ldl,又找不到了。
這才想到,libdecoder.so還要加載一個動態庫libdl.so,file not found是不是指的是這個庫找不到啊?查找運行環境下的/lib發現,果然沒有libdl.so文件。把這個庫拷進來,mocp在dlopen的時候就通過了。Done!
其實,如果我在運行程序之前就檢查好這個程序究竟需要那些動態庫,也就不至于花了這么大力氣查找這個問題。
用objdump命令就可以查看目標文件包含的信息,其中就有程序需要鏈接的動態庫。
dlopen - gain access to an executable object file
#include <dlfcn.h>
void *dlopen(const char *file, int mode);
dlopen() makes an executable object file specified by file available to the calling program. The class of files eligible for this operation and the manner of their construction are specified by the implementation, though typically such files are executable objects such as shared libraries, relocatable files or programs. Note that some implementations permit the construction of dependencies between such objects that are embedded within files. In such cases, a dlopen() operation will load such dependencies in addition to the object referenced by file. Implementations may also impose specific constraints on the construction of programs that can employ dlopen() and its related services.A successful dlopen() returns a handle which the caller may use on subsequent calls to dlsym() and dlclose(). The value of this handle should not be interpreted in any way by the caller.
file is used to construct a pathname to the object file. If file contains a slash character, the file argument is used as the pathname for the file. Otherwise, file is used in an implementation-dependent manner to yield a pathname.
If the value of file is 0, dlopen() provides a handle on a global symbol object. This object provides access to the symbols from an ordered set of objects consisting of the original program image file, together with any objects loaded at program startup as specified by that process image file (for example, shared libraries), and the set of objects loaded using a dlopen() operation together with the RTLD_GLOBAL flag. As the latter set of objects can change during execution, the set identified by handle can also change dynamically.
Only a single copy of an object file is brought into the address space, even if dlopen() is invoked multiple times in reference to the file, and even if different pathnames are used to reference the file.
The mode parameter describes how dlopen() will operate upon file with respect to the processing of relocations and the scope of visibility of the symbols provided within file. When an object is brought into the address space of a process, it may contain references to symbols whose addresses are not known until the object is loaded. These references must be relocated before the symbols can be accessed. The mode parameter governs when these relocations take place and may have the following values:
- RTLD_LAZY
- Relocations are performed at an implementation-dependent time, ranging from the time of the dlopen() call until the first reference to a given symbol occurs. Specifying RTLD_LAZY should improve performance on implementations supporting dynamic symbol binding as a process may not reference all of the functions in any given object. And, for systems supporting dynamic symbol resolution for normal process execution, this behaviour mimics the normal handling of process execution.
- RTLD_NOW
- All necessary relocations are performed when the object is first loaded. This may waste some processing if relocations are performed for functions that are never referenced. This behaviour may be useful for applications that need to know as soon as an object is loaded that all symbols referenced during execution will be available.
Any object loaded by dlopen() that requires relocations against global symbols can reference the symbols in the original process image file, any objects loaded at program startup, from the object itself as well as any other object included in the same dlopen() invocation, and any objects that were loaded in any dlopen() invocation and which specified the RTLD_GLOBAL flag. To determine the scope of visibility for the symbols loaded with a dlopen() invocation, the mode parameter should be bitwise or'ed with one of the following values:
- RTLD_GLOBAL
- The object's symbols are made available for the relocation processing of any other object. In addition, symbol lookup using dlopen(0, mode) and an associated dlsym() allows objects loaded with this mode to be searched.
- RTLD_LOCAL
- The object's symbols are not made available for the relocation processing of any other object.
If neither RTLD_GLOBAL nor RTLD_LOCAL are specified, then an implementation-specified default behaviour will be applied.
If a file is specified in multiple dlopen() invocations, mode is interpreted at each invocation. Note, however, that once RTLD_NOW has been specified all relocations will have been completed rendering further RTLD_NOW operations redundant and any further RTLD_LAZY operations irrelevant. Similarly note that once RTLD_GLOBAL has been specified the object will maintain the RTLD_GLOBAL status regardless of any previous or future specification of RTLD_LOCAL, so long as the object remains in the address space (see dlclose()).
Symbols introduced into a program through calls to dlopen() may be used in relocation activities. Symbols so introduced may duplicate symbols already defined by the program or previous dlopen() operations. To resolve the ambiguities such a situation might present, the resolution of a symbol reference to symbol definition is based on a symbol resolution order. Two such resolution orders are defined: load or dependency ordering. Load order establishes an ordering among symbol definitions, such that the definition first loaded (including definitions from the image file and any dependent objects loaded with it) has priority over objects added later (via dlopen()). Load ordering is used in relocation processing. Dependency ordering uses a breadth-first order starting with a given object, then all of its dependencies, then any dependents of those, iterating until all dependencies are satisfied. With the exception of the global symbol object obtained via a dlopen() operation on a file of 0, dependency ordering is used by the dlsym() function. Load ordering is used in dlsym() operations upon the global symbol object.
When an object is first made accessible via dlopen() it and its dependent objects are added in dependency order. Once all the objects are added, relocations are performed using load order. Note that if an object or its dependencies had been previously loaded, the load and dependency orders may yield different resolutions.
The symbols introduced by dlopen() operations, and available through dlsym() are at a minimum those which are exported as symbols of global scope by the object. Typically such symbols will be those that were specified in (for example) C source code as having extern linkage. The precise manner in which an implementation constructs the set of exported symbols for a dlopen() object is specified by that implementation.
If file cannot be found, cannot be opened for reading, is not of an appropriate object format for processing by dlopen(), or if an error occurs during the process of loading file or relocating its symbolic references, dlopen() will return NULL. More detailed diagnostic information will be available through dlerror().
No errors are defined.
None.
None.
None.
dlclose(), dlerror(), dlsym().
Android 開機會出現3個畫面:
a. Linux 系統啟動,出現Linux小企鵝畫面(reboot);
b. Android平臺啟動初始化,出現"A N D R I O D"文字字樣畫面;
c. Android平臺圖形系統啟動,出現含閃動的ANDROID字樣的動畫圖片(start)。
1/ 開機圖片(Linux小企鵝)
Linux Kernel引導啟動后,加載該圖片。
/kernel/trunk/drivers/video/fbmem.c
/kernel/trunk/drivers/video/fbmem.h
/kernel/trunk/drivers/video/logo/logo.c
/kernel/trunk/drivers/video/logo/logo.h
/kernel/trunk/drivers/video/logo/Kconfig
/kernel/trunk/include/linux/linux_logo.h
2/ 開機文字("A N D R I O D")
Android 系統啟動后,讀取 /initlogo.rle(一張565 rle壓縮的位圖),如果讀取成功,測在/dev/graphics/fb0顯示Logo圖片;如果讀取失敗,則將/dev/tty0設為TEXT模式, 并打開/dev/tty0,輸出文本“A N D R I O D”字樣。
相關代碼:
/system/core/init/init.c
/system/core/init/init.h
/system/core/init/init.rc
/system/core/init/logo.c
*.rle文件的制作步驟:
a. 使用GIMP或者Advanced Batch Converter軟件,將圖象轉換為RAW格式;
b. 使用android自帶的rgb2565工具,將RAW格式文件轉換為RLE格式(如:rgb2565 -rle < initlogo.raw > initlogo.rle)。
3/ 開機動畫(閃動的ANDROID字樣的動畫圖片)
Android 的系統登錄動畫類似于Windows系統的滾動條,是由前景和背景兩張PNG圖片組成,這兩張圖片存在于/system/framework /framework-res.apk文件當中。前景圖片(android-logo-mask.png)上的Android文字部分鏤空,背景圖片 (android-logo-shine.png)則是簡單的紋理。系統登錄時,前景圖片在最上層顯示,程序代碼控制背景圖片連續滾動,透過前景圖片文字 鏤空部分滾動顯示背景紋理,從而實現動畫效果。
相關代碼:
/frameworks/base/libs/surfaceflinger/BootAnimation.h
/frameworks/base/libs/surfaceflinger/BootAnimation.cpp
/frameworks/base/core/res/assets/images/android-logo-mask.png
Android默認的前景圖片,文字部分鏤空,大小256×64
/frameworks/base/core/res/assets/images/android-logo-shine.png
Android默認的背景圖片,有動感效果,大小512×64
參考文檔:
圖說Android開機畫面和開機動畫
http://www.shudoo.com/09/1030/15/13418431.html
initlogo.rle: display an image on boot
http://forum.xda-developers.com/showthread.php?t=443431
分析Android 根文件系統啟動過程(init守護進程分析)
http://crazier9527.javaeye.com/blog/454635
Martin Belcher | 26th May 2010 | ||||||||
Intro
This article describes how to force the orientation of an Android view not to change ie screen not to rotate. How to lock the orientationIn the onCreateDialog(int) event of the activity use the setRequestedOrientation(int) method to set the screen orientation to your chosen setting. The activity will stay in this orientation regardless of if the device is tilted or not.
How to detect the current orientationTo programmatically detect the current orientation of the activity use the following code snippet. Theorientation property of the Configuration class returns three possible values corresponding to Landscape, Portrait and Square.
Example : Locking rotation while performing an action.You might wish to disable the screen rotation whilst performing an action or by user command, to do this you need to combine the above samples to detect the current orientation and lock the display to that orientation.
Once your action has completed you may wish to enable screen rotation again, see the next section for an example on how to do this. How to re-enable screen rotationTo enable the orientation to be automatically changed on device tilt simply pass thesetRequestedOrientation(int) method the enumeration value for an unspecified orientation.
|
G1帶有實體鍵盤,可以側推。雖然如今的G2 G3去掉了實體鍵盤,但同志們開發的應用還是得兼容一下G1吧。先從幾個問題入手:
1、不管鍵盤是否滑出,都要設置屏幕為豎屏或者橫屏。這個該怎么處理?
2、當用戶在豎屏狀態下編輯了一個文本框,又突然想推出實體鍵盤進行編輯,而此時Activity重繪,文本框內未保存的信息又該怎么辦?
3、監聽鍵盤滑動事件。讓縱橫屏狀態下載入不同的layout。
當然你也許可以再java代碼中去設置很多事件捕獲,但有一個更好的方法,那就是修改Androidmanifest.xml.
默認的情況下推出或縮進鍵盤會重新啟動activity
要不關閉activity 則可以在manifest.xml中增加 android:configChanges=”keyboardHidden|orientation”
然后重載public void onConfigurationChanged(Configuration newConfig) 函數
鍵盤被抽出后會首先調用onConfigurationChanged
如果你希望滑動鍵盤不改變屏幕分辨率 則可以增加屬性:android:screenOrientation=”portrait“>
portrait :豎
landscape: 橫
sensor:根據手機的角度自動調整
詳細說明:
<activity …
android:configChanges=[one or more of: "mcc" "mnc" "locale"
"touchscreen" "keyboard" "keyboardHidden"
"navigation" "orientation" "fontScale"]
…
</activity>
android:configChanges
Lists configuration changes that the activity will handle itself. When changes that are not listed occur, the activity is shut down and restarted. When a listed change occurs, the activity remains running and its onConfigurationChanged() method is called.
Any or all of the following strings can be used to set this attribute. Values are separated by ‘|’ — for example, “locale|navigation|orientation”.
Value Description
“mcc” The IMSI mobile country code (MCC) has changed — that is, a SIM has been detected and updated the MCC.
“mnc” The IMSI mobile network code (MNC) has changed — that is, a SIM has been detected and updated the MNC.
“locale” The locale has changed — for example, the user has selected a new language that text should be displayed in.
“touchscreen” The touchscreen has changed. (This should never normally happen.)
“keyboard” The keyboard type has changed — for example, the user has plugged in an external keyboard.
“keyboardHidden” The keyboard accessibility has changed — for example, the user has slid the keyboard out to expose it.
“navigation” The navigation type has changed. (This should never normally happen.)
“orientation” The screen orientation has changed — that is, the user has rotated the device.
“fontScale” The font scaling factor has changed — that is, the user has selected a new global font size.
All of these configuration changes can impact the resource values seen by the application. Therefore, when onConfigurationChanged() is called, it will generally be necessary to again retrieve all resources (including view layouts, drawables, and so on) to correctly handle the change.
//----------
//main.cpp:
//----------
#include <iostream>
#include <dlfcn.h>
int main()
{
using std::cout;
using std::cerr;
cout << "C++ dlopen demo\n\n";
// open the library
cout << "Opening hello.so...\n";
void* handle = dlopen("./hello.so", RTLD_LAZY);
if (!handle) {
cerr << "Cannot open library: " << dlerror() << '\n';
return 1;
}
// load the symbol
cout << "Loading symbol hello...\n";
typedef void (*hello_t)();
// reset errors
dlerror();
hello_t hello = (hello_t) dlsym(handle, "hello");
const char *dlsym_error = dlerror();
if (dlsym_error) {
cerr << "Cannot load symbol 'hello': " << dlsym_error <<'\n';
dlclose(handle);
return 1;
}
// use it to do the calculation
cout << "Calling hello...\n";
hello();
// close the library
cout << "Closing library...\n";
dlclose(handle);
}
//----------
// hello.cpp:
//----------
#include <iostream>
extern "C" void hello()
{
std::cout << "hello" << '\n';
}
extern "C" int foo;
extern "C" void bar();
extern "C"
{
extern int foo;
extern void bar();
}
extern "C" int foo;
extern "C"
{
int foo;
}
//----------
//main.cpp:
//----------
#include "polygon.hpp"
#include <iostream>
#include <dlfcn.h>
int main()
{
using std::cout;
using std::cerr;
// load the triangle library
void* triangle = dlopen("./triangle.so", RTLD_LAZY);
if (!triangle)
{
cerr << "Cannot load library: " << dlerror() << '\n';
return 1;
}
// reset errors
dlerror();
// load the symbols
create_t* create_triangle = (create_t*) dlsym(triangle, "create");
const char* dlsym_error = dlerror();
if (dlsym_error)
{
cerr << "Cannot load symbol create: " << dlsym_error << '\n';
return 1;
}
destroy_t* destroy_triangle = (destroy_t*) dlsym(triangle, "destroy");
dlsym_error = dlerror();
if (dlsym_error)
{
cerr << "Cannot load symbol destroy: " << dlsym_error << '\n';
return 1;
}
// create an instance of the class
polygon* poly = create_triangle();
// use the class
poly->set_side_length(7);
cout << "The area is: " << poly->area() << '\n';
// destroy the class
destroy_triangle(poly);
// unload the triangle library
dlclose(triangle);
}
//----------
//polygon.hpp:
//----------
#ifndef POLYGON_HPP
#define POLYGON_HPP
class polygon
{
protected:
double side_length_;
public:
polygon()
:side_length_(0) {}
virtual ~polygon() {}
void set_side_length(double side_length)
{
side_length_ = side_length;
}
virtual double area() const = 0;
};
// the types of the class factories
typedef polygon* create_t();
typedef void destroy_t(polygon*);
#endif
//----------
//triangle.cpp:
//----------
#include "polygon.hpp"
#include <cmath>
class triangle : public polygon
{
public:
virtual double area() const
{
return side_length_ * side_length_ * sqrt(3) / 2;
}
};
// the class factories
extern "C" polygon* create()
{
return new triangle;
}
extern "C" void destroy(polygon* p)
{
delete p;
}
Status: Draft (as of May 18, 2006)
It needs to be possible to build the Android platform for multiple targets. This means:
To achieve the objectives, the build system will be rewritten to use make non-recursively. For more background on this, read Recursive Make Considered Harmful. For those that don't want PDF, here is the Google translated version.
When developing a component, for example a C++ shared library, it must be possible to easily rebuild just that component, and not have to wait more than a couple seconds for dependency checks, and not have to wait for unneeded components to be built.
To set the target, and other options, some people on the team like to have a configuration file in a directory so they do not have an environment setup script to run, and others want an environment setup script to run so they can run builds in different terminals on the same tree, or switch back and forth in one terminal. We will support both.
Object files and other intermediate files will be generated into a directory
that is separate from the source tree. The goal is to have make clean be
"rm -rf
The SDK will be a tarball that will allow non-OS-developers to write apps. The apps will actually be built by first building the SDK, and then building the apps against that SDK. This will hopefully (1) make writing apps easier for us, because we won't have to rebuild the OS as much, and we can use the standard java-app development tools, and (2) allow us to dog-food the SDK, to help ensure its quality. Cedric has suggested (and I agree) that apps built from the SDK should be built with ant. Stay tuned for more details as we figure out exactly how this will work.
Dependencies should all be automatic. Unless there is a custom tool involved (e.g. the webkit has several), the dependencies for shared and static libraries, .c, .cpp, .h, .java, java libraries, etc., should all work without intervention in the Android.mk file.
The default of the build system will be to hide the command lines being executed for make steps. It will be possible to override this by specifying the showcommands pseudo-target, and possibly by setting an environment variable.
Wildcarding source file will be discouraged. It may be useful in some
scenarios. The default $(wildcard *)
will not work due to the
current directory being set to the root of the build tree.
It will be possible to generate more than one target from a given subdirectory. For example, libutils generates a shared library for the target and a static library for the host.
Android.mk is the standard name for the makefile fragments that control the building of a given module. Only the top directory should have a file named "Makefile".
Currently, the simulator is not built to use shared libraries. This should be fixed, and now is a good time to do it. This implies getting shared libraries to work on Mac OS.
These things would be nice to have, and this is a good place to record them, however these are not promises.
The hope is to be able to do two builds for different combos in the same tree at the same time, but this is a stretch goal, not a requirement. Doing two builds in the same tree, not at the same time must work. (update: it's looking like we'll get the two builds at the same time working)
Problems can arise if you delete a header file that is referenced in ".d" files. The easy way to deal with this is "make clean". There should be a better way to handle it. (from fadden)
One way of solving this is introducing a dependency on the directory. The problem is that this can create extra dependecies and slow down the build. It's a tradeoff.
General way to perform builds across the set of known platforms. This would make it easy to perform multiple platform builds when testing a change, and allow a wide-scale "make clean". Right now the buildspec.mk or environment variables need to be updated before each build. (from fadden)
We will eventually need to add support for creating locales and carrier customizations to the SDK, but that will not be addressed right now.
The Building document describes how do do builds.
. build/envsetup.sh
you'll get a few helpful shell functions:
make
from the top of the tree. This is
useful because you can run make from within subdirectories. If you have the
TOP
environment variable set, it uses that. If you don't, it looks
up the tree from the current directory, trying to find the top of the tree.cd
to the top of the tree.When building for a particular product, it's often useful to have minor variations on what is ultimately the final release build. These are the currently-defined "flavors" or "types" (we need to settle on a real name for these).
eng |
This is the default flavor. A plain "make " is the
same as "make eng ". droid is an alias
for eng .
|
user |
"make user "
This is the flavor intended to be the final release bits.
|
userdebug |
"make userdebug "
The same as
|
If you build one flavor and then want to build another, you should run
"make installclean
" between the two makes to guarantee that
you don't pick up files installed by the previous flavor. "make
clean
" will also suffice, but it takes a lot longer.
Sometimes you want to just build one thing. The following pseudotargets are there for your convenience:
make droid
is the normal build. This target
is here because the default target has to have a name.make all
builds everything make
droid
does, plus everything whose LOCAL_MODULE_TAGS
do not
include the "droid" tag. The build server runs this to make sure
that everything that is in the tree and has an Android.mk builds.make clean-libutils
and it will delete libutils.so and all of the
intermediate files, or you can type make clean-Home
and it will
clean just the Home app.make clean
deletes all of the output and
intermediate files for this configuration. This is the same as rm -rf
out/<configuration>/
make clobber
deletes all of the output
and intermediate files for all configurations. This is the same as
rm -rf out/
.make dataclean
deletes contents of the data
directory inside the current combo directory. This is especially useful on the
simulator and emulator, where the persistent data remains present between
builds.showcommands
is a modifier target
which causes the build system to show the actual command lines for the build
steps, instead of the brief descriptions. Most people don't like seeing the
actual commands, because they're quite long and hard to read, but if you need
to for debugging purposes, you can add showcommands
to the list
of targets you build. For example make showcommands
will build
the default android configuration, and make runtime showcommands
will build just the runtime, and targets that it depends on, while displaying
the full command lines. Please note that there are a couple places where the
commands aren't shown here. These are considered bugs, and should be fixed,
but they're often hard to track down. Please let
android-build-team know if you find
any.LOCAL_MODULE
in an Android.mk is made into a pseudotarget. For example, make
runtime
might be shorthand for make
out/linux-x86-debug/system/bin/runtime
(which would work), and
make libkjs
might be shorthand for make
out/linux-x86-debug/system/lib/libkjs.so
(which would also work).make targets
will print a list of all of
the LOCAL_MODULE names you can make.This template is pretty self-explanitory. See the variables below for more details.
Use the templates/java_library
file.
Use the templates/executable
file, or the
templates/executable_host
file.
By default, on the target these are built into /system/bin, and on the
host, they're built into LOCAL_MODULE_PATH
. See
Use the templates/shared_library
file, or the
templates/shared_library_host
file.
Remember that on the target, we use shared libraries, and on the host, we use static libraries, since executable size isn't as big an issue, and it simplifies distribution in the SDK.
Use the templates/static_library
file, or the
templates/static_library_host
file.
Remember that on the target, we use shared libraries, and on the host, we use static libraries, since executable size isn't as big an issue, and it simplifies distribution in the SDK.
intermediates:= $(local-intermediates-dir)
GEN := $(intermediates)/chartables.c
$(GEN): PRIVATE_CUSTOM_TOOL = $(HOST_OUT_EXECUTABLES)/dftables $@
$(GEN): $(HOST_OUT_EXECUTABLES)/dftables
$(transform-generated-source)
LOCAL_GENERATED_SOURCES += $(GEN)
intermediates:= $(local-intermediates-dir)
GEN := $(intermediates)/file.c
$(GEN): PRIVATE_INPUT_FILE := $(LOCAL_PATH)/input.file
$(GEN): PRIVATE_CUSTOM_TOOL = cat $(PRIVATE_INPUT_FILE) > $@
$(GEN): $(LOCAL_PATH)/file.c
$(transform-generated-source)
LOCAL_GENERATED_SOURCES += $(GEN)
intermediates:= $(local-intermediates-dir)
GEN := $(addprefix $(intermediates)/kjs/, \
array_object.lut.h \
bool_object.lut.h \
)
$(GEN): PRIVATE_CUSTOM_TOOL = perl libs/WebKitLib/WebKit/JavaScriptCore/kjs/create_hash_table $< -i > $@
$(GEN): $(intermediates)/%.lut.h : $(LOCAL_PATH)/%.cpp
$(transform-generated-source)
LOCAL_GENERATED_SOURCES += $(GEN)
For a device build, TARGET_OS
is linux
(we're using
linux!), and TARGET_ARCH
is arm
.
HOST_OS linux darwin (cygwin) |
HOST_ARCH x86 |
HOST_BUILD_TYPE release debug |
|
TARGET_OS linux darwin (cygwin) |
TARGET_ARCH arm x86 |
TARGET_BUILD_TYPE release debug |
TARGET_PRODUCT sim dream sooner |
ifeq ($(TARGET_SIMULATOR),true)
LOCAL_CFLAGS += -DSIMULATOR
endif
ifeq ($(TARGET_BUILD_TYPE),release)
LOCAL_CFLAGS += -DNDEBUG=1
endif
# from libutils
ifeq ($(TARGET_OS),linux)
# Use the futex based mutex and condition variable
# implementation from android-arm because it's shared mem safe
LOCAL_SRC_FILES += futex_synchro.c
LOCAL_LDLIBS += -lrt -ldl
endif
LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT_SBIN)
LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_SBIN_UNSTRIPPED)
Look in config/envsetup.make
for all of the variables defining
places to build things.
These are the variables that you'll commonly see in Android.mk files, listed alphabetically.
But first, a note on variable naming:
include $(CLEAR_VARS)
line, so you can rely on them
being empty after including that file. Most of the variables you'll use
in most modules are LOCAL_ variables.In Android.mk files that include $(BUILD_PACKAGE)
set this
to the set of files you want built into your app. Usually:
LOCAL_ASSET_FILES += $(call find-subdir-assets)
This will probably change when we switch to ant for the apps' build system.
If you want to use a different C compiler for this module, set LOCAL_CC to the path to the compiler. If LOCAL_CC is blank, the appropriate default compiler is used.
If you want to use a different C++ compiler for this module, set LOCAL_CXX to the path to the compiler. If LOCAL_CXX is blank, the appropriate default compiler is used.
If you have additional flags to pass into the C or C++ compiler, add them here. For example:
LOCAL_CFLAGS += -DLIBUTILS_NATIVE=1
If you have additional flags to pass into only the C++ compiler, add them here. For example:
LOCAL_CPPFLAGS += -ffriend-injection
LOCAL_CPPFLAGS
is guaranteed to be after LOCAL_CFLAGS
on the compile line, so you can use it to override flags listed in
LOCAL_CFLAGS
.
If your C++ files end in something other than ".cpp
",
you can specify the custom extension here. For example:
LOCAL_CPP_EXTENSION := .cc
Normally, the compile line for C and C++ files includes global include
paths and global cflags. If LOCAL_NO_DEFAULT_COMPILER_FLAGS
is non-empty, none of the default includes or flags will be used when compiling
C and C++ files in this module.
LOCAL_C_INCLUDES
, LOCAL_CFLAGS
, and
LOCAL_CPPFLAGS
will still be used in this case, as will
any DEBUG_CFLAGS
that are defined for the module.
This will be going away.
The set of files to copy to the install include tree. You must also
supply LOCAL_COPY_HEADERS_TO
.
This is going away because copying headers messes up the error messages, and may lead to people editing those headers instead of the correct ones. It also makes it easier to do bad layering in the system, which we want to avoid. We also aren't doing a C/C++ SDK, so there is no ultimate requirement to copy any headers.
This will be going away.
The directory within "include" to copy the headers listed in
LOCAL_COPY_HEADERS
to.
This is going away because copying headers messes up the error messages, and may lead to people editing those headers instead of the correct ones. It also makes it easier to do bad layering in the system, which we want to avoid. We also aren't doing a C/C++ SDK, so there is no ultimate requirement to copy any headers.
Additional directories to instruct the C/C++ compilers to look for header
files in. These paths are rooted at the top of the tree. Use
LOCAL_PATH
if you have subdirectories of your own that you
want in the include paths. For example:
LOCAL_C_INCLUDES += extlibs/zlib-1.2.3
LOCAL_C_INCLUDES += $(LOCAL_PATH)/src
You should not add subdirectories of include to
LOCAL_C_INCLUDES
, instead you should reference those files
in the #include
statement with their subdirectories. For
example:
#include <utils/KeyedVector.h>
not #include <KeyedVector.h>
There are some components that are doing this wrong, and should be cleaned up.
Set LOCAL_MODULE_TAGS
to any number of whitespace-separated
tags. If the tag list is empty or contains droid
, the module
will get installed as part of a make droid
. Otherwise, it will
only get installed by running make <your-module>
or with the make all
pseudotarget.
Set LOCAL_REQUIRED_MODULES
to any number of whitespace-separated
module names, like "libblah" or "Email". If this module is installed, all
of the modules that it requires will be installed as well. This can be
used to, e.g., ensure that necessary shared libraries or providers are
installed when a given app is installed.
If your executable should be linked statically, set
LOCAL_FORCE_STATIC_EXECUTABLE:=true
. There is a very short
list of libraries that we have in static form (currently only libc). This is
really only used for executables in /sbin on the root filesystem.
Files that you add to LOCAL_GENERATED_SOURCES
will be
automatically generated and then linked in when your module is built.
See the Custom Tools template makefile for an
example.
When linking Java apps and libraries, LOCAL_JAVA_LIBRARIES
specifies which sets of java classes to include. Currently there are
two of these: core
and framework
.
In most cases, it will look like this:
LOCAL_JAVA_LIBRARIES := core framework
Note that setting LOCAL_JAVA_LIBRARIES
is not necessary
(and is not allowed) when building an APK with
"include $(BUILD_PACKAGE)
". The appropriate libraries
will be included automatically.
You can pass additional flags to the linker by setting
LOCAL_LDFLAGS
. Keep in mind that the order of parameters is
very important to ld, so test whatever you do on all platforms.
LOCAL_LDLIBS
allows you to specify additional libraries
that are not part of the build for your executable or library. Specify
the libraries you want in -lxxx format; they're passed directly to the
link line. However, keep in mind that there will be no dependency generated
for these libraries. It's most useful in simulator builds where you want
to use a library preinstalled on the host. The linker (ld) is a particularly
fussy beast, so it's sometimes necessary to pass other flags here if you're
doing something sneaky. Some examples:
LOCAL_LDLIBS += -lcurses -lpthread
LOCAL_LDLIBS += -Wl,-z,origin
If your package doesn't have a manifest (AndroidManifest.xml), then
set LOCAL_NO_MANIFEST:=true
. The common resources package
does this.
LOCAL_PACKAGE_NAME
is the name of an app. For example,
Dialer, Contacts, etc. This will probably change or go away when we switch
to an ant-based build system for the apps.
The directory your Android.mk file is in. You can set it by putting the following as the first line in your Android.mk:
LOCAL_PATH := $(my-dir)
The my-dir
macro uses the
MAKEFILE_LIST
variable, so you must call it before you include any other makefiles. Also,
consider that any subdirectories you inlcude might reset LOCAL_PATH, so do your
own stuff before you include them. This also means that if you try to write
several include
lines that reference LOCAL_PATH
,
it won't work, because those included makefiles might reset LOCAL_PATH.
For host executables, you can specify a command to run on the module after it's been linked. You might have to go through some contortions to get variables right because of early or late variable evaluation:
module := $(HOST_OUT_EXECUTABLES)/$(LOCAL_MODULE)
LOCAL_POST_PROCESS_COMMAND := /Developer/Tools/Rez -d __DARWIN__ -t APPL\
-d __WXMAC__ -o $(module) Carbon.r
When including $(BUILD_PREBUILT) or $(BUILD_HOST_PREBUILT), set these to executables that you want copied. They're located automatically into the right bin directory.
When including $(BUILD_PREBUILT) or $(BUILD_HOST_PREBUILT), set these to libraries that you want copied. They're located automatically into the right lib directory.
These are the libraries you directly link against. You don't need to pass transitively included libraries. Specify the name without the suffix:
LOCAL_SHARED_LIBRARIES := \
libutils \
libui \
libaudio \
libexpat \
libsgl
The build system looks at LOCAL_SRC_FILES
to know what source
files to compile -- .cpp .c .y .l .java. For lex and yacc files, it knows
how to correctly do the intermediate .h and .c/.cpp files automatically. If
the files are in a subdirectory of the one containing the Android.mk, prefix
them with the directory name:
LOCAL_SRC_FILES := \
file1.cpp \
dir/file2.cpp
These are the static libraries that you want to include in your module. Mostly, we use shared libraries, but there are a couple of places, like executables in sbin and host executables where we use static libraries instead.
LOCAL_STATIC_LIBRARIES := \
libutils \
libtinyxml
LOCAL_MODULE
is the name of what's supposed to be generated
from your Android.mk. For exmample, for libkjs, the LOCAL_MODULE
is "libkjs" (the build system adds the appropriate suffix -- .so .dylib .dll).
For app modules, use LOCAL_PACKAGE_NAME
instead of
LOCAL_MODULE
. We're planning on switching to ant for the apps,
so this might become moot.
Instructs the build system to put the module somewhere other than what's
normal for its type. If you override this, make sure you also set
LOCAL_UNSTRIPPED_PATH
if it's an executable or a shared library
so the unstripped binary has somewhere to go. An error will occur if you forget
to.
See Putting modules elsewhere for more.
Instructs the build system to put the unstripped version of the module
somewhere other than what's normal for its type. Usually, you override this
because you overrode LOCAL_MODULE_PATH
for an executable or a
shared library. If you overrode LOCAL_MODULE_PATH
, but not
LOCAL_UNSTRIPPED_PATH
, an error will occur.
See Putting modules elsewhere for more.
These are the static libraries that you want to include in your module without allowing the linker to remove dead code from them. This is mostly useful if you want to add a static library to a shared library and have the static library's content exposed from the shared library.
LOCAL_WHOLE_STATIC_LIBRARIES := \
libsqlite3_android
Any flags to pass to invocations of yacc for your module. A known limitation here is that the flags will be the same for all invocations of YACC for your module. This can be fixed. If you ever need it to be, just ask.
LOCAL_YACCFLAGS := -p kjsyy
You should never have to touch anything in the config directory unless you're adding a new platform, new tools, or adding new features to the build system. In general, please consult with the build system owner(s) (android-build-team) before you go mucking around in here. That said, here are some notes on what's going on under the hood.
In order to make easier for people when the build system changes, when it is necessary to make changes to buildspec.mk or to rerun the environment setup scripts, they contain a version number in the variable BUILD_ENV_SEQUENCE_NUMBER. If this variable does not match what the build system expects, it fails printing an error message explaining what happened. If you make a change that requires an update, you need to update two places so this message will be printed.
You probably shouldn't use these variables. Please consult android-build-team before using them. These are mostly there for workarounds for other issues, or things that aren't completely done right.
If your module needs to depend on anything else that
isn't actually built in to it, you can add those make targets to
LOCAL_ADDITIONAL_DEPENDENCIES
. Usually this is a workaround
for some other dependency that isn't created automatically.
When a module is built, the module is created in an intermediate directory then copied to its final location. LOCAL_BUILT_MODULE is the full path to the intermediate file. See LOCAL_INSTALLED_MODULE for the path to the final installed location of the module.
Set by the host_xxx.make includes to tell base_rules.make and the other includes that we're building for the host. Kenneth did this as part of openbinder, and I would like to clean it up so the rules, includes and definitions aren't duplicated for host and target.
The fully qualified path name of the final location of the module. See LOCAL_BUILT_MODULE for the location of the intermediate file that the make rules should actually be constructing.
Used in some stuff remaining from the openbinder for building scripts with particular values set,
Used in some stuff remaining from the openbinder build system that we might find handy some day.
Which kind of module this is. This variable is used to construct other variable names used to locate the modules. See base_rules.make and envsetup.make.
Set to the leaf name of the LOCAL_BUILT_MODULE. I'm not sure, but it looks like it's just used in the WHO_AM_I variable to identify in the pretty printing what's being built.
The suffix that will be appended to LOCAL_MODULE
to form
LOCAL_MODULE_NAME
. For example, .so, .a, .dylib.
Calculated in base_rules.make to determine if this module should actually
be stripped or not, based on whether LOCAL_STRIPPABLE_MODULE
is set, and whether the combo is configured to ever strip modules. With
Iliyan's stripping tool, this might change.
Set by the include makefiles if that type of module is strippable. Executables and shared libraries are.
Used while building the base libraries: libc, libm, libdl. Usually it should be set to "none," as it is in $(CLEAR_VARS). When building these libraries, it's set to the ones they link against. For example, libc, libstdc++ and libdl don't link against anything, and libm links against libc. Normally, when the value is none, these libraries are automatically linked in to executables and libraries, so you don't need to specify them manually.
通過程序獲取android系統手機的鈴聲和音量。同樣,設置鈴聲和音量的方法也很簡單!
//通話音量
//系統音量
//鈴聲音量
//音樂音量
//提示聲音音量
設置音量的方法也很簡單,AudioManager提供了方法:
public void setStreamVolume(int streamType, int index, int flags)
其中 streamType 有內置的常量,去文檔里面就可以看到
當你創建工程時,系統幫助生成一個原始的 manifest文件。對于只包含一個 activity的簡單的應用程序,原始的 manifest文件夠了,或者只需要很小的改動。另外, manifest也可以很復雜,比如 Android自帶的 API樣例,該文件就超過 1000多行。你的應用程序的 manifest行數大概也就介于此間吧。
manifest文件的大部分有趣的功能會在以后相應的章節更加詳細的介紹。比如 service元素會在創建 service章節詳細講述。現在,主要關注 manifest文件的作用和它的一般結構。
在文件開始,有根,文件基本上就正確
manifest文件的根是這樣一個 manifest元素:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.commonsware.android.search">
...
</manifest>
注意命名空間聲明。奇怪的是,自動生成的 manifest文件,命名空間是應用在屬性上,而不是元素上(例如,是 manifest,不是 android:manifest),然而,這種形式工作正確,只要 android不發生改變,就堅持用這種形式。
根元素 manifest里面最有用的信息是 package屬性(奇怪的是 package前沒有命名空間)。這里,你可填成你的 java package的名子,以后在 manifest文件里,如果需要類的名子,就可以用點來代替 package的名子,例如:如果在 manifest文件需要引用 com.commonsware.android.search.Snicklefritz,你就可以寫成 .Snicklefitz,因為 com.commonsware.android.search已經被定義成應用程序的包。
權限,特殊工具,和應用程序
在 manifest元素里有如下子元素:
l uses-permission元素,表示應用程序必須據有這些權限才能工作正常- permissions章節
l permission元素,定義一些權限,當其它的程序如果想使用你的程序的數據或者邏輯時,必須據有這些權限,參考 permissions章節
l instrumentation元素,表示某些代碼,當一些重要的系統事件發生時,這些代碼被調用,例如:啟動一個 activities,打印 log或者監視某些信息。
l uses-library元素,掛鉤( hook)進可選的 android組件里,例如 mapping services。
l application元素,定義 manifest描述的應用程序的細節。
在上面的例子中, uses-permission元素表明了應用程序將要使用的一些設備的功能,在這個例子中,就是程序據有了定位自己的功能。 applicaton元素描述了一些 activities, serives和其它組成應用的一些組件。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.commonsware.android">
<uses-permission
android:name="android.permission.ACCESS_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_GPS" />
<uses-permission
android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission
android:name="android.permission.ACCESS_CELL_ID" />
<application>
...
</application>
</manifest>
應用程序需要實現一些功能,對嗎?
manifest文件最重要的部分就是 application元素的子元素。
創建新工程時,默認生成只含一個 activity元素的 manifest文件,如下:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.commonsware.android.skeleton">
<application>
<activity android:name=".Now" android:label="Now">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
這個 activity元素提供了如下信息, android:name-實現 activity的類;和 android:label-當運行 activity時顯示的名字; intent-filter子元素-描述在什么條件下 activity才顯示。這個 activity元素設置在運行時顯示這個 activity,現在你可以運行它了。在后面的章節,會看到有多個 activities的工程。
可能還會有一個或者多個 receiver元素,表示在一定條件下,一些非 activites組件需要被觸發,例如收到一條短信。這被稱作是 intent receivers,在后續章節會講到。
可能還會有一個或者多個 provider元素,表示 content providers組件,它們負責提供數據給 activities使用,并且,如果有權限,其它應用程序也可以使用它們提供的數據。它們把數據庫或者其它數據存儲包裝成一個接口 供其它應用程序使用。后續章節會講怎么創建 content provides和如何使用 content provides。
最后,可能會有一個或者多個 service元素,描述 services-獨立于 activity,并且長期運行的一些代碼片段。最好的例子就是 mp3播放器,你想邊聽音樂,邊打開其它 activities,這時候 mp3播放器的使用界面被覆蓋。后面有兩章會講如何創建和使用 services。