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

Search results for 'asm'

2011-10-30 C inline assembler

There is long time since wanted to learn "creepy" gcc inline assembly.
Looking at manuals its not so hard and "creepy". Using it is more
interesting and dissambly of compiled code is very nice looking.

volatile puts our asm code where it is and don't optimize it without
volatile it can optimize.

What to write in __asm__ directive looks like this

__asm__ __volatile__("our_code":output:input:used)


as code to convert to inline asm we will use last post [2].

There is only one instruction that we using and it usage was

get_timer:
	rdtsc
	ret


its not very optimal and for 1 instruction writing whole function
its not beautiful. We remember that returning result of this function is
saved in eax register.

__asm__ __volatile__("rdtsc":"=a"(x)::)


code looks like this. But we can make it as define function

#define get_timer(X) __asm__ __volatile__("rdtsc":"=a"(X)::)


This code works fine and give 70058 ticks on cycle
When adding option -O2 then result becomes wherry strange.

As we remember that rdtsc return result in edx:eax then we add to
used registers(clobber) %edx.

#define get_timer(X) __asm__ __volatile__("rdtsc":"=a"(X)::"%edx")


And also we can rewrite everything as
inline function.

static inline unsigned int get_timeri()
{
	unsigned int i;
	__asm__ __volatile__("rdtsc":"=a"(i)::);
	return i;
}


Now this two functions works fine with -O options.
When empty cycle is optimized then it becomes empty and resulting
tick number is 32 for both inline function and define macro.
It not working for his main purpose. When no optimization switched
then get_timer works for some ticks faster then get_timeri.

We can add attribute always inline and we will win some ticks
and function will always inline regards optimization level

__attribute__((always_inline)) unsigned int get_timeri() 


Too fix test cycle for our measurement we make it as object file
and it will compiled without options.

void fixed_cycle()
{
	int i;
	for (i=0;i<10000;i++)
	{
	}
}


Now everything looks quite good and also inline assembly works as expected.

For reference about inline asm you can go to [1]

Source

Links
[1]http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html
[2]http://main.lv/post/linux-antidebug-5

2011-09-28 Linux antidebug 5

When debuging programm line by line or when running it
in some debugger then ther can be some time delays when you
pressing buttons. We can measure them with asm command

rdtsc 


this instruction read time-stamp counter into edx:eax in our programm will be enought values from
eax

function for c that uses rdtsc is

extern int get_timer()


in fasm it looks like

get_timer:
	rdtsc
	ret


ther is writen code

s = get_timer();
for (i=0;i<10000;i++)
{
}
e = get_timer();
d = e - s;


average time to execute 10000 is 70069 ticks for value
on with we detecting how fast working code i have choose
twice of average 120000 if execution time is larger then
probably it is debuged.

Compile
make


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-07-01 AVR disassembler

Disassembler for Atmel AVR microcontrollers made for be fast and simple. No extra features only
basics.  Converts binary file to AVR asm output.

If you have ihex then you can convert it to binary with
ReprBin

Here is example output

2411      CLR   0x11  
be1f      OUT   0x3f   , 0x1    
e5cf      LDI   0xc    , 0x5f   
e0d4      LDI   0xd    , 0x4    
bfde      OUT   0x3e   , 0x1d   
bfcd      OUT   0x3d   , 0x1c   
e010      LDI   0x1    , 0x0    
e6a0      LDI   0xa    , 0x60   
e0b0      LDI   0xb    , 0x0    
ebee      LDI   0xe    , 0xbe   
e0f0      LDI   0xf    , 0x0    
c002      RJMP  +4    
9005      LPM   0x0   
920d      ST    0x0    , 0x0    
36a0      CPI   0xa    , 0x60   
07b1      CPC   0x1b   , 0x11   
f7d9      BRBC  0x1    , -10 
e010      LDI   0x1    , 0x0    
e6a0      LDI   0xa    , 0x60   
e0b0      LDI   0xb    , 0x0    
c001      RJMP  +2    

2011-04-21 Hooking interrupt descriptor table

Hook interrupt descriptor table

Hooking interrupt table is very interesting thing
with it you can dissallow some operations to be made or watch what
happening in system. This article is more like review and more tehnical
description is in link 1

