2012/08/04

工欲善其事,必先利其器:GDB 基本教學

最基本的編譯時要加"-g",把 debugging information 編譯進去,否則印不出什麼資訊來。再來就是不要做 optimize,不然程式碼行數會對不上。
$ gcc -g -o hello hello.c

啟動 GDB
$ gdb ./hello

必要時加入"-d (dirctory)"的參數,指定 source code 的位置
$ gdb -d /home/brian/test ./hello 

若程式已經在執行了,可以先查詢 pid,然後用 attach 的方式。記得 binary 的要跟正在 run 的 program 一致
$ gdb ./hello 12238

進入GDB後執行程式
(GDB) run
若要帶參數的話
run (init parameter)
Ex:
(GDB) run -h localhost -p 8080

Breakpoint
設定中斷點
b (filename):(line num)
Ex:
(GDB) b hello.c:5

列出目前的中斷點
(GDB) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x000000000040049c in main at hello.c:5

移除中斷點
d (breakpoint id)
Ex:
(GDB) d 1

列出當下的狀況
列出 function stack (Back trace)
(GDB) bt
#0  hello () at hello.c:9
#1  0x00000000004004cf in main () at hello.c:14

列出更詳細的資訊,包含 variable 的值
(GDB) bt full
#0  hello () at hello.c:9
        i = 0
#1  0x00000000004004cf in main () at hello.c:14
No locals.

列印變數
p (variable)
Ex:
(GDB) p iValue
(GDB) p *stEmployee

切換 frame。要列印區域變數時,必須要切換到正確的 frame
f (frame num)
EX:
(GDB) f 3

流程控制
Step over (不會進 function)
(GDB) n
Step into (會跳入 function)
(GDB) s
Continue
(GDB) c

Signal Handle
handle (signal) (operation)
Operation 預設為 stop print noignore,也就是遇到 signal 時,GDB 會先攔截,並中斷程式,必要時可以改為 nostop noprint,讓程式本身去處理 signal。若下達 ignore 則是讓程式忽略此 signal。
(GDB) handle SIGUSR nostop noprint

列出目前 signal 設定的狀態
(GDB) i handle
Signal        Stop      Print   Pass to program Description

SIGHUP        Yes       Yes     Yes             Hangup
SIGINT        Yes       Yes     No              Interrupt
SIGQUIT       Yes       Yes     Yes             Quit
SIGILL        Yes       Yes     Yes             Illegal instruction
SIGTRAP       Yes       Yes     No              Trace/breakpoint trap
有關 signal 的部分可以參考 http://sourceware.org/gdb

Thread
查看目前在哪個 thread
(GDB) thread

切換 thread
(GDB) thread 3

列出所有 thread 的 function stack
(GDB) thread apply all bt
(GDB) thread apply all bt full

Ref:
Examining the Symbol Table

在 Mac OS 上使用 Wireshark

Network interface 預設的權限是 root,由於 wireshark 是以 user 的權限來開啓,故無法存取 interface,解決的辦法就是修改權限為大家都可讀。
sudo chmod 644 /dev/bpf*
解決!

2012/08/01

Ignore SIGPIPE in socket programming

通常在寫 socket programming 時,系統對一個 invalid fd (file descriptor) 做寫入時會讓系統丟出 SIGPIPE 的 signal,為了避免程式被中斷,通常都會 ignore 它。

#include <signal.h>
struct sigaction sa;

sa.sa_handler = SIG_IGN;
sa.sa_flags = 0;

sigemptyset(&sa.sa_mask);
sigaction(SIGPIPE, &sa, 0);

2012/07/05

Mac OS X 釋放記憶體

我的 Macbook Pro 已經把 ram 升級到 8GB 了,但長時間使用還是會有不足的現象,打開活動監視器發現大部分的 memory 好像都 cache 住了。

在網路上找到 purge 這個指令,是這麼解釋的:
purge -- force disk cache to be purged (flushed and emptied)
Disk I/O的速度遠小於 Memory,所以 OS 會把常用的資料 cache 一份在 memory,這樣就不用每次都跑去 disk了。而此指令就是把這些 cache 釋放掉摟。


打開終端機執行 purge


Cool! 釋放了大半部的記憶體,終於不用常常重開機了~


參考資料
Using purge to free inactive memory on Mac OS X

2012/06/26

C compile 常見的錯誤

C 語言是我最熟悉的語言,通常我用它的時候都是講求效能,但顧效能的同時也需要花費更多心力(效率降低)。抓 memory leak、segmentation fault 這些都很要命,當然用對工具可以讓你 debug 速度加快很多,gdb、valgrind、oprofile 也都是必學的。由於沒有 OO 概念,常常需要用 structure 跟 point 去模擬物件、封裝,專案寫大的時候就會很難維護。

下面把我常遇到的 compile error 列出來:

No such file or directory
$ gcc -o test test.c
test.c:2:23: error: json/json.h: No such file or directory
test.c: In function 'main':
test.c:8: warning: assignment makes pointer from integer without a cast
test.c:12: warning: assignment makes pointer from integer without a cast
表示 include 的 header file 找不到,預設會去找 /usr/include、/usr/local/include,若 library 安裝在其他目錄,可以在 compile 時加上 -I/opt/json-c-0.9/include。


