[libdispatch-dev] libdispatch threads stack size

j.averous at sourcemac.com j.averous at sourcemac.com
Fri Mar 7 08:07:03 PST 2014

Hi Thomas,

Like Micheal and Dave said, it's perhaps possible with some assembler "hack".

Here is a try which seem to work on my side. Probably the thing should be enhanced (protection, red-zone ?) :

// ============================================================
#include <stdlib.h>
#include <Block.h>
#include <dispatch/dispatch.h>
#include <stdint.h>

** Defines
#pragma mark - Defines

#define	LOC_STACK_INCR	16
#define	LOC_ROUND_FRAME(x)	((((unsigned)(x)) + LOC_STACK_INCR - 1) & ~(LOC_STACK_INCR-1))

** Helpers
#pragma mark - Helpers

static inline void call_block(void *ctx)
	dispatch_block_t block = ctx;

** Functions
#pragma mark - Functions

void execute_function_stack(size_t size, void (*foo)(void *ctx), void *ctx)
	void *buffer = NULL;
	void *stack = NULL;
	// Round stack size.
	size = LOC_ROUND_FRAME(size);
	if (size < 128)
	// Alloc stack.
	if (posix_memalign(&buffer, LOC_STACK_INCR, size) != 0)
	stack = buffer + (size - LOC_STACK_INCR); // Do we have to install a red-zone ?
	// Set the stack, call the function, and reset the stack.
	asm("movq	%%rsp, %%r15	\n\t"
		"movq	%0, %%rsp		\n\t"
		"movq	%1, %%rdi		\n\t"
		"callq	*%2				\n\t"
		"movq	%%r15, %%rsp	\n\t"
		: "m" (stack), "m" (ctx), "m" (foo)
		: "%rsp", "%rdi", "%r15", "%rax", "cc"
	// Clean buffer.

void execute_block_stack(size_t size, dispatch_block_t block)
	execute_function_stack(size, call_block, (void *)block);

// ============================================================


On 5 mars 2014, at 22:35, Michael Roitzsch <mroi at os.inf.tu-dresden.de> wrote:

Hi Thomas,

We are using a library (out of our control) which is crashing our program apparently because it consumes all available stack space. We are not in control of the underlying threads since they are created by the libdispatch. Anything we can do here or are we back to managing pthreads?

If stack space is a problem, could you just allocate a large slab of memory on the heap, point ESP there and then call into that problematic library? Then revert back to the original stack when control returns from the library to you. It’s just an idea, I have not tried that. You would have to know, how much memory you need, though, as the heap allocation obviously does not grow automatically.

Michael Roitzsch

libdispatch-dev mailing list
libdispatch-dev at lists.macosforge.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.macosforge.org/pipermail/libdispatch-dev/attachments/20140307/d12cdb80/attachment.html>

More information about the libdispatch-dev mailing list