First thing that we should know that it will done trought kernel module
there is 2 commands for loading and unloading modules

insmod

and

rmmod

there is way how we can check system call addresses and position of syscall
table

grep sys_call_table /proc/kallsyms
grep system_call /proc/kallsyms

also we can use it for detecting our module functions and syscall addreses
grep sys_write /proc/kallsyms
or if we whant check out module functions
grep hook_idt /proc/kallsyms
We will now try to hook sys_mkdir. I usualy using some minimalistic windowmanagers but some browsers or other GUIsh programs like such directories "Download" or "Desktop" all my directories in ~/ is lowercase and I realy hate anoying "Download" and "Desktop" directories that are made without my permission and for my lowercase /home directory style is agly. With this hook they will be denied to make such thing. Out kernel module consist of such functions:

static int __init hook_init(void) //stufff on module init,idt hooking
static void __exit hook_exit(void) //stuff on module exit, restore idt table

asmlinkage long hooked_mkdir(const char *filename, mode_t mode) //our hook function

//how works this functions you can find in link number 1 
void *get_writable_sct(void *sct_addr)
void *get_syscall_table(void) 
Basic hooked function is:
asmlinkage long hooked_mkdir(const char *filename, mode_t mode)
{
	return mkdir(filename, mode);
}
but now we need to add check for ("Desktop","Download"). First we need some error that will returned when some one whant to make bad directory we will use EACCES error. here is modified functions for out task:
//hook mkfile command
asmlinkage long hooked_mkdir(const char *filename, mode_t mode)
{
	//it will disallow all files that starts with Desktop&&Download
	if (((strncmp(filename,"Desktop",7) == 0) && (strlen(filename) == 7)) ||
		((strncmp(filename,"Download",8) == 0) && (strlen(filename) == 8)))
	{
		printk(KERN_INFO "Mkdir hook\n");
		return EACCES;
	}
	return real_mkdir(filename, mode);
}
For module compiling: make This is tested with kernel version 2.6.38 Links:
[1] http://codenull.net/articles/kmh_en.html
[2] http://www.gadgetweb.de/linux/40-how-to-hijacking-the-syscall-table-on-latest-26x-kernel-systems.html

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

2011-02-10 ReprBin - represent binary files in different formats

This is bin2hex style project. It converts binary to other formats. Its purpose is to use with combination with assembler or uC.Code is public and on Evil Google::Code page
Google storage

SVN line: svn checkout http://represent-binary-file.googlecode.com/svn/trunk/ represent-binary-file-read-only

2011-01-22 Linux assembler scripting language

This is small interpretr in asm.
It works with small language thats can make simple things
All that you need to know about language
is this symbols "ABCDI$@"

ABCD is used with parametr.
I without param
$@ is params


ABCD - is like assembler command mov where symbol is register name
A0 is mov eax, 0
B9 is mov ebx, 9
only one number is supported. Number range after ABCD suposed to be 0...9. But you can add any other symbol only not @ or $. Look inside ascii table char '0' is 0 and other goes relativly from it. number '~' is '~'-'0'=127-48=79

I - is interupt number 80h

$@ - is variables from stack
@ - uses current varaible from stack and stack pointer goes to next stack value
$ - uses current stack value and dont change stack pointer position

Thats all.

Now we can make our first script and run it.

There is 2 thing that you should know. Script is converted to assembler commands and copyed in memory position.

Every file has hiw own purpose and all they seperated for easy to use

'script.inc' you scipt inside it
'stack_table.inc' configure stack for use
'variables.inc' define variables
'exec.inc' memory region wher script interpreted commands will copyed

Example 1:
Now first example script:

script db 'A1B0I'
mov eax, 1 ;you can look this variable inside
#include < asm/unistd.h> 
or in http://bluemaster.iu.hio.no/edu/dark/lin-asm/syscalls.html
mov ebx, 0
int 80h

it is command exit. stack can be empty.
Example2:
Now we can make hello_world.
script db 'A4B1C@D@IA1B0I'
It is
mov eax, 4
mov ebx, 1
mov ecx, buffer_msg; stack value 0
mov edx, buffer_len; stack value 1
int 80h

