What Is a Thunk?

What Is a Thunk?

The term thunk dates back to the days of the antediluvian Algol programming language and has stuck since then. A thunk is an invisible and parameter-less function or procedure that returns an address. A thunk isn’t implemented as a full-blown C++ function. Rather, it usually consists of one or two assembly directives that read a CPU register or manipulate some value to return the result. For example, the implicit this pointer passed as an argument to a C++ member function is often implemented as a thunk. The object’s address is stored in a CPU register and the thunk reads it from that register. Likewise, when you call delete[] to destroy an array of objects, C++ uses a thunk to retrieve the number of the elements in the array.
Thunks have other uses. The Linux kernel uses thunks extensively. For example, to obtain the task struct associated with the current process, the kernel applies the bitwise AND operator to the stack pointer (which is stored in the ESP register) and a magic number:

 task_struct * p = STACK_POINTER & 0xffffe000; //pseudo code

Under Windows, thunks are used to convert a 16-bit address to a 32-bit address, for example.


Share the Post: