www.main.lv
Don't think just code it

Search results for 'elf'

2011-12-15 List ELF section names

Every ELF (Executable Linux Format) file has standard structure.
There is section names that used to identify purpose of section.

Here is example how to write all names of all ELF sections.

Here is steps that we have taken:
1. Find String Table Section
2. Get all section names from string table section
3. Run trough all section an get names of sections

First of all we need get ELF header (Elf32_Ehdr) from position 0.
ELF header have offset of section headers (Elf32_Ehdr.e_shoff).

Sting table section have attributes with help us to recognize it:
1. string table section header address in memory (Elf32_Shdr.sh_addr) is 0
2. its type (Elf32_Shdr.sh_type) is SHT_STRTAB = 3
3. and it is first section with such attributes

To get trough all sections we make for cycle. We can get number
of sections from (Elf32_Ehdr.e_shnum) .
we run all trough all sections and checking for 3 string table section
rules.

for ( iter_s=0; iter_s < ELFheader.e_shnum; iter_s++  )
	{
		fseek( f, ELFheader.e_shoff+(ELFheader.e_shentsize*iter_s), SEEK_SET);
		fread( &STRheader, ELFheader.e_shentsize, 1, f );
		if ((STRheader.sh_type == SHT_STRTAB) && 
			(STRheader.sh_addr == 0x00000000))
		{
			//some code
			iter_s=ELFheader.e_shnum+1; //this is to exit from for cycle
		}
	}


String table section has all section names as strings. Section name
is in (Elf32_Shdr.sh_name) as position number of strings first symbol.

All string table values we read inside buffer

fseek( f, STRheader.sh_offset, SEEK_SET);
fread( STR_buffer, STRheader.sh_size, 1, f);


Now we can get section name with

printf("%s\n", STR_buffer+ITERheader.sh_name);


This is example code to get some info from ELF file. There is allot other
info that can be gained from ELF file.

2011-09-15 Linux antidebug 4

Here is one more method how to check if your application is debugged.
Need to set signal handler with handles interrupt number 3 with is used
for step by step debugging

Compile:
gcc main.c -o main

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

#define FALSE 0
#define TRUE  1

void sig_handler( int );

int debuging;

int main()
{
	debuging = FALSE;
	signal(SIGTRAP, sig_handler);
	__asm__("int3");
	if (debuging == FALSE)
	{
		printf("Nothing special\n");
	} else
	{
		printf("Playing seek and hide\n");
	}
	exit(1);
}

void sig_handler( int sig)
{
	debuging = TRUE;
}


Run:
./main

Example with asm

Compile:
fasm ad4.asm ad4.o
gcc ad4.o -o ad4
format ELF

include 'ccall.inc'

SYS_EXIT	equ		1
SIGTRAP		equ		5
TRUE		equ		1
FALSE		equ		0
section '.text' executable

public main

extrn printf
extrn exit
extrn signal

main:
	ccall	signal, SIGTRAP, sig_handler
	int		3h
	
	cmp		[debug],FALSE
	jne		no_dbg
	ccall	printf,str1
	jmp exit
	
no_dbg:
	ccall	printf,str2

to_exit:
	mov		eax, SYS_EXIT
	mov		ebx, 0
	int		80h

sig_handler:
	param1 equ dword [ebp+8]	
	mov		[debug], TRUE
	ret

section '.data' writable

debug	db	FALSE
str1	db "Under debug",0xA,0
str2	db "No debug",0xA,0
Tested and works for gdb and ald. Links:
[1] http://blog.binarycell.org/2011/04/simple-antidebugging-methods-part-2.html

2011-03-13 Sauerbraten patching and cheating

sauerbraten is open source first person shooter. Also there is multi player
mode. I like time to time play sauerbraten. But I am not very good player.

As game source is comes with game you can view it and add some patches that
can help get better scores in games. Usually it called cheating.
As this features/cheats is made by my self I don't think so. But in game admins
don't care =] about it.

First of all this patches don't make game enjoyable for other players
that way sooner or later you will be banned. Every one have freedom to
be banned.

First "allowed" cheat is recoil to 0 from any weapon

in file src/fpsgame/game.h on line 333:   

static const struct guninfo { short sound, attackdelay, damage, projspeed, part, kickamount, range; const char *name, *file; } guns[NUMGUNS] = 
 { 
 { S_PUNCH1, 250, 50, 0, 0, 0, 14, "fist", "fist" }, 
 { S_SG, 1400, 10, 0, 0, 20, 1024, "shotgun", "shotg" }, // *SGRAYS 
 { S_CG, 100, 30, 0, 0, 7, 1024, "chaingun", "chaing"}, 
 { S_RLFIRE, 800, 120, 80, 0, 10, 1024, "rocketlauncher", "rocket"}, 
 { S_RIFLE, 1500, 100, 0, 0, 30, 2048, "rifle", "rifle" }, 
 { S_FLAUNCH, 500, 75, 80, 0, 10, 1024, "grenadelauncher", "gl" }, 
 { S_PISTOL, 500, 25, 0, 0, 7, 1024, "pistol", "pistol" }, 
 { S_FLAUNCH, 200, 20, 50, PART_FIREBALL1, 1, 1024, "fireball", NULL }, 
 { S_ICEBALL, 200, 40, 30, PART_FIREBALL2, 1, 1024, "iceball", NULL }, 
 { S_SLIMEBALL, 200, 30, 160, PART_FIREBALL3, 1, 1024, "slimeball", NULL }, 
 { S_PIGR1, 250, 50, 0, 0, 1, 12, "bite", NULL }, 
 { -1, 0, 120, 0, 0, 0, 0, "barrel", NULL } 
 };

changing sixths values all to 0 makes no recoil.
but if you change recoil to 1024 you can easily jump on the sky after shut.
Think what will see your on-line opponents? Someone if shutting from the skies. 

Not-flying rocket? Yes you can make it.
fourth field in structure is projspeed change it for rocket launcher to
0 and you can place your rockets on air. Bet I don't know what see others.
Only thing with that you will get ban for team-killing because team mates
are usually around you and they blow-up when colliding with rockets in air.

Precision also is very nice but every one will notice that you shutting with shotgun
and chain-gun with precision like rifle.
In src/fpsgame/weapon.cpp on 130 line:  
void offsetray(const vec &from, const vec &to, int spread, float range, vec &dest) 
   { 
       float f = to.dist(from)*spread/1000; 
       for(;;) 
       { 
           #define RNDD rnd(101)-50 
           vec v(RNDD, RNDD, RNDD); 
           if(v.magnitude()>50) continue; 
           v.mul(f); 
           v.z /= 2; 
           dest = to; 
           dest.add(v); 
           vec dir = dest; 
           dir.sub(from); 
           dir.normalize(); 
           raycubepos(from, dir, dest, range, RAY_CLIPMAT|RAY_ALPHAPOLY); 
           return; 
       } 
   } 
make
#define RNDD rnd(2)-1 

and it will work fine.

Remember this patches is cheat/like and it is not good to play with others
when this patches is added because they loose their enjoyment of game. Remember of FREEDOM to be banned.

2011-03-12 Python web login tips

Some times there is need to automitize all tasks.
Like login on page download some info and go out.
There is html parsers they can do such tasks

For example it can be login script for some browser game or mail account that doesnt allow
SMTP or SMTP is not for free.

For example there is web-browser game travian an it after some time playing
it becomes very boring to play because only thing that you do it waiting
while some game events take too many time. Like when you click upgdade
something than you need to wait some hours until finish.

Now here we will make login example.
We need external libraries:
httplib2 http://code.google.com/p/httplib2/
lxml http://lxml.de/

First thing that we need its to get page source.

conn = httplib2.Http("cache")
resp,cont = conn.request("http://travian.com")


After we have source we look on login form
<form method="post" name="snd" action="dorf1.php">
	<input class="text" type="text" name="name" value="">
	<input class="text" type="password" name="password" value="" maxlength="20">
	<input type="image" value="login" name="s1" onclick="xy();" id="btn_login" class="dynamic_img">
	<input type="hidden" name="w" value="">
	<input type="hidden" name="login" value="1299937743">
</form>

 As we see here is many inputs

As ther is only 1 form we dont check and simply take first form from array

from lxml.html import parse,tostring,fromstring,submit_form

page = fromstring( cont )
form = page.forms[0] 
for inp in form.inputs:
	if inp.type == "text":
		inp.value = name
	if inp.type == "password":
		inp.value = password



Dont forget about method="post"

headers = {'Content-type': 'application/x-www-form-urlencoded'}


Now we are ready to send data and get cookie that will allow us
get inside the page