mov eax, 1
mov ebx, 0
int 80
in C it would be
write(1,buffer_msg,buffer_len)
exit(0);
Here is example how corresponds asm to C code http://www.main.lv/posts/view/linux-assembler-open-file. Ther is used stack in 'stack_table.inc':
stack_table:
	dd buffer_msg ;variable 0
	dd buffer_len ;variable 1
and in 'variables.inc' we define this variables:
buffer_msg db "Hello world",10	;with newline
buffer_len = $-buffer_msg	;using fasm mega feature to detect size
we can count equvialent asm commands and there is 8 of them it means add 8 lines in 'exec.inc'
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90
	db 0x90,0x90,0x90,0x90,0x90

type make and everything works =]. WooHoo small interpretd language is made and it fits in 417 bytes.

2010-12-03 Skype Rich Mood Text Animations

Mood text in skype is simple and not very interactive. Trought skype api there can be done some animations.First step was to test set mood text  trought api.Here is script that directly sends to skype Skype commnd for setting rich mood text. Linux dont support latest skype Protocol 7 (API version 3.0) but on Win there everything words ok. Here you type in commandline
./setrichmood.py "New mood"
and rich mood text changed

import sys
import os
import Skype4Py

skype = Skype4Py.Skype()
skype.Attach()

if len(sys.argv) == 2:
	if os.path.exists( sys.argv[1] ):
		f = open( sys.argv[1] , "r" )
		s = unicode(f.read())
		f.close()
		c = skype.Command( "SET PROFILE RICH_MOOD_TEXT "+s )
		skype.SendCommand( c )
	else:
		s = unicode(sys.argv[1])
		c = skype.Command( "SET PROFILE RICH_MOOD_TEXT "+s )
		skype.SendCommand( c )

Why I it call rich mood text? because it support some xml like commands.from skype api there is such commands
Example:

//------------------------------------------------------------------
// For purpose of bit conservation we omit feedback notifications
SET PROFILE RICH_MOOD_TEXT Smiley: <ss type="smile">:-)</ss>
SET PROFILE RICH_MOOD_TEXT <font color="#ff0010">Red text</font>
SET PROFILE RICH_MOOD_TEXT <blink>Blinking text</blink>
SET PROFILE RICH_MOOD_TEXT <b>Bold text</b>
SET PROFILE RICH_MOOD_TEXT <i>Italics</i>
SET PROFILE RICH_MOOD_TEXT <u>Underlined</u>
SET PROFILE RICH_MOOD_TEXT First lineSecond lineThird line

<ss type="smile"></ss> also accepts following smileys:

    * smile, sad, laugh, cool, surprised, wink, cry, sweat, speechless, kiss, tongueout, blush, wonder, sleepy, snooze, dull, inlove, talk, yawn, puke, doh, angry, wasntme, party, worry, mmm, nerdy, lipssealed, hi, call, devil, angel, envy, wait, hug, makeup, giggle, clap, think, bow, rofl, whew, happy, smirk, nod, shake, punch, emo, no, yes, handshake, skype, heart, brokenheart, mail, flower, rain, sun, time, music, movie, phone, coffee, pizza, cash, muscle, beer, drink, dance, ninja, star, mooning, finger, bandit, smoke, toivo, rock, headbang, poolparty, swear, bug, fubar, tmi. 
I have tryed use them one inside other but it doesnt worked.How there can be made animations? Here is very simple example that reads from file linesand after time delay shows lines.

./moodanime.py anime.xml
Here is new peace of script:
import sys
import os
import Skype4Py
import time

skype = Skype4Py.Skype()
skype.Attach()

s = []
if os.path.exists( sys.argv[1] ):
	f = open( sys.argv[1] , "r" )
	for line in f:
		s.append(line)
	f.close()
	
while True:
	for frame in s:
		c = skype.Command( "SET PROFILE RICH_MOOD_TEXT "+frame )
		skype.SendCommand( c )
		time.sleep( 1 )

as example file can be:
____Bonanza____
___#Bonanza#___
__##Bonanza##__
_###Bonanza###_
####Bonanza####
_###Bonanza###_
__##Bonanza##__
___#Bonanza#___

