Use gcc plugins to modify the order of variable de

2019-08-11 06:15发布

I know this is very hard to do, and that I should avoid that, but I have my reasons for this. I want to modify the order of some field declarations in compilation time, for example :

class A {
  char c;
  int i;
}

must turn to :

class A {
      int i;
      char c;
}

if I chose to swap the order of i and c, I want to know how to change the location of a field declaration having its tree

Anyone know how can I do this ?? thanks !

I use the g++ 4.9.2 version of plugins

2条回答
太酷不给撩
2楼-- · 2019-08-11 06:22
  1. Hook in to the PLUGIN_FINISH_TYPE event and rewrite the type there. To rewrite it, reorder the fields and force a relayout of the type. You'll have to read a bit of GCC source to understand how to invalidate the layout and force a new one.

This is implemented in randomize_layout_plugin.c in linux kernel.

This solution works but it breaks down dwarf debug information. Actually, in debug information, the order of members stay the same one as initially defined in the source code, but the structure is well shuffled in the binary.

查看更多
干净又极端
3楼-- · 2019-08-11 06:47

If I was going to try this, I would try two different approaches.

  1. Hook in to the PLUGIN_FINISH_TYPE event and rewrite the type there. To rewrite it, reorder the fields and force a relayout of the type. You'll have to read a bit of GCC source to understand how to invalidate the layout and force a new one.

  2. If that didn't work, add a new pass that is run just after gimplification, and try to rewrite the types there. I suspect this is not likely to work, though.

查看更多
登录 后发表回答