Saturday, December 11, 2004

What is Pure code anyway?

I have been asked by many as to what and why is my website id
www.purecode.us, pure code is a dirty alias for re-entrant code, or
non self modifying code. I wanted to give an explanation. Nothing
works better then an example. See the compilation unit given below in
c. Notice the various data types declared, they include static
variables, global variables, constant data types, pointers and so on.
Now see the assembly dump below that, and see in which sections did
they all go. I assume familiarity with the sections of a unix process:
text, read only data, initalized data, bss -> unitialized data, stack
and the heap. Naturally, we cant examine the contents of the stack and
the heap so easily, but we can find out whats in the other sections.
For code to be pure, or re-entrant, or non self modifying, the
requirement is that the code should be contained only in the text and
the .rodata (read-only) sections of the process. Static and global
data fall into the .bss and .data sections unless they are constants.
If the process is entirely in the text and .rodata sections, then we
can have multiple threads playing around with it, or we can have
multiple users sharing the pages via segmentation or paging virtual
memory implementations, and not worry about any damage to the code. It
is non-self modifying. Multiple calls to the same code will not modify
it too. Now ever wonder why we ever created the heck out of it of
making const objects and having const qualified class methods.
Thread-safe, pure, re-entrant, non self modifying....
-----------------------------------------------------------------------------------------------------
#include
const int i = 3;
float b = 3.4;
static int m = 3;
int x;
int *p;
int main()
{
x = i;
static int l = 5;
p = (int*) malloc (sizeof(int)*2);
int a = 3 + 4;
free(p);
return 0;
}
--------------------------------------------------------------------------------------------------------------
.file "fun.c"
.global b
.section ".data"
.align 4
.type b, #object
.size b, 4
b:
.long 1079613850
.align 4
.type m, #object
.size m, 4
m:
.long 3
.global x
.section ".bss"
.align 4
.type x, #object
.size x, 4
x:
.skip 4
.global p
.align 4
.type p, #object
.size p, 4
p:
.skip 4
.section ".data"
.align 4
.type _ZZ4mainE1l, #object
.size _ZZ4mainE1l, 4
_ZZ4mainE1l:
.long 5
.section ".text"
.align 4
.global main
.type main, #function
.proc 04
main:
.LLFB3:
!#PROLOGUE# 0
save %sp, -120, %sp
.LLCFI0:
!#PROLOGUE# 1
sethi %hi(x), %g1
or %g1, %lo(x), %o5
mov 3, %g1
st %g1, [%o5]
sethi %hi(p), %g1
or %g1, %lo(p), %l0
mov 8, %o0
call malloc, 0
nop
mov %o0, %g1
st %g1, [%l0]
mov 7, %g1
st %g1, [%fp-20]
sethi %hi(p), %g1
or %g1, %lo(p), %g1
ld [%g1], %o0
call free, 0
nop
mov 0, %g1
mov %g1, %i0
ret
restore
.LLFE3:
.size main, .-main
.section ".rodata"
.align 4
.type i, #object
.size i, 4
i:
.long 3
.ident "GCC: (GNU) 3.3.2"

0 Comments:

Post a Comment

<< Home