Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the length of a function in bytes?

Tags:

I want to know the length of C function (written by me) at runtime. Any method to get it? It seems sizeof doesn't work here.

like image 466
Thomson Avatar asked Nov 11 '10 16:11

Thomson


People also ask

How to get size of bytes in Python?

Use the len() function to get the length of a bytes object, e.g. len(my_bytes) . The len() function returns the length (the number of items) of an object and can be passed a sequence (a bytes, string, list, tuple or range) or a collection (a dictionary, set, or frozen set).

How do you find the dimensions of a function?

Size of any function is calculated as: Size of function = Size of all local variable which has declared in function + Size of those global variables which has used in function+ Size of all its parameter+ Size of returned value if it is an address.

What is a free function?

The free() function in C++ deallocates a block of memory previously allocated using calloc, malloc or realloc functions, making it available for further allocations. The free() function does not change the value of the pointer, that is it still points to the same memory location.


2 Answers

There is a way to determine the size of a function. The command is:

 nm -S <object_file_name> 

This will return the sizes of each function inside the object file. Consult the manual pages in the GNU using 'man nm' to gather more information on this.

like image 54
Clocks Avatar answered Sep 24 '22 16:09

Clocks


You can get this information from the linker if you are using a custom linker script. Add a linker section just for the given function, with linker symbols on either side:

mysec_start = .; *(.mysection) mysec_end = .; 

Then you can specifically assign the function to that section. The difference between the symbols is the length of the function:

#include <stdio.h>  int i;   __attribute__((noinline, section(".mysection"))) void test_func (void) {     i++; }  int main (void) {     extern unsigned char mysec_start[];     extern unsigned char mysec_end[];      printf ("Func len: %lu\n", mysec_end - mysec_start);     test_func ();      return 0; } 

This example is for GCC, but any C toolchain should have a way to specify which section to assign a function to. I would check the results against the assembly listing to verify that it's working the way you want it to.

like image 44
FazJaxton Avatar answered Sep 24 '22 16:09

FazJaxton