And now everything works fine. I have tested this scipts with python2.7 and on ArchLinux. If there is some problems try static or dynamic skype from skype download page

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-09-07 Robatik

This is programming game where you have to controll your robots with simple assembler like language. Game is inspired by AutoWars.  Source contains source,small turorial and examples.
Robatik Game

2010-03-05 Linux antidebug 3

Now we will try to make disasm output whery unclear. We make jump with eax register
Programm 1

main:
	push lbl+1
	pop eax
	jmp eax	
lbl:
	db 0xe8
	mov eax, 4
	mov ebx, 1
	mov ecx, msg1
	mov edx, msg1_size
	int 80h
	
	mov eax, 1
	mov ebx, 0
	int 80h
Output is same as source. Nothing changes
Dissassembler output 1
? ....... ! main:                           ;xref o80482d7     
? ....... !   push        offset_804837d                  
? 8048379 !   pop         eax                        
? 804837a !   jmp         eax                         
? 804837c     db          0e8h                            
? 804837d !                                                   
? ....... ! offset_804837d:                 ;xref o8048374 
? ....... !   mov         eax, 4                       
? 8048382 !   mov         ebx, 1                   
? 8048387 !   mov         ecx, strz_I_am_running__8049568  
? 804838c !   mov         edx, 0eh           
? 8048391 !   int         80h              
? 8048393 !   mov         eax, 1             
? 8048398 !   mov         ebx, 0 
? 804839d !   int         80h 


Here we add only one instruction. We get jump adress and add 1. Disasm cannot calculate adress of jmp.
Programm 2
Like in first programm disasm think that we push correct adress and disasm it. And our byte 0xe9 is used for disasm output. That nice.
main:
	push lbl
	pop eax
	inc eax
	jmp eax
lbl:
	db 0xe9
	mov eax, 4
	mov ebx, 1
	mov ecx, msg1
	mov edx, msg1_size
	int 80h
	
	mov eax, 1
	mov ebx, 0
	int 80h

Dissassembler output 2
? ....... ! main:                           ;xref o80482d7  
? ....... !   push        offset_804837d 
? 8048379 !   pop         eax            
? 804837a !   inc         eax     
? 804837b !   jmp         eax   
? 804837d !                      
? ....... ! offset_804837d:                 ;xref o8048374 
? ....... !   jmp         804883ah        
? 8048382     add         [ebx+1], bh     
? 8048388     mov         ecx, 8049568h   
? 804838d     mov         edx, 0eh  
? 8048392     int         80h     
? 8048394     mov         eax, 1  
? 8048399     mov         ebx, 0 
? 804839e     int         80h 
Now we add nop instruction after every line of our code. It doesnt have any imapct on programm work.
Programm 3
main:
	push lbl
	pop eax
	inc eax
	jmp eax
lbl:
	db 0xe9
	mov eax, 4
	nop 
	mov ebx, 1
	nop
	mov ecx, msg1
	nop
	mov edx, msg1_size
	int 80h
	
	mov eax, 1
	mov ebx, 0
	jmp lbl2+1
lbl2:
	db 0xe9
	int 80h

Disasm output now is very nice. Output isnt very good. For first time when you view this output it is very unclearabout what exactly is done by this code.
Dissassembler output 3
? ....... ! main:                           ;xref o80482d7
? ....... !   push        offset_804837d  
? 8048379 !   pop         eax   
? 804837a !   inc         eax     
? 804837b !   jmp         eax  
? 804837d !               
? ....... ! offset_804837d:                 ;xref o8048374 
? ....... !   jmp         804883ah   
? 8048382     add         [eax+1bbh], dl
? 8048388     add         [eax+49578b9h], dl  
? 804838e     or          [eax+0ebah], dl     
? 8048394     add         ch, cl               
? 8048396     cmp         byte ptr [eax+1], 0bbh  
? 804839d     add         [eax], al   
? 804839f     add         [eax], al  
? 80483a1     jmp         80483a4h
? 80483a3     jmp         98950475h  

Here is one more way how to make unclear jumo to other place. We using functionand inside function we change return adress by 1.