resp , cont = self.conn.request( self.server+"/"+form.action , "POST" , body=urllib.urlencode(body) , headers=headers )


Response has cookie that we need to save if would like to work with page in future

cookie = resp['set-cookie']


Also cookie is needed if whant to logout:

headers = { 'Content-type': 'application/x-www-form-urlencoded' }
headers = { 'Cookie': self.cookie }
body = {}
resp,cont = self.conn.request(self.server+"/logout.php", body=urllib.urlencode(body) , headers=headers)


As you see now cookie is inside headers. You should allways place cookie
inside headers if whant to be loged in. Because only cookie that you get at login
says for server that you are loged in and can see what is behind the wall.

Thers is also easy way how to access DOM components
With your favorite browser you can easly get DOM path to prefered tag in HTML source.

tmp = page.xpath("/html//div//div//div//div//p//span")


You can find some tag by class name using find_class()
Or get text content from tag with text_content()

tmp = page.xpath("/html//div//div//div//div//p//span")[2].find_class("none")[0].text_content()


To make your own script that can parse and get info you need only

reguest()
find_class()
text_content()
xpath()
fromstring()


It is very easy. Now you know everything to make your first script that can login on
you favorite page.

2011-02-25 Linux Assembler SSE add

SSe programming is whery interesting fromthat point that there are parallely 4 numbers that are porcessed.SSE has registers of size 128 bits. They can handle 4 floats.GCC C there is no default type for 128 bits and we define our ownstructure for that.

typedef struct xmm
{
    float a;
    float b;
    float c;
    float d;
} xmm __attribute__ ((aligned (16)));
structure is aligned for perfomance.to make 4byted value + 4byte valuewe need to load values:
movaps xmm0, [eax]
movaps xmm1, [ebx]
and add them
addps xmm0,xmm1
after that store somewhere
movaps [eax], xmm0
Final test program in C looks like:
typedef struct xmm
{
    float a;
    float b;
    float c;
    float d;
} xmm __attribute__ ((aligned (16)));

extern void sse_add( xmm *, xmm * );

int main( int argc, char **argv)
{
    xmm x0,x1;
    x0.a = 1.0;
    x0.b = 2.0;
    x0.c = 3.0;
    x0.d = 4.0;
    x1.a = x1.b = x1.c = x1.d = 5.0;
    
    printf("%10f %10f %10f %10f\n",x0.a,x0.b,x0.c,x0.d);
    printf("%10f %10f %10f %10f\n",x1.a,x1.b,x1.c,x1.d);
    
    sse_add( &x0 , &x1 );
    
    printf("%10f %10f %10f %10f\n",x0.a,x0.b,x0.c,x0.d);
    printf("%10f %10f %10f %10f\n",x1.a,x1.b,x1.c,x1.d);
    
    return 0;
}
gcc main.c add.o -o main And asm example
format ELF

section '.text'

public sse_add

align 4
sse_add:
    ;arguments that are pointers for 2 xmm data blocks
    x0 equ [ebp+8]
    x1 equ [ebp+12]
    
    push ebp
    mov ebp, esp
    
    mov eax, x0
    mov ebx, x1
    
    ;load in xmm0 and xmm1 values
    ;if values where not aligned than we would used other instruction
    movaps xmm0, [eax]
    movaps xmm1, [ebx]
    
    ;sum up and save inside xmm0
    addps xmm0,xmm1
    
    ;save value in first argument
    movaps [eax], xmm0
    
    pop ebp
    ret
fasm add.asm add.o

2011-02-18 Intel/Linux/BSD system

FreeBSD assembler sample:
Tools
Simple programm
Hello world
Hello world + libc
C + asm
Links where is somthing useful
Files
Open File

Linux assembler samples:
Hello World
gcc + asm
g++ + asm
Open file 
Make directory

SDL assembler example
SDL programming

FPU Topics
Calculating polinom

SSE
SSE add

Programming sample from various themes.
Basic HTTP server
FPU catch division by zero
BIn2Hex converter
ReprBin
Arp Packet Analyzer
Keyboard LED flush
PC speaker
Xlib, hello world

Interesting themes:
Linux Format String Attack
ELF rewrite function
Assembler scripting language
ELF text section
Linux ShellCode 1
Local Descriptor Table
Nano bug (CVS 2010-1160)
Hooking interrupt descriptor table

