├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── examples ├── function-not-found │ ├── .gcc-callgraph.yml │ ├── Makefile │ └── main.c ├── random-sort │ ├── .gcc-callgraph.yml │ ├── Makefile │ ├── callgraph.svg │ ├── main.c │ ├── sort.c │ └── sort.h └── same-name-funcs │ ├── Makefile │ ├── a.c │ ├── b.c │ ├── c.c │ ├── callgraph.svg │ └── header.h └── gcc-callgraph-plugin.py /.gitignore: -------------------------------------------------------------------------------- 1 | .tmp-bin 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:xenial 2 | 3 | RUN apt-get update 4 | RUN apt-get install -y gcc g++ git make graphviz python3 python3-dev \ 5 | python3-yaml python3-six python3-pygments python3-lxml \ 6 | libpython3.5 libgcc1 libc6 python3-sphinx \ 7 | gcc-5-plugin-dev libjs-sphinxdoc 8 | 9 | WORKDIR /tmp 10 | RUN git clone https://github.com/davidmalcolm/gcc-python-plugin.git 11 | WORKDIR /tmp/gcc-python-plugin 12 | RUN make -j$(nproc) install PYTHON=python3 PYTHON_CONFIG=python3-config 13 | RUN rm -rf /tmp/gcc-python-plugin 14 | 15 | RUN mkdir /plugin 16 | COPY gcc-callgraph-plugin.py /plugin/ 17 | 18 | RUN mkdir /src 19 | WORKDIR /src 20 | CMD "bash" 21 | 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gcc-callgraph-plugin 2 | 3 | A python script to print call graphs during compilation with GCC. It uses the 4 | [gcc-python-plugin](https://github.com/davidmalcolm/gcc-python-plugin) 5 | architecture. 6 | 7 | Example output for [`examples/random-sort`](examples/random-sort): 8 | 9 | ![example output](./examples/random-sort/callgraph.svg) 10 | 11 | ## Features 12 | 13 | - Display the whole callgraph, considering all compilling files. 14 | - Performs in O(V + E), where V is the number of functions and E is the number 15 | of calls. 16 | - Possibility to restrict callgraph with sets of starting and ending functions. 17 | - Possibility to exclude certain functions. 18 | - Accept any output format known by `dot`. 19 | - Differentiate two or more valid functions with the same name. 20 | 21 | ## Dependencies 22 | 23 | - python version >= 3.5 24 | - [PyYAML](https://pyyaml.org/) 25 | - [gcc-python-plugin](https://github.com/davidmalcolm/gcc-python-plugin) 26 | - dot (from the [graphviz](https://www.graphviz.org/) package) 27 | 28 | ## Using 29 | 30 | With the `gcc-python-plugin` installed, compile your code with: 31 | 32 | ``` 33 | $ gcc -fplugin=python \ 34 | -fplugin-arg-python-script= \ 35 | -flto -flto-partition=none \ 36 | 37 | ``` 38 | 39 | This will generate a `callgraph.svg` image in the working directory, containing 40 | the program's call graph. 41 | 42 | Note: 43 | - Give the full path to `-fplugin-arg-python-script`. Don't use `~/`, for 44 | example. 45 | - When compiling and linking in two steps, don't forget to use those flags in 46 | both of them. 47 | - If you are compilling a code with a Makefile, you can use `make CC="gcc 48 | -fplugin ..."` 49 | 50 | ### With docker 51 | 52 | You may also skip installing dependencies and run the plugin in a docker 53 | container. 54 | 55 | To build the image: 56 | 57 | ``` 58 | $ docker build -t callgraph . 59 | ``` 60 | 61 | Then, in the directory of the project you want to generate the call graph for, 62 | run: 63 | 64 | ``` 65 | $ docker run -v "$PWD:/src" -it callgraph 66 | ``` 67 | 68 | This will run the container interactively, giving you a bash session in the 69 | directory it was invoked. Then you can compile your project with the same 70 | command shown in the previous section. Just remember to use: 71 | 72 | ``` 73 | -fplugin-arg-python-script=/plugin/gcc-callgraph-plugin.py 74 | ``` 75 | 76 | ## Configuring output 77 | 78 | The plugin will read user specified settings from a `.gcc-callgraph.yml` file 79 | (if it exists), in the working directory or in the user's home directory (in 80 | this order). This file must be in YAML format and can contain the following 81 | attributes (none of them are required): 82 | 83 | - `start` (str or str list): set of functions to start the callgraph at. Any 84 | call chain that doesn't start in one of these is excluded. 85 | - `end` (str or str list): set of functions to end the callgraph at. Any call 86 | chain that does not end in one of these is excluded. 87 | - `exclude` (str or str list): set of functions to be excluded from the 88 | callgraph. 89 | - `multiple_edges` (boolean): whether to display each call between functions A 90 | and B as individual edges (True) or as a single edge (False). Default is 91 | False. 92 | - `abort_on_func_not_found` (boolean): whether to abort imediatelly if any 93 | function specified in the config file is not found (True), or continue with a 94 | warning (False). Default is False. 95 | - `out_file` (str): output file name. Extension must be one of the formats 96 | accepted by `dot`, e.g. `.png` or `.svg`. Default is `callgraph.svg`. 97 | 98 | **Functions must be specified in the format** `path:function_name`, where 99 | `path` points to the file in which the function was declared, relative to the 100 | working directory of compilation. When specified, the starting nodes will be 101 | colored blue and the end ones green. 102 | 103 | As an example, with the following we get all paths from a function A to a 104 | function B that don't contain a function C (all declared in the same file, 105 | main.c): 106 | 107 | ``` 108 | start: main.c:A 109 | end: main.c:B 110 | exclude: main.c:C 111 | ``` 112 | 113 | ## Examples 114 | 115 | The `examples` directory contain a couple of toy C projects to compile with this 116 | plugin. Every subdirectory has a `M̀akefile` designed to generate the call graph 117 | inside the `callgraph` docker container. 118 | 119 | ## Extra 120 | 121 | If you want to find paths in the call graph for a particular execution, you 122 | might want to try [callpath](https://github.com/matheustavares/callpath). 123 | 124 | -------------------------------------------------------------------------------- /examples/function-not-found/.gcc-callgraph.yml: -------------------------------------------------------------------------------- 1 | 2 | start: return_tow_dloube 3 | -------------------------------------------------------------------------------- /examples/function-not-found/Makefile: -------------------------------------------------------------------------------- 1 | 2 | .PHONY: callgraph 3 | callgraph: 4 | gcc -fplugin=python \ 5 | -fplugin-arg-python-script=/plugin/gcc-callgraph-plugin.py \ 6 | -flto -flto-partition=none \ 7 | main.c -o .tmp-bin 8 | rm .tmp-bin 9 | 10 | -------------------------------------------------------------------------------- /examples/function-not-found/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | double return_one_double() 4 | { 5 | return 1.0; 6 | } 7 | 8 | int return_two_int() 9 | { 10 | return (int) (return_one_double() + return_one_double()); 11 | } 12 | 13 | int main() 14 | { 15 | double result = .0; 16 | result += return_one_double(); 17 | result += (double) return_two_int(); 18 | printf("%lf (should be 3)\n", result); 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /examples/random-sort/.gcc-callgraph.yml: -------------------------------------------------------------------------------- 1 | 2 | start: sort.c:random_sort 3 | end: sort.c:random_in_range 4 | 5 | -------------------------------------------------------------------------------- /examples/random-sort/Makefile: -------------------------------------------------------------------------------- 1 | 2 | .PHONY: callgraph 3 | callgraph: 4 | gcc -fplugin=python \ 5 | -fplugin-arg-python-script=/plugin/gcc-callgraph-plugin.py \ 6 | -flto -flto-partition=none \ 7 | *.c *.h -o .tmp-bin -lm 8 | rm .tmp-bin 9 | 10 | -------------------------------------------------------------------------------- /examples/random-sort/callgraph.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | Callgraph 11 | 12 | 13 | sort.c:random_sort 14 | 15 | sort.c:random_sort 16 | 17 | 18 | sort.c:random_swap_two 19 | 20 | sort.c:random_swap_two 21 | 22 | 23 | sort.c:random_sort->sort.c:random_swap_two 24 | 25 | 26 | 27 | 28 | sort.c:random_swap_random 29 | 30 | sort.c:random_swap_random 31 | 32 | 33 | sort.c:random_sort->sort.c:random_swap_random 34 | 35 | 36 | 37 | 38 | sort.c:random_in_range 39 | 40 | sort.c:random_in_range 41 | 42 | 43 | sort.c:random_swap_two->sort.c:random_in_range 44 | 45 | 46 | 47 | 48 | sort.c:random_swap_random->sort.c:random_in_range 49 | 50 | 51 | 52 | 53 | sort.c:random_swap_random->sort.c:random_swap_two 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /examples/random-sort/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "sort.h" 5 | 6 | #define ARR_SIZE 10 7 | 8 | double *random_array(int N) 9 | { 10 | double *arr = malloc(N * sizeof(double)); 11 | for (int i = 0; i < N; ++i) 12 | arr[i] = (double) rand() / RAND_MAX; 13 | return arr; 14 | } 15 | 16 | void print_sorted_info(double *arr, int N) 17 | { 18 | if (is_sorted(arr, N)) 19 | printf("Array is sorted!\n"); 20 | else 21 | printf("Array *not* sorted.\n"); 22 | } 23 | 24 | int main() 25 | { 26 | double *arr; 27 | 28 | srand((unsigned int)time(NULL)); 29 | arr = random_array(ARR_SIZE); 30 | 31 | print_sorted_info(arr, ARR_SIZE); 32 | printf("Running random_sort...\n"); 33 | random_sort(arr, ARR_SIZE); 34 | print_sorted_info(arr, ARR_SIZE); 35 | 36 | free(arr); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /examples/random-sort/sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "sort.h" 4 | 5 | #define MAX_SWAPS_IN_A_ROW 10 6 | 7 | int random_in_range(int max) 8 | { 9 | return (int) floorf((rand() / (float) RAND_MAX) * max); 10 | } 11 | 12 | int random_boolean() 13 | { 14 | return (rand() > RAND_MAX / 2); 15 | } 16 | 17 | void random_swap_two(double *arr, int N) 18 | { 19 | int a = random_in_range(N); 20 | int b = random_in_range(N); 21 | double tmp = arr[a]; 22 | arr[a] = arr[b]; 23 | arr[b] = tmp; 24 | } 25 | 26 | void random_swap_random(double *arr, int N) 27 | { 28 | int swaps = random_in_range(MAX_SWAPS_IN_A_ROW) / 2; 29 | for (int i = 0; i < swaps; ++i) 30 | random_swap_two(arr, N); 31 | } 32 | 33 | void random_sort(double *arr, int N) 34 | { 35 | while (!is_sorted(arr, N)) { 36 | if (random_boolean()) 37 | random_swap_random(arr, N); 38 | else 39 | random_swap_two(arr, N); 40 | } 41 | } 42 | 43 | int is_sorted(double *arr, int N) 44 | { 45 | if (N == 1) 46 | return 1; 47 | 48 | for (int i = 1; i < N; ++i) 49 | if (arr[i] < arr[i-1]) 50 | return 0; 51 | return 1; 52 | } 53 | -------------------------------------------------------------------------------- /examples/random-sort/sort.h: -------------------------------------------------------------------------------- 1 | #ifndef _SORT_H 2 | #define _SORT_H 3 | 4 | void random_sort(double *arr, int N); 5 | int is_sorted(double *arr, int N); 6 | 7 | #endif 8 | -------------------------------------------------------------------------------- /examples/same-name-funcs/Makefile: -------------------------------------------------------------------------------- 1 | 2 | .PHONY: callgraph 3 | callgraph: 4 | gcc -fplugin=python \ 5 | -fplugin-arg-python-script=/plugin/gcc-callgraph-plugin.py \ 6 | -flto -flto-partition=none \ 7 | *.c *.h -o .tmp-bin 8 | rm .tmp-bin 9 | 10 | -------------------------------------------------------------------------------- /examples/same-name-funcs/a.c: -------------------------------------------------------------------------------- 1 | static void a(void) 2 | {} 3 | 4 | void a_wrapper(void) 5 | { 6 | a(); 7 | } 8 | -------------------------------------------------------------------------------- /examples/same-name-funcs/b.c: -------------------------------------------------------------------------------- 1 | void a(void) 2 | {} 3 | -------------------------------------------------------------------------------- /examples/same-name-funcs/c.c: -------------------------------------------------------------------------------- 1 | #include "header.h" 2 | 3 | int main() 4 | { 5 | a(); 6 | a_wrapper(); 7 | return 0; 8 | } 9 | -------------------------------------------------------------------------------- /examples/same-name-funcs/callgraph.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | Callgraph 11 | 12 | 13 | c.c:main 14 | 15 | c.c:main 16 | 17 | 18 | a.c:a_wrapper 19 | 20 | a.c:a_wrapper 21 | 22 | 23 | c.c:main->a.c:a_wrapper 24 | 25 | 26 | 27 | 28 | b.c:a 29 | 30 | b.c:a 31 | 32 | 33 | c.c:main->b.c:a 34 | 35 | 36 | 37 | 38 | a.c:a 39 | 40 | a.c:a 41 | 42 | 43 | a.c:a_wrapper->a.c:a 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /examples/same-name-funcs/header.h: -------------------------------------------------------------------------------- 1 | void a(void); 2 | void a_wrapper(void); 3 | -------------------------------------------------------------------------------- /gcc-callgraph-plugin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright 2019 Matheus Tavares 4 | # 5 | # This program is free software: you can redistribute it and/or 6 | # modify it under the terms of the GNU General Public License as 7 | # published by the Free Software Foundation, version 2 only of the 8 | # License. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program (./LICENSE). If not, see 17 | # . 18 | 19 | import gcc 20 | import subprocess 21 | import os 22 | import sys 23 | import textwrap 24 | import yaml 25 | from pathlib import Path 26 | import difflib 27 | 28 | PROG_NAME = 'callgraph-plugin' 29 | 30 | # HACK: print on stderr by default to avoid messing with the pipe to ld. 31 | sys.stdout = sys.stderr 32 | 33 | class Out: 34 | RED = '\033[1;31;49m' 35 | GREEN = '\033[1;32;49m' 36 | YELLOW = '\033[1;33;49m' 37 | END = '\033[m' 38 | 39 | @classmethod 40 | def wrap(cls, msg, prefix=' ', wrap_prefix=' ', width=80): 41 | wrapper = textwrap.TextWrapper(width=width, initial_indent=prefix, 42 | subsequent_indent=wrap_prefix) 43 | return '\n'.join(map(wrapper.fill, msg.splitlines())) 44 | 45 | @classmethod 46 | def cprint(cls, msg, color=None, wrap=True): 47 | if wrap: 48 | msg = cls.wrap(msg, prefix="", wrap_prefix="", width=80) 49 | if color == None: 50 | print(msg) 51 | else: 52 | print(color + msg + cls.END) 53 | 54 | @classmethod 55 | def info(cls, msg): 56 | cls.cprint("%s: %s" % (PROG_NAME, msg)) 57 | 58 | @classmethod 59 | def warn(cls, msg): 60 | cls.cprint("%s warn: %s" % (PROG_NAME, msg), cls.YELLOW) 61 | 62 | @classmethod 63 | def error(cls, msg): 64 | cls.cprint("%s error: %s" % (PROG_NAME, msg), cls.RED) 65 | 66 | @classmethod 67 | def success(cls, msg): 68 | cls.cprint("%s: %s" % (PROG_NAME, msg), cls.GREEN) 69 | 70 | @classmethod 71 | def abort(cls, msg="", err=1): 72 | cls.error(msg if msg != "" else "unknown error") 73 | sys.exit(err) 74 | 75 | class Config: 76 | 77 | CONFIG_FILENAME = ".gcc-callgraph.yml" 78 | DEFAULT_OUT_FILE = 'callgraph.svg' 79 | START, END, EXCLUDE = "start", "end", "exclude" 80 | OUT_FILE, MULTIPLE_EDGES = "out_file", "multiple_edges" 81 | ABORT_ON_FUNC_NOT_FOUND = "abort_on_func_not_found" 82 | KNOWN_KEYS = {START, END, EXCLUDE, OUT_FILE, MULTIPLE_EDGES, 83 | ABORT_ON_FUNC_NOT_FOUND} 84 | 85 | def __init__(self, config): 86 | self.start = self.__coerse_to_set(config.get(self.START, [])) 87 | self.end = self.__coerse_to_set(config.get(self.END, [])) 88 | self.exclude = self.__coerse_to_set(config.get(self.EXCLUDE, [])) 89 | self.out_file = config.get(self.OUT_FILE, self.DEFAULT_OUT_FILE) 90 | self.multiple_edges = config.get(self.MULTIPLE_EDGES, False) 91 | self.abort_on_func_not_found = config.get(self.ABORT_ON_FUNC_NOT_FOUND, 92 | False) 93 | 94 | @classmethod 95 | def __coerse_to_set(cls, setting): 96 | t = type(setting) 97 | if t == list: 98 | return set(setting) 99 | elif t == str: 100 | return {setting} 101 | else: 102 | Out.abort("internal error at __coerse_to_set: received a '%s'" % t) 103 | 104 | @classmethod 105 | def __validate(cls, config): 106 | cls.__check_unknown(config) 107 | cls.__check_types(config) 108 | 109 | @classmethod 110 | def __check_types(cls, config): 111 | for k, v in config.items(): 112 | if k == cls.MULTIPLE_EDGES or k == cls.ABORT_ON_FUNC_NOT_FOUND: 113 | if type(v) != bool: 114 | Out.abort('invalid value for "%s". Must be a boolean.' % k) 115 | elif type(v) == list: 116 | if not all(type(e) == str for e in v): 117 | Out.abort(('invalid value for "%s". The list must contain' 118 | ' only strings.') % (k)) 119 | elif type(v) != str: 120 | Out.abort(('invalid value for "%s". Must be a string or string' 121 | ' list') % k) 122 | 123 | @classmethod 124 | def __check_unknown(cls, config): 125 | diff = set(config) - cls.KNOWN_KEYS 126 | if len(diff) > 0: 127 | Out.abort("unknown settings: %s" % ", ".join(diff)) 128 | 129 | @classmethod 130 | def read(cls): 131 | home = str(Path.home()) 132 | local_conf = cls.CONFIG_FILENAME 133 | home_conf = os.path.join(home, cls.CONFIG_FILENAME) 134 | if os.path.isfile(local_conf): 135 | conf_path = local_conf 136 | elif os.path.isfile(home_conf): 137 | conf_path = home_conf 138 | else: 139 | return Config({}) 140 | 141 | try: 142 | fd = open(conf_path, "r") 143 | config_dict = yaml.safe_load(fd.read()) 144 | fd.close() 145 | except IOError as e: 146 | Out.abort('failed to read config file: "%s"' % str(e)) 147 | except yaml.YAMLError as e: 148 | Out.abort('failed to parse config file: "%s"' % str(e)) 149 | except Exception as e: 150 | Out.abort(str(e)) 151 | cls.__validate(config_dict) 152 | return Config(config_dict) 153 | 154 | class Node(): 155 | 156 | def __init__(self, callers, callees): 157 | self.callers = callers 158 | self.callees = callees 159 | 160 | def copy(self): 161 | return Node(self.callers.copy(), self.callees.copy()) 162 | 163 | class PathFinder(): 164 | 165 | def __init__(self, graph, exclude): 166 | '''exclude is a set of functions to be excluded from the PathFinder''' 167 | self.graph = {} 168 | for fname in graph: 169 | if fname not in exclude: 170 | self.graph[fname] = graph[fname].copy() 171 | 172 | def find(self, start, end): 173 | '''Returns a set of node names that are in some path between any of 174 | the functions in start to any in of the ones in end. If start or end 175 | are empty, don't limit the callgraph in the respective direction.''' 176 | forward = self.__search("forward", start) 177 | backward = self.__search("backward", end) 178 | len_start, len_end = len(start), len(end) 179 | if len_start == 0 and len_end == 0: 180 | return set(self.graph) 181 | elif len_start == 0: 182 | return backward 183 | elif len_end == 0: 184 | return forward 185 | return forward.intersection(backward) 186 | 187 | def __search(self, direction, start): 188 | '''Performs a dfs from the functions in the @start list in the given 189 | @direction and returns a set of nodes reachable from it. ''' 190 | neighbours = {s for s in start if s in self.graph} 191 | visited = set() 192 | 193 | while len(neighbours) > 0: 194 | fname = neighbours.pop() 195 | visited.add(fname) 196 | node = self.graph[fname] 197 | flist = node.callees if direction == "forward" else node.callers 198 | for child in flist: 199 | if child not in visited and child in self.graph: 200 | neighbours.add(child) 201 | 202 | return visited 203 | 204 | class OutputCallgraph(gcc.IpaPass): 205 | 206 | def gcc_node_to_str(self, gcc_node): 207 | return "%s:%s" % (gcc_node.decl.location.file, gcc_node.decl.name) 208 | 209 | def print_graph_debug(self, graph, nodes): 210 | '''Print @nodes from @graph.''' 211 | Out.info("info on the callgraph:\n") 212 | for fname in nodes: 213 | if fname not in graph: continue 214 | print(fname) 215 | print(" callers:") 216 | for caller in graph[fname].callers: 217 | print(" %s" % caller) 218 | print(" callees:") 219 | for callee in graph[fname].callees: 220 | print(" %s" % callee) 221 | print("") 222 | 223 | def to_dot(self, graph, nodes, start, end): 224 | '''Return a string in dot format of the given @graph but restricted to 225 | the given @nodes. The nodes in @start are colored blue and in @end, 226 | green.''' 227 | dot = 'digraph Callgraph {\n' 228 | for s in start: 229 | if s in nodes: 230 | dot += '"%s" [fillcolor=blue style=filled];\n' % s 231 | for e in end: 232 | if e in nodes: 233 | dot += '"%s" [fillcolor=green style=filled];\n' % e 234 | for fname in nodes: 235 | if fname not in graph: continue 236 | for callee in graph[fname].callees: 237 | if callee in nodes: 238 | dot += ' "%s" -> "%s";\n' % (fname, callee) 239 | dot += "}\n" 240 | return dot 241 | 242 | def clean_lib_functions(self, graph): 243 | for fname in graph: 244 | node = graph[fname] 245 | node.callers = [c for c in node.callers if c in graph] 246 | node.callees = [c for c in node.callees if c in graph] 247 | 248 | def get_graph(self, medges): 249 | graph = {} 250 | for cgn in gcc.get_callgraph_nodes(): 251 | fname = self.gcc_node_to_str(cgn) 252 | callees = [] if medges else set() 253 | callers = [] if medges else set() 254 | for edge in cgn.callees: 255 | add = callees.append if medges else callees.add 256 | add(self.gcc_node_to_str(edge.callee)) 257 | for edge in cgn.callers: 258 | add = callers.append if medges else callers.add 259 | add(self.gcc_node_to_str(edge.caller)) 260 | graph[fname] = Node(callers, callees) 261 | self.clean_lib_functions(graph) 262 | return graph 263 | 264 | def write_out_file(self, dot_str, filename): 265 | # Note: we write to dot's stdin in ascii and read from its stdout in 266 | # utf-8. This is done to ensure it will be able to read our input whilst 267 | # being permissive in its output. 268 | fmt = os.path.splitext(filename)[1][1:] 269 | if len(fmt) == 0: 270 | Out.abort("invalid filename: '%s'" % filename) 271 | out = subprocess.run(["dot", "-T%s" % fmt, "-o", filename], 272 | stderr=subprocess.STDOUT, stdout=subprocess.PIPE, 273 | input=bytes(dot_str, encoding='ascii')) 274 | if out.returncode != 0: 275 | stdout_str = Out.wrap(out.stdout.decode('utf-8')) 276 | Out.abort("failed to call 'dot'. Got:\n %s" % stdout_str) 277 | 278 | def print_final_report(self, graph, config, found_paths): 279 | if found_paths: 280 | Out.success("written to %s" % config.out_file) 281 | else: 282 | Out.info("no paths found between the given function sets") 283 | 284 | def check_functions_in_config(self, config, graph): 285 | for f in config.start | config.end | config.exclude: 286 | if f not in graph: 287 | closest = difflib.get_close_matches(f, graph, n=2) 288 | warn_msg = 'function "%s" not found.' % f 289 | if len(closest) > 0: 290 | closest_str = ', '.join(['"%s"' % s for s in closest]) 291 | warn_msg += ' Most similar: %s.' % closest_str 292 | Out.warn(warn_msg) 293 | if config.abort_on_func_not_found: 294 | Out.abort('aborting because "abort_on_func_not_found"=True') 295 | 296 | def execute(self): 297 | if gcc.is_lto(): 298 | config = Config.read() 299 | graph = self.get_graph(config.multiple_edges) 300 | self.check_functions_in_config(config, graph) 301 | finder = PathFinder(graph, config.exclude) 302 | nodes = finder.find(config.start, config.end) 303 | found_paths = len(nodes) != 0 304 | if found_paths: 305 | dot_str = self.to_dot(graph, nodes, config.start, config.end) 306 | self.write_out_file(dot_str, config.out_file) 307 | self.print_final_report(graph, config, found_paths) 308 | 309 | if sys.version_info.major != 3 or sys.version_info.minor < 5: 310 | Out.abort("must have python >= 3.5") 311 | 312 | cg = OutputCallgraph(name='output-callgraph') 313 | cg.register_before('whole-program') 314 | 315 | --------------------------------------------------------------------------------