Thursday, February 12, 2009

CLANG Static Analyzer

If you aren't using the LLVM/Clang Static Analyzer, you really should be. The Clang Project is an attempt to write a front end for the LLVM Compiler for the C language family. But the static analyzer tool is a standalone product you can run on any project, and it creates a nifty HTML report showing a bunch of possible bugs and/or problems with your code.

Here's a screen capture showing what the generated report looks like:

I forgot to release my formatter, and Clang realized it. This probably would have shown up in Instruments before I shipped, but it's nice to have all these little leaks and mistakes pointed out in one report. If you do nothing more than run the static analyzer over your code before shipping your next iPhone application, you will ship a better application.

Let's walk you through getting it installed and using it, so you have no excuse for not using it. First, go download the latest build. The website claims it's a bzip2 file, but Safari thinks it's a plain old tar file, and the following command expanded it for me:
tar -xvf checker-0.155.tar.bz2.tar

You may have to change the filename based on the latest version. If that doesn't work, then try using the bunzip2 command.

Now, you need to put this somewhere and add it to your PATH. You could put the files into /user/local/bin if you want. Personally, I have a folder in my home directory called bin that's part of my path. You can add a folder to your PATH variable by adding the folder to the invisible configuration file in your home directory for the Unix shell you use. Terminal now defaults to BASH, it used to default to TCSH. If you don't know which one you're using, go to Terminal's preferences and look at your startup options. The shell you use will be shown there - you can see from this screenshot that I'm a TCSH user.



If you're a TCSH user, like me, you add directories to your path variable by editing an invisible file in your home directory called .cshrc. If you use TextMate, you can edit this file by opening a terminal window and typing
mate .cshrc
or you can edit it right in the terminal using vi, emacs, or pico. Here's what my .cshrc file looks like - it's the first line you're interested in. If this file doesn't exist, go ahead and create a new file with the name.
set path= ( /usr/local/ImageMagick-6.4.3/bin /usr/X11/bin /opt/local /opt/local/bin ~/bin /usr/local/bin /usr/bin /bin /usr/X11R6/include/GL /System/Library/Frameworks/OpenGL.framework/Headers /usr/x11R6/lib /usr/local/sbin /usr/sbin /sbin /Users/jeff/Applications/apache-ant-1.6.1/bin /Users/jeff/bin /Developer/Tools /opt/local/bin /usr/local/BerkeleyDB.4.2/bin /usr/local/pgsql/bin /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/ /Users/jeff/bin/checker-0.155)

setenv TERM vt100
setenv CVSROOT "/usr/local/cvsrep"
setenv CVSEDITOR "mate -w"
setenv SVN_EDITOR "mate -w"
setenv JAVA_HOME "/Library/Java/Home"
setenv PGUSER "pgsql"
setenv PGDATABASE "postgres"
setenv PYTHONPATH "/Users/jeff/bin/python:/usr/local/pgsql/lib/libpq.a"
setenv PGSQLDIR "/usr/local/pgsql/include/libpq"
setenv EDITOR "mate -w"
setenv MAGICK_HOME "/usr/local/ImageMagick-6.4.3"
setenv YLD_LIBRARY_PATH "$MAGICK_HOME/lib"

setenv MANPATH "${HOME}/man:/usr/local/share/man:/usr/share/man"
alias gwhois "whois -h geektools.com"
stty erase 

To add directories to your path, just add them to that first line that says set path=. In this file, spaces separate the individual, which means you'll have to escape or put quotes around directories with spaces in them.

If you're a BASH person, the process is almost the same, except you need to edit a file called .bash_profile, and the syntax is a little different. Here's an example .bash_profile file. In this example, it's the last line you're interested in and, again, if the file doesn't exist, go ahead and create a new one.

[ -f /etc/profile ] && . /etc/profile
[ -f ~/.bashrc ] && . ~/.bashrc

export PATH="/usr/local/ImageMagick-6.2.6/bin:/opt/local:/opt/local/bin/:Users/jeff/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/Users/jeff/Applications/apache-ant-1.6.1/bin:/Users/jeff/bin:/Developer/Tools:/opt/local/bin:/usr/local/BerkeleyDB.4.2/bin:/usr/local/pgsql/bin:/Users/jeff/bin/checker-0.155"


In the BASH file, you separate the directories with a colon.

I'm going to assume that you've now put the static analyzer files somewhere in your path. Open a new terminal window. It has to be a new terminal window because any ones that are open won't have the changes you made to your path. Now, use the cd command to navigate to the folder of the Xcode project you want to analyze, for example:
cd dev/My Project Folder

Now, launch the analyzer by typing
scan-build xcodebuild

