How to get func code size

168 views
Skip to first unread message

涛叔

unread,
Aug 23, 2021, 11:56:02 PM8/23/21
to golang-dev
Hi, guys,

While I can get a pointer to func's code  memory block by the following go code

code := **(**uintptr)(unsafe.Pointer(&someFunc))

Is there any way to detect this code block's size(in bytes)?

Thank you.

Ian Lance Taylor

unread,
Aug 24, 2021, 12:31:46 AM8/24/21
to 涛叔, golang-dev
Not at the language level, no.

You can get this information, though not completely reliably, by
opening the executable as a file and looking at the symbol table. In
ELF the answer should be precise, but it may not be on systems that
use other object file formats (namely Windows and macOS).

Ian

Josh Bleecher Snyder

unread,
Aug 24, 2021, 12:44:38 AM8/24/21
to Ian Lance Taylor, golang-dev, 涛叔
For fun, some other ways:

Another approach to this is parsing the first few instructions; Go functions have a common prologue, one of which is a jump to a standard epilogue that handles stack growth. The details will vary by architecture and Go version, and there are several flavors of prologues, including some functions with no prologues, but it’ll work for most functions.

Also, on some architectures, gaps between functions are filled with special break/interrupt instructions. In those cases you can probably read forward until you encounter such instructions. (This will be wrong in the rare case in which someone has written an assembly routine containing such an instruction.)

Closures may complicate some of these approaches as well.

-josh



--
You received this message because you are subscribed to the Google Groups "golang-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-dev+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-dev/CAOyqgcVEOTAMRgeLA7A2pJ_symLrJSNmEU8S15Op%2BDks0SZokw%40mail.gmail.com.

Jan Mercl

unread,
Aug 24, 2021, 6:33:35 AM8/24/21
to 涛叔, golang-dev
On Tue, Aug 24, 2021 at 5:56 AM 涛叔 <haita...@gmail.com> wrote:

> While I can get a pointer to func's code memory block by the following go code
>
> code := **(**uintptr)(unsafe.Pointer(&someFunc))

You cannot take an address of a function using &:
https://play.golang.org/p/AaxLM8Ju0d1

Jeremy Faller

unread,
Aug 24, 2021, 9:07:35 AM8/24/21
to Josh Bleecher Snyder, Ian Lance Taylor, golang-dev, 涛叔
NB: The "walk till you find a break," method that Josh suggests won't always work. If the functions are packed perfectly, no break instructions will be inserted by the linker, and you're stuck with falling back to prologue inspection.



--
Warmest Regards,
Jeremy Faller
Reply all
Reply to author
Forward
0 new messages