talloc_tos() in common code

Volker Lendecke Volker.Lendecke at SerNet.DE
Wed Apr 13 13:40:00 MDT 2011


Hi, Matthieu!

On Wed, Apr 13, 2011 at 09:00:31PM +0400, Matthieu Patou wrote:
> >I think this is a good idea. talloc_tos() is such a
> >useful concept that working without it tends to make
> >code a lot more clumsy.
> Could you introduce the benefits of talloc_tos ?

It is a safe way to always have a temporary talloc context
available for the lifetime of a function, and no longer.

A talloc_stackframe() is exactly what you what expect from a
stack: They nest. The normal use pattern is as follows:

void func(void) {
	TALLOC_CTX *frame = talloc_stackframe();

	/* talloc_tos() now references "frame", even if
	 * called in functions called from here */

	/* tmp and tmp2 are equivalent, it's a matter of
	 * taste */
	char *tmp = talloc_strdup(talloc_tos(), "hello");
	char *tmp2 = talloc_strdup(frame, "hello2");hello2

	/* do something more */

	/* implicitly free tmp and tmp2 and everything 
	 * talloc'ed off the call to talloc_stackframe() and
	 * here */
	
	talloc_free(frame);
}

For this it does not differ from a standard temporary talloc
context. The main trick is safety:

void inner(void) {
        TALLOC_CTX *inner_frame = talloc_stackframe();

	if (some_error) {
		/* Watch out, I forgot to free "inner_frame"
		return;
	}
	/* normal return here */
	talloc_free(inner_frame);
}

void outer(void) {
	TALLOC_CTX *outer_frame = talloc_stackframe();
	
	inner();
	
	/* Hey, cool trick! Now also free inner_frame()
	 * implicitly even if some_error happened! */
	talloc_free(outer_frame);
}

Hope that this explains the main safety feature of it.

The life time rule for a something talloc'ed off
talloc_tos() is simple: It lives as long as your function
lives, beyond that nothing is safe. A bit like lazy alloca.

The efficiency comes via the call to
talloc_stackframe_pool() in smbd/process.c, function
smbd_process. For many smb requests we only do one malloc(3)
libc call, the rest is just pointer increments.

> And why is it forbidden in source4 (maybe a question for the andrews).

The main loop must set up the talloc stackframe and properly
free it. This is not done yet in S4.

Volker

-- 
SerNet GmbH, Bahnhofsallee 1b, 37081 Göttingen
phone: +49-551-370000-0, fax: +49-551-370000-9
AG Göttingen, HRB 2816, GF: Dr. Johannes Loxen


More information about the samba-technical mailing list