xcodebuild is a command line tool that does the same thing as pressing the build option in Xcode. By passing that command to scan-build, we're telling it to analyze the project that would get compiled if we typed xcodebuild in this directory. It will run for a few seconds, and then it will tell you how many bugs you have and tell you a command you can run to view the report. It'll look something like this:
** BUILD SUCCEEDED **
scan-build: 6 bugs found.
scan-build: Run 'scan-view /var/folders/w6/w6u1ni7mEjW7oDaih6Dw9U+++TI/-Tmp-//scan-build-2009-02-12-2' to examine bug reports.


Now, we can just copy that command and paste it back in the terminal:
scan-view /var/folders/w6/w6u1ni7mEjW7oDaih6Dw9U+++TI/-Tmp-//scan-build-2009-02-12-2

and our report will launch in a browser. It's a fully hyperlinked report that's pretty pretty easy to understand.



48 comments:

Stuart Robertson said...

Thanks for highlighting this tool Jeff. A lot of us are newbies to ungarbage-collected langs, so this really hits a need.

William Dahlberg said...

Very useful tip! I've been meaning to check this thing out, this post got me to it. Thanks!

Seventoes said...

Woah thats really cool, thanks for the tip!

rentzsch said...

Nikita Zhuk's excellent AnalysisTool puts LLVM/Clang static analyze into a pre-built double-clickable app and adds additional custom analyses to boot:

http://www.karppinen.fi/analysistool/

Cyril said...

Jeff, you're my god! Johnatan 'Wolf' Rentzsch is not too far behind.
Oh my god, I let this code out?

Hendrik said...

I love this tool.

I recommend using
scan-build -k -V xcodebuild
which will show the results automatically.

Jeff LaMarche said...

Cyril

While I appreciate the kind words, Wolf should not be "behind" me by any stretch of the imagination.

Wolf:

Thanks for that link - that looks easier and more convenient.

Hendrick

Thanks for that note - that's a good tip.

Wendell Hicken said...

Dunno if I did something obviously wrong, but scan-build fails for me (xcodebuild succeeds). The head of the output looks like this, it may be a configuration issue:

=== BUILDING NATIVE TARGET Warmachine OF PROJECT Warmachine WITH THE DEFAULT CO\
NFIGURATION (Release) ===

Checking Dependencies...
2009-02-15 17:43:58.939 xcodebuild[3684:4213] Warning: Couldn't discover the '\
ccc-analyzer' compiler's built-in search paths and preprocessor definitions for\
language dialect 'objective-c'. This may lead to indexing issues.
Compiler: /Users/whicken/bin/ccc-analyzer
Reason: gcc-4.0: installation problem, cannot exec '/Developer/usr/bin/arm-ap\
ple-darwin9-gcc-4.0.1': No such file or directory

TC said...

Was getting the same error. I ended up being able to get it to run by specifying both the configuration and sdk. I used the following:

scan-build -k -V xcodebuild -configuration Debug -sdk iphonesimulator2.1

Michael said...

Has anyone tried using clang with the SDK v3.0 installed? I'm getting all sorts of build errors but am not quite cleaver enough to work out the issue. Any thoughts?

NB The app is built with a target of 2.2 in xCode 3.1.2 as we know we can do

Laurent said...

Hi Jeff, not that it's important, but you can add this line:

source ~/.bash_profile

and that would obviate the need to open a new terminal.

Matt Farnell said...

Thank Jeff, your tutorial was exactly what I needed (even the primer on bash was helpful).
For those that have Beta 3 iphone SDK and have problems I got it working with this scan-build -k -V xcodebuild -configuration Debug -sdk iphonesimulator2.1

Thanks!!!

mygamebest said...

Very nice! Aion Gold You guys know what buy wow gold you're doing in wow power leveling designing Allods Gold these Allods Gold health status ffxi gil dashboards. Glad EQ2 Gold to see Lotro Gold your taking maple story mesos transparency seriously, and recognizing ROM Gold the benefits of opening eve isk up to your users. It will be an interest case study Lineage 2 adena to see how the (inevitable) next downtime event compares to the swg Credits previous one now that this exists.

Vikash Dubey said...

Thanks this was very useful

Robin said...

Thanks very much - a real newbie like me needed e.g. those paths to discover where e.g. xcodebuild actually is!

qishaya said...

Milan create week ended last night with donatella christian louboutin london disregard presenting the ending show of the autumn christian louboutin online frost 2003 italian collections.Donatella, the creative chief of christian boots the house her delayed brother founded, delivered a collection that was, christian louboutin uk as they say, very christian louboutin shoes.First up was the versus limit, louboutin boots the cheaper christian louboutin line. Girls stomped christian louboutin 2010 out with backcombed tresses bearing turquoise leather trousers, christian louboutin uk sale patchwork pullover and blonde fur sliced into stoles and active jackets. christian boots uk But this aggressive hell’s angels look almost seemed a caricature of the christian louboutin boots christian louboutin boots comfort. louboutin sandals Next up was gianni christian louboutin, buy christian louboutin the main collection

