Use gcc plugins to modify the order of variable declarations

家住魔仙堡 提交于 2019-12-24 03:23:26

问题


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


回答1:


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.




回答2:


  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.



来源:https://stackoverflow.com/questions/29488782/use-gcc-plugins-to-modify-the-order-of-variable-declarations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!