Antidebug
Antidebug 1
Antidebug 2
Antidebug 3

2010-09-16 ELF rewrite function

Main idea was to replace compiled in function with some other code and run it.In default it is not possible. If you try to write some bytes withmemcpy() in function location then segfault happens. Why? Programm has different segments and they used for different program purpose.Our code belongs to readonly-executable segment. And '.text' section We can se it with
readelf -S main -l
in previos post there was program that can be used to make segment writable.After running
./textwriteble main
now segment with '.text' section becomes writable. When we try use memcpy() there is no segfault now.Second thing is how to make our function that will replace compiled in functionposition independent for some data inside function? First of all we should know our current position.It is in eip register. push eip? mov eax, eip? it doesnt work. When we use call in stack is saved return address. Now with this small functionit can be saved in some location

get_ip:
    mov ecx, [esp]
    ret
At this moment we have converted segment to writable.Have writen position detection function. If there would be data that will used in replaced function than need detectposition of that data. For example we will use
mov eax, sys_call ;we will use SYS_WRITE = 5
mov ebx, output_id ; output on terminal is STDOUT 1
mov ecx, pointer_to_msg
mov edx, size_of_msg
int 80h
if this was ordinary situation then define:
msg db "Hello",10
msg_size = $-msg
and our code becomes
mov eax, SYS_WRITE
mov ebx, STDOUT
mov ecx, msg
mov edx, msg_size
int 80h
but how to know position of msg if you dont know position where function will placed?Use function get_it and you will know current instruction position. And it will next instructionafter
call get_ip
Our code becomes
call get_ip    ;calling and detecting eip
saved_ip:      ;position that will be saved
jmp get_ip_end ;jump over function
get_ip:
    mov ecx, [esp] ;save return eip
    ret
get_ip_end:
mov eax, SYS_WRITE   
mov ebx, STDOUT
add ecx, msg-saved_ip  ;offset of msg
mov edx, msg_size
int 80h
ECX has position independent pointer to our text.For testing purposes function fun() is filled with
asm(".byte 0x90, ... ,0x90");
hex 0x90 translates in nop instruction.nop is No OPeration instruction.And function does nothing.Function fun()  contains
push ebp
mov ebp, esp
start_overwrite_here:
nop
...
...
...
nop
pop ebp
ret
Nop instructions can be replaced with any binary code.There should be enought nop instructions for our binary code.There is no check on function size that way when overwriting can be problemsif binary code size is larger then function size.Start function overwriting at position (&fun+3) witn memcpy()
push ebp
mov ebp, esp
start_overwrite_here:
nop
...
...
...
nop
pop ebp
ret
Wuala function after enabling segment can be overwriten. Here is used previous expirienceand we have mega trick with function replacment.
Compile:
make

Source

Linkage:
[1] http://www.unixwiz.net/techtips/win32-callconv-asm.html
[2] http://www.programmersheaven.com/mb/x86_asm/357735/357735/get-the-value-of-eip/
[3] http://toku.es/2010/06/text-writable/
[4] http://main.lv/posts/view/elf-text-section
[5] http://main.lv/posts/view/linux-assembler-hello-world

2010-08-23 ELF text section

This code based on .text writable

Find out .text section and make it writable.
segmentcheck.h contains two functions

int sec_text_check( FILE* );

check if given file have .text writable section or not. return 0 if  fasle, 1 if true and -1 if there was some kind error.
int sec_text_set( FILE* , int );
set section segment to writable/unwritable depends on second value that canbe 0 or 1.
Code:
Source includes two tests for both functions.I have not tested both functions very whell. That whay there can be some error.I have used used that for proving concept. And have checked result with
test1
and
readelf -l simple
Source

2010-01-21 Linux assembler and g++

format ELF

section '.text' executable

public eexit
eexit:
	mov	eax,1
	xor	ebx,ebx
	int	0x80
	ret


#include <cstdlib>
#include <cstdio>
#include <iostream>

extern "C" void eexit();

int main()
{
	eexit();
	std::cout << "Problem?\n";
	return 0;
}

Compile:
fasm hello.asm hello.o
g++ -c cmain.cpp -o cmain.o
g++ cmain.o hello.o -o cmain

2010-01-21 Linux assembler and gcc

format ELF

section '.text' executable

public eexit
eexit:
	mov	eax,1
	xor	ebx,ebx
	int	0x80
	ret



