gcccompiler-constructiongcc-plugins

How to embed metadata in object file from GCC plugin


I'm trying to write a GCC plugin that does some domain-specific analysis of the programs it compiles. I'm wondering about the best way to embed the analysis results as some kind of metadata (like debug information) in the generated object files.

Ideally, some metadata (in my case, text) should be embedded in each object file, the linker should retain the data from all the objects it links, and finally I should have some way to access all the metadata from the final binary using objdump, readelf or similar.

My current idea is to try to add a uniquely named global string variable to each compilation unit, by adding it to the GIMPLE AST. However, I'm wondering if there is a more "disciplined" way; how can plugins generate debug information or other such metadata?


Solution

  • I'm giving myself a preliminary answer, based on this answer on how to create a global variable: Insert global variable declaration whit a gcc plugin

    This code seems to work for just embedding a string my_string of length size as variable varname in the binary:

    // make a char array type
    type = build_array_type_nelts(char_type_node, size);
    
    // create the variable and set its name
    var = add_new_static_var(type);
    name = get_identifier(varname);
    DECL_NAME(var) = name;
    
    // make sure this is a definition (otherwise GCC optimizes it away!)
    TREE_PUBLIC(var) = 1;
    
    // initialize the variable to a string value
    initializer = build_string_literal(size, my_string);
    DECL_INITIAL(var) = initializer;