devxlogo

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.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist