什麼是Infer?
Facebook的infer是一個靜態分析工具,如果你給定infer Objective-C,Java或C代碼,它將分析潛在的bug列表。
任何人都可以使用infer攔截嚴重的安全漏洞,在應用上線之前有助於防止崩潰或性能不佳。
Infer能將代碼分解,小範圍分析後再將結果整合在一起,兼顧分析的深度和速度。
產品特點
Android和Java
報告空指針異常和資源泄漏。
iOS(本文以在Mac及IOS案例爲主,android and java留坑慢填)
除以上之外,報告iOS和C代碼的內存泄漏問題。
誰在使用infer?
它是用來作爲Facebook發展過程中移動應用程序的一部分 - 其中包括主要的Facebook應用程序的Android和iOS,Facebook的messenger,Instagram,並且所使用的超過十億用戶的其他應用程序。
so
沒事兒弄來玩一玩還是很不錯的哈~(老闆:(╯°□°)╯︵ ┻━┻ 給勞資寫代碼去!不然扣你KPI )
- Mac OS X: https://github.com/facebook/infer/releases/download/v0.1.0/infer-osx-v0.1.0.tar.xz
- Linux: https://github.com/facebook/infer/releases/download/v0.1.0/infer-linux64-v0.1.0.tar.xz
tar xf infer-osx-v0.1.0.tar.xz
如果你是Linux的話,運行以下命令解壓(注意你下載的文件名、版本號,別隻copy啊~)tar xf infer-linux64-v0.1.0.tar.xz
注意你下載的文件名、版本號,別隻copy啊~重要的話要重複三遍…… cd infer-*v0\.\1\.0 &&
echo "export PATH=\"\$PATH:`pwd`/infer/infer/bin\"" \ >> ~/.bash_profile &&
source ~/.bash_profile
這段命令包含了3個步驟,你看到有2個&&。infer -v
有返回版本號,則成功了接下來使用官方提供的一個簡單的栗子來使用infer,你可以在終端使用infer命令來獲取錯誤反饋,並在修復後繼續執行來查看結果。
infer -- xcodebuild -target HelloWorldApp -configuration Debug -sdk iphonesimulator
裏面的HelloWorldApp是和你的項目名稱是一樣的/Users/roy/Desktop/debug/infer-osx-v0.1.0/infer/examples/ios_hello/HelloWorldApp/AppDelegate.m:20: error: MEMORY_LEAK
memory dynamically allocated to shadowPath by call to CGPathCreateWithRect() at line 20, column 28 is not reachable after line 20, column 5
-(void) memory_leak_bug {
CGPathRef shadowPath = CGPathCreateWithRect(self.inputView.bounds, NULL);
}
soga!原因是沒有使用shadowPath,一般xcode也會發出警告~/Users/roy/Desktop/debug/infer-osx-v0.1.0/infer/examples/ios_hello/HelloWorldApp/AppDelegate.m:25: error: RESOURCE_LEAK
resource acquired to fp by call to fopen() at line 25, column 8 is not released after line 25, column 5
--------------
-(void) resource_leak_bug {
FILE *fp;
fp=fopen("c:\\test.txt", "r"); //獲取文件對象,卻沒有使用
}
/Users/roy/Desktop/debug/infer-osx-v0.1.0/infer/examples/ios_hello/HelloWorldApp/AppDelegate.m:29: warning: PARAMETER_NOT_NULL_CHECKED
Parameter callback is not checked for null, there could be a null pointer dereference: pointer callback could be null and is dereferenced at line 29, column 5
--------------------
-(void) parameter_not_null_checked_block_bug:(void (^)())callback {
callback(); //參數沒有判斷爲nil,OMG~
}
-(void) resource_leak_bug {
FILE *fp;
fp=fopen("c:\\test.txt", "r");
fclose(fp); //這裏加一個關掉
}
重新執行檢查,infer -- xcodebuild -target HelloWorldApp -configuration Debug -sdk iphonesimulator
然後再次打開bus.txt(得把舊的關掉重新打開),發現/Users/roy/Desktop/debug/infer-osx-v0.1.0/infer/examples/ios_hello/HelloWorldApp/AppDelegate.m:25: error: RESOURCE_LEAK
resource acquired to fp by call to fopen() at line 25, column 8 is not released after line 25, column 5
已經不存在了,so good!!!-----END---------------------
快速使用facebook infer的栗子就寫到這裏了,明天上班我會實際運用到正式項目當中,希望能有所收穫。