#include <stdlib.h>
#include <stdio.h>

extern void eexit();

int main()
{
	eexit();
	printf("Problem?\n");
	return 0;
}

Compile:

fasm eexit.asm eexit.ogcc -c main.c
gcc main.o eexit.o -o main

2010-01-21 Linux assembler Hello World

format ELF executable

segment readable executable

start:
	mov eax, 4
	mov ebx, 1
	mov ecx, hello_msg
	mov edx, hello_size
	int 80h

	mov eax, 1
	mov ebx, 0
	int 80h

segment readable writeable

hello_msg db "Hello World!",10,0
hello_size = $-hello_msg

Compile:
fasm hello.asm hello

2009-11-08 Linux Assembler Make Directory

Code for creating file:

format ELF executable

include 'cdecl.inc'
include 'syscall.inc'

mode_t equ dd

segment readable executable
start:
	mov eax, SYS_MKDIR
	mov ebx, path
	mov ecx, [mode]
	int 80h
	
	mov eax, SYS_EXIT
	xor ebx, ebx
	int 80h

segment readable writeable
path	db 	"dir",0 
mode	mode_t  0777o
fasm makedir.asm -o makedir
Source

2009-10-30 Linux assembler SDL

Open SDL window from asm. I tryed to open SDL window from asm. And that worked. Hardest thing is defining all structures from SDL headers. Windows opening and waiting while anykey will pressed.

include 'cdecl.inc'

format ELF

extrn SDL_Init
extrn SDL_SetVideoMode
extrn SDL_PollEvent
extrn SDL_Quit

;video settings
SDL_INIT_VIDEO	equ 0x00000020
SDL_FULLSCREEN	equ 0x80000000

;event settings
SDL_KEYDOWN         equ 2
SDL_MOUSEBUTTONDOWN equ 5

;programm settings
SCREEN_WIDTH equ 800
SCREEN_HEIGHT equ 600
SCREEN_BPP equ 24

struc SDL_keysym
{
	.scancode 	db 0
	.sym 		dd 0
	.mod		dd 0
	.unicode 	dd 0
}

struc SDL_KeyboardEvent
{
	.type  db 0
	.which db 0
	.state db 0
	.keysym SDL_keysym
}

struc SDL_Event
{
	.type db 0
	union SDL_KeyboardEvent
	.empty db 0,0,0
}

section '.text' executable
public _start
_start:
	ccall SDL_Init,SDL_INIT_VIDEO
	ccall SDL_SetVideoMode, SCREEN_WIDTH , SCREEN_HEIGHT , SCREEN_BPP , SDL_FULLSCREEN
	;try to make while loop
while_run:	
	while_polleEvent:
		ccall SDL_PollEvent, event
		cmp eax, 0
		je	while_polleEventquit
		cmp byte [event.type], SDL_KEYDOWN
		jne	while_polleEvent
		mov byte [run], 0
		jmp while_polleEvent
	while_polleEventquit:
	
	; if run != 1 quit
	cmp byte [run], 1	
	je	while_run
	
	ccall SDL_Quit, 0
	
	mov eax, 1
	xor ebx, ebx
	int 80h
	
section '.data' writeable
event		SDL_Event
run 		db 		1

Compile with lines:
fasm sdl.asm sdl.o
ld -dynamic-linker /lib/ld-linux.so.2 sdl.o /usr/lib/libSDL.so -o sdl

Dowload Source

2009-10-24 Making C executables smaller

There are some simple things that can be done to make C executables as small as possible.
Here is some example code we will work with:

#include <SDL/SDL.h>

char quit = 0;

int main()
{
    SDL_Surface *screen,surface;
    SDL_Event e;
    SDL_Init( SDL_INIT_VIDEO );
    screen = SDL_SetVideoMode( 400, 400, 32, SDL_SWSURFACE );
    while(!quit)
        while(SDL_PollEvent(&e)>0)
        {
            if(e.type==SDL_MOUSEBUTTONDOWN) quit=1;
            if(e.type==SDL_KEYDOWN) quit=1;
        }
    SDL_Quit();
}


Compile:
gcc main.c -o main -lSDL

Size before: 5326 bytes
Execute command:
strip main

