开发者

How to find all the structs that could be made smaller by changing the order of their members

Background: The compiler may insert padding into a struct to make it's members align better. This will result in the sizeof the struct being larger than the sum of the sizes of it's members. Reordering the members of the structure so they pack better can remove the need for the compiler to pad in this manner and make the struct smaller saving memory. I need to get those memory savings.

The fallback option is to check every struct by hand. I'm looking for an automated approach that can cut down the effort.

Even if it only reduces the number of structs to be checked by hand that would help.

So for example a process/tool/etc that lists all the structs that are bigger than the sum of the sizes of their members, while not perfect would still be helpful as it would limit the ones that need to be manually checked.

Does anyone know of any tools that can do this or can anyone suggest any approaches that might help.

p.s. I 开发者_Go百科need to do this on an embedded C codebase containing over 1 million lines of code.


pahole is a utility written for this specific purpose. It'll analyse your compiled object files (compiled with debugging enabled), and show you the structure holes.


gcc's -Wpadded warning option can be used to tell you when a structure is being padded. This won't tell you when the structure can be made smaller, but it can help reduce the work.


You can write a program that in turn writes out a small C program for every permutation of the fields in the struct, and when the output program is compiled and run its prints out the struct size. This will become impractical if the number of fields becomes much larger than 10 or so.


CIL is a robust C parser written in OCaml that understand the padding of structs. It comes with a detection C program. Struct padding is platform-specific, I do not doubt you know it, but you could have made it clearer in your question. The detection program packaged with CIL detects the size of types, and the algorithm that CIL assumes is used for the padding of structs is that the n-th field's offset is computed by rounding up (offset of the (n-1)-th field + size of the (n-1)-th field) to the nearest multiple of (alignment of the n-th field).

It would be less than 200 lines of OCaml to make the tool you need, starting from CIL. But there may be better solutions yet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