[DTrace-devel] Strange but fun things

Kris Van Hees kris.van.hees at oracle.com
Thu Jul 2 08:19:22 PDT 2020


The D language allows for some complex constructs and is more powerful than
I often give it credit for.  Not all features are as useful as others, but
sometimes you can run into things that are acceptable at compile time when
being actually entirely pointless and arguably, wrong).

Consider the following construct:

this int v[10];

BEGIN {
	p = &this->v[2];
	*p = 25;
	exit(0);
}

END {
	trace(*p);
}

As you can see, v is an int array of fixed size, declared as a clause-local
variable.  Since it is declared outside of a clause, its definition will be
known within the clause but you shouldn't be counting on its value surviving
across clause boundaries.

By taking the address of the element with index 2 of this->v and storing it
in a global variable, we effectively can access its content across clause
boundaries.

So, when the END clause is executed we get the result '25'.

But...  Should this code actually be valid?  Given that this->v is a
clause-local variable per its declaration, it shouldn't persist across clause
boundaries (and arguably the compiler could re-use the storage used for it at
the end of a clause and choose other storage locations for different clauses
that make use of it.  It doesn't but it could.  So, storing a pointer to a
storage location of a clause local variable shouldn't make sense, and yet it
is allowed and happens to work.

But get this...  If you use:

this int v;

BEGIN
{
	p = *this->v;
	exit(0);
}

you will get a compilation error (cannot take address of dynamic variable).

The following will get the same error:

this struct task_struct v;

BEGIN {
	p = &this->v;
	exit(0);
}

But...  the next example DOES work:

this struct task_struct v;

BEGIN {
	p = &this->v.pid;
	*p = 25;
	exit(0);
}

END {
	trace(*p);
}

Just don't plan on using this rather crazy construct...  it won't work on
DTrace v2 (not because I am disallowing it - I may - but because I cannot even
see a way to make it work).

	Kris



More information about the DTrace-devel mailing list