strip is included in most unix systems. It deletes some info symbols from executables Size after: 3532 bytes
You can also try sstrip which is advanced version of strip. You can download it from ELF kickers webpage. Execute command:
sstrip main
Size after: 1960 bytes
There are some others way to decrease size of programm. GC Masher Allows to bruteforce gcc options for smaller executable size. I where using this options for gcsmaher
-O  -O0  -O1  -O2  -O3  -Os
-ffast-math
-fomit-frame-pointer
-fauto-inc-dec
-mpush-args
-mno-red-zone
-mstackrealign 

After runnig with this options executble size is 5175 bytes and best compiling options are all posible combination.  Combining with sstrip gives 1960 bytes. And there size where not reduced but some time there can be saved some bytes.Now we will change main function with
void _start()
and return change to
asm ( \
      "movl $1,%eax\n" \
      "xor %ebx,%ebx\n" \
      "int $128\n" \
    );
One other thing is to archive your executable and cat it with unpack shell script.
a=/tmp/I;tail -n+2 $0|zcat>$a;chmod +x $a;$a;rm $a;exit
Best options and smallest size now is 563 byte. Nope this is not smallest size try to rename executable name to one symbol and you will get 4 extra bytes.
gcc -Os -ffast-math -fomit-frame-pointer 
-fauto-inc-dec -mpush-args -mno-red-zone -c small.c;
ld -dynamic-linker /lib/ld-linux.so.2 small.o /usr/lib/libSDL.so -o small;
strip -s -R .comment -R .gnu.version small;sstrip small;
7z a -tGZip -mx=9 small.gz small > /dev/null;
cat unpack.header small.gz > small;
chmod a+x small;rm small.gz small.o
Download Source
Rewriting all in asm gives 526 bytes Link.
Link to other resources Link1.
Author in link has 634 bytes. With his options I have 622 bytes and using gcmasher i have 606 bytes. I have used his source in this compare.

2009-10-08 UNIX-programming

Programming sample from various themes.
Basic HTTP server
BIn2Hex converter
Arp Packet Analyzer
Keyboard LED flush
PC speaker
Xlib, hello world

Interesting themes:
Linux Format String Attack
ELF rewrite function
ELF text section
Linux ShellCode 1
Local Descriptor Table
Nano bug (CVS 2010-1160)

Antidebug
Antidebug 1
Antidebug 2
Antidebug 3

2009-09-23 Python Pygame Tutorial Randomnes

All boxes moving with same speed in same directions and all boxes have same size and colorMake changes step by step to see result