Programm 4
Thats also works fine. Disasm dont know real return adress ans and use 0xe8 as he think is better.
main:
	call fun
	db 0xe8
	mov eax, 4
	mov ebx, 1
	mov ecx, msg1
	mov edx, msg1_size
	int 80h
	
	mov eax, 1
	mov ebx, 0
	int 80h
	
fun:
	pop ebp
	inc ebp
	push ebp
	ret

Dissassembler output 4
? ....... ! main:                           ;xref o80482d7 
? ....... !   call        sub_804839c   
? 8048379 !   call        8048836h  
? 804837e !   add         [ebx+1], bh      
? 8048384 !   mov         ecx, strz_I_am_running__8049568
? 8048389 !   mov         edx, 0eh
? 804838e !   int         80h 
? 8048390 !   mov         eax, 1 
? 8048395 !   mov         ebx, 0
? 804839a !   int         80h 
? 804839c !                       
? ....... ! ;-----------------------     
? ....... ! ;  S U B R O U T I N E   
? ....... ! ;----------------------- 
? ....... ! sub_804839c:                    ;xref c8048374  
? ....... !   pop         ebp     
? 804839d !   inc         ebp     
? 804839e !   push        ebp 
? 804839f !   ret  


Source

2010-01-24 Linux Local Descriptor Table

If 0x80**** adreeses is default nope. You can setup your own. Compiler will not see thembut you can do it. Setup LDT and you will see it.

use32
mov dword [0] ,"Hall"
mov dword [4] ,"Ball"
mov dword [8] ,"Mall"
mov dword [12],0x00000000
yes everything starts from 0x0
#include <stdlib.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <asm/ldt.h>

char new_segment[16];

int main()
{
	int r;
	
	struct user_desc *ldt;
	
	ldt = (struct user_desc*)malloc(sizeof(struct user_desc));
	
	ldt->entry_number = 0;
	ldt->base_addr = ((unsigned long)&new_segment);
	ldt->limit = 16;
	ldt->seg_32bit = 0x1;
	ldt->contents = 0x0;
	ldt->read_exec_only = 0x0;
	ldt->limit_in_pages = 0x0;
	ldt->seg_not_present = 0x0;
	ldt->useable = 0x1;
	
	printf("Start\n");
	r = syscall( __NR_modify_ldt, 1 , ldt , sizeof(struct user_desc) );
	if ( r == -1 )
	{
		printf("Sorry\n");
		exit( 0 );
	}
	asm("pushl %ds");
	asm("movl $0x7, %eax"); /* 0111: 0-Index 1-Using the LDT table 11-RPL of 3 */
	asm("movl %eax, %ds");	
	asm(".byte 0xc7,0x5,0x0,0x0,0x0,0x0,0x48,0x61,0x6c,0x6c,0xc7,0x5,0x4,0x0,0x0,0x0,0x42,0x61,0x6c,0x6c,0xc7,0x5,0x8,0x0,0x0,0x0,0x4d,0x61,0x6c,0x6c,0xc7,0x5,0xc,0x0,0x0,0x0,0x0,0x0,0x0,0x0");
	asm("popl %ds");
	printf("End\n");
	
	printf("Segment [%s]\n",new_segment);
	
	free( ldt );
	
	return 0;
}


asm(".byte ... ") is code.bin

Compile:
fasm code.asm code.bin
gcc main.c -o main

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-30 Linux ShellCode 1

First shell code writened from example. Shell code is very interesting way how to execute some code.asm source:

use32				
xor eax, eax
inc eax
xor ebx, ebx
int 80h


fasm code.asm code.bin
bin2hex output:
\x31\xc0\x40\x31\xdb\xcd\x80
C source:

#include <stdio.h>
char code[] = "\x31\xc0\x40\x31\xdb\xcd\x80";
int main()
{
  void (*ret)();
  ret = (void (*)())code;
  ret();
  printf("Nope it not working\n");
}


gcc main.c -o main
run
./main
nothing happens. That exactly that code do exits from programm Source

My variant of Bin2Hex

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-11-08 Linux Assembler

Covering some topics on assembly under Linux. Not all topics are specific for Linux.

SDL example
SDL programming


FPU Topics
Calculating polinom

System
Hello World
gcc + asm
g++ + asm
Open file
Make directory

« Previous 12