Patrick Alessi said...

Jeff,

I ran the Static Analyzer in Xcode on this bit of code and it failed to report that I don't release theString:

NSMutableString *theString = [[NSMutableString alloc] init];

for (int i=0; i<100; i++)
{
[theString appendFormat:@"%d ",i] ;
}

NSLog(@"theString is: %@", theString);

Any thoughts on why that might be? I was hoping to use this code as an example of debugging a memory leak in my book. The leak shows up fine in the Leaks tool, but I was hoping to demonstrate using the Analyzer as well.

Thanks.

Pat

Admin said...

nice post for iPhone. That great information
--
Travel blog i write Travel Jakarta Bandung dont enjoying travel jakarta-bandung with agent Travel Jakarta Bandung and keep support for Used Stationary Bikes blog with article Used Stationary Bikes and actually im write Blogger Templates Colorizetemplates.com |Hosting Profesional Indonesia yang murah

sexy said...

herve leger
herve leger dress
herve leger bandage dress
herve leger sale
herve leger dress sale
Herve Leger Dresses
Herve Leger Skirts

sexy said...

herve leger
herve leger dress
herve leger bandage dress
herve leger sale
herve leger dress sale

sexy said...

moncler
moncler jackets
Moncler Online
moncler sale
moncler clothing
Moncler Women
Moncler Jacken
Moncler Men
Moncler Kids
Moncler Jassen
Moncler Uomo
Moncler Vest
Moncler Accessories
moncler coats
piumini moncler
moncler branson
moncler jas

sexy said...

moncler
moncler jackets
Moncler Online
moncler sale
moncler clothing

sexy said...

P90X
p90x results
p90x workout
p90x reviews
p90x dvd set
p90x workout schedule
p90x extreme home fitness
p90x nutrition plan
p90x exercise program
p90x torrent
p90x dvd
p90x sale
Shaun T INSANITY Workout 13 DVDs
RevAbs
ChaLEAN
Brazil Butt Lift
10 Minute Trainer

sexy said...

P90X
p90x results
p90x workout
p90x reviews
p90x dvd set
p90x workout schedule
p90x extreme home fitness
p90x nutrition plan
p90x exercise program
p90x torrent
p90x dvd
p90x sale
Shaun T INSANITY Workout 13 DVDs
RevAbs
ChaLEAN
Brazil Butt Lift
10 Minute Trainer

sexy said...

P90X
p90x results
p90x workout
p90x reviews
p90x dvd set
p90x workout schedule
p90x extreme home fitness
p90x nutrition plan
p90x exercise program
p90x torrent
p90x dvd
p90x sale
Shaun T INSANITY Workout 13 DVDs
RevAbs
ChaLEAN
Brazil Butt Lift
10 Minute Trainer

Edwin said...

scrub m65 kamagra attorney lawyer body scrub field jacket lovegra marijuana attorney injury lawyer

Azee said...

I'm getting all sorts of build errors but am not quite cleaver enough to work out the issue.
===
Blogku Adalah Ladang Uangku | Blogku Adalah Ladang Uangku | Hosting Profesional Indonesia yang Murah | Blogger Templates Colorizetemplates.com | Blogger Templates Colorizetemplates.com

antywong said...

The rounded shape of speedy 30 features textile fake louis vuitton lining and leather trimmings with shiny Louis Vuitton Monogram ldylle Romance Encre golden brass. Sized at 11.8" x 8.3" x 6.7", the large capacity Hermes Original Python Birkin 30 Grey of this bag is enough for handbags review daily essentials; you can put bags wholesale everything into this city bag. It also fits for Hermes Clemence Jypsiere 34 Purple every occasion and perfectly goes with any outfits mfakng100910.

Kuyang Maneuver said...

awesome Blog Informasi Inspirasi Dan Sharing Motivasi

author said...

awesome..thanks for share this is really cool..
eyebrow threading|eyebrow shaping|laser hair removal

Febry Saputra said...

very useful info and great post. I like it so much because it's a unique article and easy to remember for me.
pasang iklan gratis sebagai awal mulai bisnis online |pasang iklan gratis sebagai awal mulai bisnis online |pasang iklan gratis sebagai awal mulai bisnis online |pasang iklan gratis sebagai awal mulai bisnis online |menjadi blogger yang bahagia |bisnis syariah |kita ada karena kontribusi | belajar seo

Febry Saputra said...

