Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any tools for parsing a c header file and extract a function protoype from a c header file

Especially getting the function return type(and if possible whether its a pointer type).

(I'm trying to write auto generation of ioctl/dlsym wrapper libs(to be LD_PRELOAD ed)). A python or ruby library would be preferred but any workable solution is welcome.

like image 497
Roman A. Taycher Avatar asked Jun 09 '11 08:06

Roman A. Taycher


2 Answers

I have successfully used Haskells Language.C package from hackage (Haskells answer to CPAN) to do something similar. It will provide you with a complete parse tree of the C (or header) file which can then be traversed to extract the needed information. It should AFAIK also work with #includes #defines and so on.

I'm afraid I don't have the relevant software installed to test it, but it would go something like this:

handler (DeclEvent (Declaration d)) =
do
let (VarDecl varName declAttr t) = getVarDecl d
case t of 
     (FunctionType (FunType returnType params isVaradic attrs)) -> 
        do {- varName RETURNS returnType .... -}
         _ -> do return ()
    return ()
handler _ = 
    do return ()

main = do    
    let compiler = newGCC "gcc"
    ast <- parseCFile compiler Nothing opts cFileName
    case (runTrav newState (withExtDeclHandler (analyseAST ast) handler)) of
        ...

The above might look scary, but you probably won't be needing that many more lines of Haskell to do what you want! I'll gladly share the complete source code I used (~200 lines) if it can be of any help.

like image 179
user786653 Avatar answered Oct 29 '22 20:10

user786653


The cproto program does this. Note that there are two separate versions:

  • 4.6 based at SourceForge, and
  • 4.7j based at Freshmeat

Up until recently, GCC included a program protoize that could do that job (and convert K&R function definitions to ISO prototyped function definitions); that is no longer part of the GCC distribution, though.

like image 27
Jonathan Leffler Avatar answered Oct 29 '22 21:10

Jonathan Leffler