Undefined reference
$ gcc -o test test.c -I/opt/json-c-0.9/include
/tmp/ccMCrNFo.o: In function `main':
test.c:(.text+0x9): undefined reference to `json_object_new_object'
test.c:(.text+0x17): undefined reference to `json_object_new_string
...
test.c:(.text+0xc1): undefined reference to `json_object_put'
collect2: ld returned 1 exit status
表示 link library 失敗,compile 時要加上 -ljson


Linking fail
$ gcc -o test test.c -I/opt/json-c-0.9/include -ljson
/usr/bin/ld: cannot find -ljson
collect2: ld returned 1 exit status
表示找不到 libjson.so 的 library 檔案,預設的搜尋路徑 /lib、/lib64、/usr/lib、/usr/local/lib, 若 library 安裝在其他地方,在 compile 時要加上 -L/opt/json-c-0.9/lib 來增加搜尋的路徑。


Implicit declaration of function
$ gcc -Wall -o test test.c test2.o -I/opt/json-c-0.9/include -L/opt/json-c-0.9/lib -ljson
test.c: In function 'main':
test.c:23: warning: implicit declaration of function 'sub_func'
出現此 warning,表示你用的 function 在 .c 檔中有定義,但是没有在對應的 header 檔中宣告。
上例中我在 test.c 去 call sub_func() 這個 function,這個 function 是在 test2.c 中 implement,但卻沒有在 test2.h 宣告。


Error while loading shared libraries
$./test
./test: error while loading shared libraries: libjson.so.0: cannot open shared object file: No such file or directory
表示 runtime 時 load 不到指定的 library,環境變數 $LD_LIBRARY_PATH 要加入 share library 路徑,LD_LIBRARY_PATH=/opt/json-c-0.9/lib

2012/06/25

JSON parser in C language - json-c

C 語言存取 JSON 格式的資料實在不是很方便,不像 python、javascript 原生的物件表示法就跟 JSON 一樣。C 的 implementation 在官網列了好幾套,我自己是選用 json-c

API 使用方式可以參考這裡

這邊就列出基本的操作,以這樣為例:
{
  "name": "Brian",
  "sex": 0,
  "data": {
    "education": "master",
    "profession": "engineer"
  }
}

組成 JSON object,並輸出成 string
struct json_object *root, *data;

root = json_object_new_object();
json_object_object_add(root, "name", json_object_new_string("Brian"));
json_object_object_add(root, "sex", json_object_new_int(0));

data = json_object_new_object();
json_object_object_add(data, "education", json_object_new_string("master"));
json_object_object_add(data, "profession", json_object_new_string("engineer"));
json_object_object_add(root, "data", data);

// Output to string
printf("%s", json_object_to_json_string(root));

// Decrease counter and free object
json_object_put(data);
json_object_put(root);

解開 JSON object
struct json_object *root, *name, *sex, *data, *edu, *prof;

root = json_tokener_parse(json_string);
// Use is_error() to check the result, don't use "j_root == NULL".
if (is_error(j_root)) {
  printf("parse failed.");
  exit(-1);
}

name = json_object_object_get(root, "name");
sex = json_object_object_get(root, "sex");
data = json_object_object_get(root, "data");
// If parse fail, object is NULL
if (data != NULL) {
  edu = json_object_object_get(data, "education");
  prof= json_object_object_get(data, "profession");
}

if (!name || !sex|| !edu || !prof) {
  printf("parse failed.");
  json_object_put(root);
  exit(-1);
}

// Fetch value
printf("name=%s", json_object_get_string(name));
printf("sex=%d", json_object_get_int(sex));
printf("education=%s", json_object_get_string(edu));
printf("profession=%s", json_object_get_string(prof));

// Free
json_object_put(root);

參考資料
json-c-0.9库的json_object_object_get()引发崩溃问题

2012/06/22

Webapp2: Hello world

最近又在摸索 Google app engine,webapp2 基本上就是 GAE 內建的 web framework 啦,提供基本的 URL route、request handler、template、database 存取,相容於 WSGI 架構。

這是官方的 Hello world
helloworld.py
import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp2 World!')

app = webapp2.WSGIApplication([
    ('/', MainPage)
], debug=True)

app.yaml
application: helloworld
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
  script: helloworld.py

若使用 WSGI 來啓動 server,預設的 configuration file 就是 app.yaml,裡面會指明要執行哪個 python code,像上面就是 helloworld.py 這個檔案。執行後會去尋找"app"這個 object,所以物件的命名不能有錯,不然就會出現錯誤:
ERROR    2012-06-20 07:37:47,561 wsgi.py:189] 
Traceback (most recent call last):
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 187, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 239, in _LoadHandler
    raise ImportError('%s has no attribute %s' % (handler, name))
ImportError:  has no attribute app


如果不想透過 google app launcher 來啓動 project,請參考這一篇 Quick start (to use webapp2 outside of App Engine),需要額外安裝三個 package。
程式碼如下,要自己另外帶起 http server:
import webapp2

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp2 World!')
app = webapp2.WSGIApplication([
    ('/', MainPage)
], debug=True)

def main():
    from paste import httpserver
    httpserver.serve(app, host='127.0.0.1', port='8080')

if __name__ == '__main__':
    main()

再從 command line 下達指令就可以了
$ python main.py
serving on http://127.0.0.1:8080