very useful info and great post. I like it so much because it's a unique article and easy to remember for me.
pasang iklan gratis sebagai awal mulai bisnis online |pasang iklan gratis sebagai awal mulai bisnis online |pasang iklan gratis sebagai awal mulai bisnis online |pasang iklan gratis sebagai awal mulai bisnis online |menjadi blogger yang bahagia |bisnis syariah |kita ada karena kontribusi | belajar seo

yuya indou said...

this tool is very amazing1

hot mobile news
info ponsel
blogspot tips
mobile news today
info handphone
blogging tips
mobile phone news
info blackberry
blogspot tutorial
mobilephone reviews
harga ponsel baru
blogspot trick
iphone news
ponsel baru 2010
tips ngeblog
korean drama synopsis
korean drama
korean drama ost
korean drama movie
korean movie ost

rasiqzone said...

I recently came accross your blog and have been reading along. I thought I would leave my first comment. I dont know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

info gadget online | news and entertainment

sister said...

Such kind of articl is our need , it can give us help from different aspect for different people . after reading this article , I learn a mount of knowkedge increase my power , my families and I all like you article ,reading you article is our best love.
NFL jerseys
Puma Shoes
Ecco shoes
Nike Sneakers

Sam Anderson said...

Great post, I really like it. Thanks
mobil keluarga ideal terbaik Indonesia

JeansPilot said...

JeansPilot offers the chance to buy a large variety of men’s and women’s jeans clothing from the world famous Italian Brands.
Online jeans clothing store looks for original fashion clothing sales and clearances of worldwide known designers. We participate in fashion auctions to get the lowest possible price for Top quality Clothes, Shoes and Accessories.
Buy Jeans

James William said...

very nice info :)

free arcade games

Admin said...

thanks for it..
by Indonesia Siap Bersaing Di SERP

CHEAPSOCCERUNIFORM said...

Really trustworthy blog, please keep updating with great posts like this one.
Now it will be very cold in winter, in order to keep warm yourself, moncler company has provide jackets for you, so it is better to own moncler jackets yourselif as soon as possible. Eeveryone love fashion clothing, polo ralph lauren is very popular all over world, that is my dream to get ralph lauren.We know Ray Ban by America soldier, all of them wear ray ban sunglasses when they walk on the road, it is fashionable for you. Most of people like to wear jeans, it is very modern when wearing true religion jeans in the street.

Indra_wiraa said...

Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

http://bestbuy-iphone3g.com

Indra_wiraa said...

Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.
http://bestbuy-iphone3g.com

Online Wedding Stuff said...

just looking for this tutorial, now let me try this :)

ask iphone

Admin said...

I was very encouraged to find this site.Free Download I wanted to thank you for this special read.perlunya web komunitas event organizer. I definitely savored every little bit of it and I have you bookmarked to check out new stuff you post.|perlunya web komunitas event organizer | busana muslim terbaru I admire the valuable information you offer in your articles.busana muslim terbaru | Cara Membuat Radio Streaming Murah | News Technology, Gadget, Computer Finally, an issue that I am passionate about.busana muslim terbaru | | Tutorial blog | Belajar Kimia

h4ns said...

What youre saying is completely true. I know that everybody must say the same thing, but I just think that you put it in a way that everyone can understand. I also love the images you put in here. They fit so well with what youre trying to say. Im sure youll reach so many people with what youve got to say.

Arsenal vs Huddersfield Town live streaming
Arsenal vs Huddersfield Town live streaming
Wolverhampton Wanderers vs Stoke City Live Streaming
Wolverhampton Wanderers vs Stoke City Live Streaming
Notts County vs Manchester City Live Streaming
Notts County vs Manchester City Live Streaming
Bologna vs AS Roma Live Streaming
Bologna vs AS Roma Live Streaming
Juventus vs Udinese Live Streaming
Juventus vs Udinese Live Streaming
Napoli vs Sampdoria Live Streaming
Napoli vs Sampdoria Live Streaming
Fulham vs Tottenham Hotspur Live Streaming
Fulham vs Tottenham Hotspur Live Streaming
AS Monaco vs Marseille Live Streaming
AS Monaco vs Marseille Live Streaming
Alajuelense vs Perez Zeledon Live Streaming
Alajuelense vs Perez Zeledon Live Streaming
Technology News | News Today | Live Streaming TV Channels

Kenneth said...

Thanks for the info: I thought i could do something like that but i'm never sure how write protected these things are. we'll talk.
P90x Workout Program

healthpharmacyrx1 said...

cipro Kaufen
Rezeptfrei accutane
acheter kamagra en ligne
nolvadex Prix en France
flagyl Bestellen Rezeptfrei
anafranil Bestellen
acheter cipro en france
diflucan Kaufen
cipro france
proscar Rezeptfrei Bestellen
viagra Ohne Rezept

louis vuitton spring summer 2010 collection said...

Discover Louis Vuitton collections online: luggage, handbags, wallets, shoes ...