self.dx = randint(1,BOX_SPEED)
self.dy = randint(1,BOX_SPEED)
and boxes now moving all seperatly at diferent directions.
self.boxes.append( Box( i*2 , i*2 , randint(BOX_MIN_SIZE,BOX_MAX_SIZE) ,
(i,0,0) ) 
now boxes have diferent sizes
Tutorial source

2009-09-15 Python Pygame Tutorial Box Move

added constants that helps controlling screen size

SCREEN_X = 500
SCREEN_Y = 500
BOX_SIZE = 20
BOX_SPEED = 1
box have speed by axis
self.dx = BOX_SPEED
self.dy = BOX_SPEE
detecting if given rect is inside screen borders or not if not then change it direction
def move( self ):
        if self.rect.left+BOX_SIZE > SCREEN_X:
            self.dx = -BOX_SPEED
        if self.rect.left < 0:
            self.dx = BOX_SPEED
        if self.rect.top+BOX_SIZE > SCREEN_Y:
            self.dy = -BOX_SPEED
        if self.rect.top < 0:
            self.dy = BOX_SPEED
        self.rect.left += self.dx
        self.rect.top += self.dy
after few line of code where added box move inside given screen and coalide with screen borders
Tutorial Source

2009-09-06 Linux assembler open file

Here code for opening file, reading from it and close it.
openfile.asm

sys_read equ 3
sys_write equ 4
sys_open equ 5
sys_close equ 6
o_rdonly equ 0
 
format ELF executable
segment readable executable
start:
    ;int fid = open("file.txt",O_RDONLY);
    mov eax, sys_open
    mov ebx, f
    mov ecx, o_rdonly
    int 80h
    mov dword [f_id], eax
    
 
    ;read( fid , &buf[0] , 12 );
    mov ebx, eax    
    mov eax, sys_read
    mov ecx, f_buf
    mov edx, f_buf_len
    int 80h
 
    ;write( 1 , &buf[0] , 12 );
    mov eax, sys_write
    mov ebx, 1
    mov ecx, f_buf
    mov edx, f_buf_len
    int 80h
 
    ;close( fid );
    mov eax, sys_close
    mov ebx, dword [f_id]
    int 80h
 
    mov eax , 1
    xor ebx, ebx
    int 80h			;system interupt
 
segment readable writeable
	f db "file.txt",0
	f_len = $-f
	f_buf db 12 dup 0
	f_buf_len = $-f_buf
	f_id dd 0

fasm openfile.asm openfile

C programm
of.c
#include <fcntl.h>
 
int main()
{
	int fid = open("file.txt",O_RDONLY);
	char buf[12];
	read( fid , &buf[0] , 12 );
	write( 1 , &buf[0] , 12 );
	close( fid );
	return 0;
}
gcc of.c -o of

2009-09-04 FreeBSD assembler open file

Here code for opening file, reading from it and close it. At beginig i have thinked taht it will be complicated. But it was easy and interesting as C. Here is both C and asm code.
openfile.asm

;/usr/include/sys/syscall.h
;#define SYS_read        3
;#define SYS_write       4
;#define SYS_open        5
;#define SYS_close       6

sys_read equ 3
sys_write equ 4
sys_open equ 5
sys_close equ 6
o_rdonly equ 0

format ELF
section '.text' executable
public _start
_start:
    ;int fid = open("file.txt",O_RDONLY);
    push o_rdonly
    push f
    mov  eax, sys_open 
    push eax
    int  0x80
    add  esp, 4*3   ; clear stack after interupt	
    mov dword [f_id], eax
	
    ;read( fid , &buf[0] , 12 );
    push f_buf_len
    push f_buf
    push eax
    mov eax, sys_read
    push eax
    int 0x80
    add esp, 4*4
	
    ;write( 1 , &buf[0] , 12 );
    push f_buf_len   
    push f_buf     
    push 1         
    mov  eax, sys_write     
    push eax
    int  0x80
    add  esp,4*3

    ;close( fid );
    push dword [f_id]
    mov eax, sys_close
    push eax
    int 0x80
    add esp, 4*2
	
    ;exit from programm
    xor eax, eax	;eax = 0
    push eax
    inc eax			;eax = 1, sys_exit
    int 80h			;system interupt

section '.data' writeable
	f db "file.txt",0
	f_len = $-f
	f_buf db 12 dup 0
	f_buf_len = $-f_buf
	f_id dd 0

fasm openfile.asm openfile.o
ld openfile.o -o openfile

c.c
#include <fcntl.h>

int main()
{
	int fid = open("file.txt",O_RDONLY);
	char buf[12];
	read( fid , &buf[0] , 12 );
	write( 1 , &buf[0] , 12 );
	close( fid );
	return 0;
}


gcc c.c -o c

file.txt
Only text!!!

2009-06-16 Assembler calculate polynom

Calculating polynom with asm and C

format ELF
section ".text" executable
public poly
align 4
poly:
a equ dword [ebp+8]
b equ dword [ebp+12]
c equ dword [ebp+16]
x equ dword [ebp+20]
	;a*x*x+b*x+c
	push ebp
	mov ebp , esp
	fld c
	fld x
	fld b
	fld x
	fld a
	fmulp st1 , st0
	faddp st1 , st0
	fmulp st1 , st0
	faddp st1 , st0
	pop ebp
	ret


For calculating polynomial used polish notation Wiki
In other words a*x*x+b*x+c to reduce operations changed to (a*x+b)*x+c and then writed out operation by prioreties [*,+,*,+].
Compiling this with lines

fasm poly.asm poly.o
#include <stdio.h>
extern float poly( float , float , float , float );
int main()
{
	float res = poly( 1.0 , 2.0 , 3.0 , 3.0 );
	printf( "%f\n" , res );
	return 0;
}

Compiling this with lines
gcc -c main.c -o main.o
Combining
gcc main.o poly.o -o main
Update on 06.12.2009
After running dome C code with FPU calculations and -O2 flag 
format ELF
section ".text" executable

public poly
align 4
poly:
a equ dword [ebp+8]
b equ dword [ebp+12]
c equ dword [ebp+16]
x equ dword [ebp+20]
	;a*x*x+b*x+c
	push ebp
	mov ebp , esp

	fld a
	fmul x
	fadd b
	fmul x
	fadd c
	
	pop ebp
	ret
Now only 5 instructions

« Previous 12