cil-project / cil

C Intermediate Language
Other
348 stars 86 forks source link

How to print GCC function attributes? #19

Closed zumpchke closed 9 years ago

zumpchke commented 9 years ago

I'm trying to print gcc function attributes i.e section. Running this code on function declarations with attribute((section)) fails to produce any output. Any idea?

open Cil 
open Pervasives
let print_attr func =
        match func with
        | GFun(f, _) ->  (
                (*Printf.printf "%s\n" f.svar.vname;*)
                match f.svar.vtype with
                        | TFun(rt,_,_,attr) ->
                                ignore(d_attrlist () (typeAttrs rt)); ()
                        | _ -> ()
        )
        | _ -> ()

let () =
        let cil_file = Frontc.parse "srcfile" () in
        iterGlobals cil_file print_attr;
kerneis commented 9 years ago

Somtimes, CIL has a hard time attaching the attribute to the expected type (because the syntax of function attributes is ambiguous I believe). Try checking the attributes on the return type (rt in your code) too, or use a visitor to explore nested types recursively.

zumpchke commented 9 years ago

I checked the source code (which is preprocessed) and the format of the function declaration is:

return_typ_t * __attribute__ ((__section__ ("section name" "fn_name"), noinline)) my_func(in_type_t *blah)
{ 
...
}

Is this correctly parsed by CIL? Also, the attribute isn't present on the prototype...

zumpchke commented 9 years ago

Oops.. turns out I wasnt printing out the attribute correctly. The following code works to append and print the attributes on a function

open Cil
open Pervasives

class test_visitor = object(self)
        inherit nopCilVisitor

        method vfunc f =
                (* Add one ? *)
                let myattr = Attr("section", [AStr("hohoho")]) in
                let newattr = addAttribute myattr f.svar.vattr in
                f.svar.vattr <- newattr;
                let mystr = Pretty.sprint ~width:0 (d_attrlist () newattr) in
                Printf.printf "New Attributes: %s\n" mystr;
                ChangeTo(f)
end

let () =
        let cilFile = Frontc.parse "test.c" () in
        let visitor = new test_visitor in
        visitCilFile visitor cilFile;
        dumpFile defaultCilPrinter stdout "" cilFile