quarta-feira, 30 de dezembro de 2009

escaping < and > to sintaxhighlighter

To put code here I use sintaxhighlighter, a great tool to color and indent my codes.
The only problem is have to escape '<' and '>' characters.. that are really commons
in C source files..
I was making this by hand.. ybut my codes are becoming larger.. so I make
this little perl scrip to do boring thigs to me
#!/usr/bin/perl

use warnings;
use strict;

$/ = undef;
my ($file) = @ARGV;
open (F, "<$file") || die $!;
my $str = <F>;
$str =~ s/</&�lt;/g;
$str =~ s/>/&�gt;/g;

print $str;
I named it as make_htmlable O_O..
so you can use like this:
./make_htmlable c-source-file.c | xclip
and then paste the code between <pre></pre>
tags with midle mouse buttom
ps: xclip read input and save in clipboard.. so u can paste as above

terça-feira, 29 de dezembro de 2009

listen for browser

#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>


int
main (int argc, char ** argv)
{
  char * html, buf[BUFSIZ];
  int socket_fd, ret_status, sock_client_fd, pid;
  struct sockaddr_in socket_name, sock_client;
  struct hostent * host_info;

  /* Create a socket */
  socket_fd = socket (PF_INET, SOCK_STREAM, 0);

  /* Store the socket name at socket addres */
  socket_name.sin_family = AF_INET;

  /* addr of server (me) */
  // socket_name.sin_addr.s_addr = INADDR_ANY;
  inet_aton (argv[1], & socket_name.sin_addr.s_addr);

  /* use port 80 */
  socket_name.sin_port = htons (80);

  /* bind socket to an addr */
  ret_status = bind (socket_fd, (struct sockaddr *) & socket_name, 
      sizeof (socket_name));
  if (ret_status == -1) {
 perror ("bind");
 return -1;
  }
  printf ("binded\n");
  /* listen for connections */
  listen (socket_fd, 3);
  printf ("listen\n");

  /* accept new connections */
  ret_status = (int) sizeof sock_client;
  while ((sock_client_fd = accept (socket_fd, (struct sockaddr *) & sock_client, 
           & ret_status)) > 0) {

   /* print the ip of client */
   printf ("\n\nreceived connection from %s\n", inet_ntoa (sock_client.sin_addr.s_addr));

   /* wait GET */
   printf ("reading from client\n");
   while ((ret_status = read (sock_client_fd, buf, BUFSIZ)) > 0) {
  write (1, buf, ret_status);
  if ((strstr (buf, "GET")) != NULL)
    break;
   }
   if (ret_status == -1) {
  perror ("reading from browser");
  return -1;
   }

   /* send an ok */ 
   printf ("sending DATA\n");
   html = 
  "HTTP/1.1 200 OK\n"
  "Accept-Ranges: Bytes\n"
  "Content-Length: 76\n"
  "Content-Type: text/html; charset=UTF-8\n"
  "\n"
  "<html>"
  "<head><title>Hello World</title></head>"
  "<body>Hello World</body>"
  "</html>";

   ret_status = write (sock_client_fd, html, strlen (html));
   if (ret_status == -1) {
  perror ("sending ok");
  return -1;
   }

  }

  return 0;
}

alias getmyip='sudo ifconfig eth0 | grep -w addr | cut -f2 -d: | cut -f1 -d" "'
compile: gcc -o listen-browser listen-browser.c
run sudo ./listen-browser $(getmyip)
this doesn't work properly yet, I just post to save the code (:

shared memory hello world improved by signals

/* file: shared-write.c
   compiling: gcc -o shared-write shared-write.c */
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <stdio.h>
#include <sys/shm.h>


/* Make this global, so visible inside handler */
static char * shared_memory;
static int segment_id;


 /* SIGNAL handler
 detach and deallocate  */
void
handler (int signumber)
{
  shmdt (shared_memory);
  shmctl (segment_id, IPC_RMID, 0);
  exit (0);
}

int
main (void)
{
  key_t key = 2525;
  int segment_size = 0x6400;
  /* Needed for signal handler */
  struct sigaction sa;
  /* install signal handler */
  sa.sa_handler = & handler;
  sigaction (SIGUSR1, &sa, NULL);
  
  /* get a shareable segment */
  segment_id = shmget (key, segment_size, IPC_CREAT | 0666);
  /* attach it with shared_memory */
  shared_memory = shmat (segment_id, NULL, 0);
  /* write into */
  sprintf (shared_memory, "0%d,Hello World", getpid());
  
  /* wait for signal */
  while (1)
 sleep (1);
  
  /* the program must exit through handler */
  return -1;
}
/* file: shared-read.c
   compiling: gcc -o shared-read shared-read.c */
#include <string.h>
#include <stdio.h>
#include <sys/shm.h>
#include <signal.h>
#include <sys/types.h>

int 
main (void)
{
  int segment_id;
  pid_t pid_of_brother;
  key_t key = 2525;
  char * shared_memory, string;
  int segment_size = 0x6400;
  char * ptr1, * ptr2, * ptr3;
  
  /* get the shared segment, using the same key */
  segment_id = shmget (key, segment_size, 0666);
  /* attaching */
  shared_memory = shmat (segment_id, NULL, 0);
  /* There is pid of the other process and a string
  split by a comma. Take the 2 values by walk
  through pointers */
  ptr1 = strchr (shared_memory, ','); 
  /* here I got the pid. If the pid is 4 numbers then
  one 0 is taken at begining of pid */
  ptr2 = ptr1 - 5;
  /* and here is string */
  ptr3 = ptr1 + 1;
  /* conver pid to pid type */
  pid_of_brother = (pid_t) atoi (ptr2);
  /* write string to stdout */
  printf ("%s\n", ptr3);
  /* send SIGUSR1 signal to other process
  saying HEY I FINISH 
  so it can detach and deallocate the 
  shared memory */
  kill (pid_of_brother, SIGUSR1);

  return 0;
}
running:
$ ./shared-write &
[1] 2026
$ ./shared-read
Hello World
[1]+ Done ./shared-write

segunda-feira, 28 de dezembro de 2009

Shared memory hello world

/*
 * file: shared-memory-write.c
 */

#include <stdio.h>
#include <sys/shm.h>


int
main (void)
{
  key_t key = 2525;
  char * shared_memory;
  int segment_size = 0x6400;
  int segment_id;
  
  segment_id = shmget (key, segment_size, IPC_CREAT | 0666);
  shared_memory = shmat (segment_id, NULL, 0);
  sprintf (shared_memory, "Hello World");
  
  while (1)
 sleep (1);
  
  return 0;
}

/*
 * file: shared-memory-read.c
 */

#include <stdio.h>
#include <sys/shm.h>

int 
main (void)
{
  int segment_id; 
  key_t key = 2525;
  char * shared_memory;
  int segment_size = 0x6400;
  
  segment_id = shmget (key, segment_size, 0666);
  shared_memory = shmat (segment_id, NULL, 0);
  printf ("%s\n", shared_memory);
  
  shmdt (shared_memory);
  shmctl (segment_id, IPC_RMID, 0);

  return 0;
}
run ./shared-memory-write
and in another shell ./shared-memory-read.c
then in first shell kill shared-memorr-write with Ctrl-c

terça-feira, 22 de dezembro de 2009

sexta-feira, 18 de dezembro de 2009

Another Hello World using threads

/*
 * file thread.c
 * compiling: gcc -o thread thread.c -lpthread
 */

#include <stdio.h>
#include <pthread.h>

/*
 * Arguments to print_arg
 */
struct arg
{
  char * str;
  int siz;
};

/*
 * thread function
 */
void *
print_arg (void * arguments)
{
  struct arg * ptr = (struct arg *) arguments;
  write (1, ptr->str, ptr->siz);
}

int
main (void)
{
  struct arg args = {
 "Hello World\n",
 12,
  };

  /* 
   * thread atribute
   */
  pthread_attr_t thread_attr;
  
  /*
   * thread id
   */
  pthread_t thread;
 
  /*
   * init, set to detach, create it
   */
  pthread_attr_init (&thread_attr);
  pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED);
  pthread_create (&thread, &thread_attr, &print_arg, &args);
  /*
   * destroy, this don't deallocate things
   */
  pthread_attr_destroy (&thread_attr);
  return 0;
}
Detached thread don't need to return the value to main..
so thread_join isn't needed here... but..
if main return before thread, then thread
is interrupted.. this is what people call bug
sometime works .. sometime not

Make a Zombie

/*
* file: make-zombie.c
* compiling: gcc -o make-zombie make-zombie.c
* This will make a Zombie Process that will endure
* for 1 minute, or at least up to you press Ctrl-c
*/
#include <stdio.h>
#include <unistd.h>

int
main (void)
{
  int child_return, child_pid = fork();

  if (child_pid != 0) 
    /*
     * I'm the parent process
     */
    sleep (60);
  wait (&child_return);
  return 0;
}

Thread Hello World

/*
 * File thread_hello.c
 * Compiling: gcc -o thread-hello thread_hello.c -lpthread
 */
#include <stdio.h>
#include <pthread.h>

void *
print_hello (void * arg)
{
  printf ("Hello World\n");
  return NULL;
}

int 
main (void)
{
  pthread_t thread_1_id;
  pthread_create (&thread_1_id, NULL, &print_hello, NULL);
  /*
   * Main need be the last funtion to return
   */
  pthread_join (thread_1_id, NULL);
  return 0;
}

quarta-feira, 16 de dezembro de 2009

What about take any byte of an int in a char variable?

here is
;;; file dwordtobyte.asm
segment .text
  global lwordhbyte, lwordlbyte, hwordhbyte, hwordlbyte, bytestodword
lwordhbyte:
;;;
;;; unsigned char lwordhbyte (unsigned int dword)
;;; return a byte containing the 0x0000FF00 bits of dword
;;; 
  enter  0,0
  push  ebx

  mov  eax, [ebp + 8] ; first argument
  rol  ax, 8
  and  eax, 0x000000FF

  pop  ebx
  leave
  ret

segment .text
lwordlbyte:
;;;
;;; unsigned char lwordlbyte (unsigned int dword)
;;; return a byte containing the 0x000000XX bits of dword
;;; 
  enter 0,0
  push ebx

  mov  eax, [ebp + 8] ; first argument
  and  eax, 0x000000FF

  pop  ebx
  leave
  ret

hwordlbyte:
;;; 
;;; unsigned char hwordlbyte (unsigned int dword)
;;; return a byte contaning the 0x00XX0000 bits of dword
;;; 
  enter  0, 0
  push ebx
  
  mov  eax, [ebp + 8]
  rol  eax, 16   ; 0x00XX0000 -> 0x000000XX
  and  eax, 0x000000FF ; let only the lower 8 bits on

  pop  ebx
  leave
  ret

hwordhbyte:
;;;
;;; unsgined char hwordhbyte (unsigned int dword)
;;; return a byte containing the 0xXX000000 bits of dword
;;; 
  enter 0,0
  push ebx

  mov  eax, [ebp + 8]
  rol  eax, 16   ; 0xXX000000 -> 0x0000XX00
  rol  ax,  8   ; 0x0000XX00 -> 0x000000XX
  and  eax, 0x000000FF

  pop  ebx
  leave
  ret

bytestodword:
;;;
;;; unsgined int bytestodword (unsigned char HH, unsigned char HL
;;;                  unsigned char LH, unsigned char LL)
;;; return an dword made by its four arguments
;;; in this fashion 0xHHHLLHLL
;;; 
  enter  0,0
  push ebx
        ; High word  
  mov  ah, [ebp + 8] ; 0x0000XX00 
  mov  al, [ebp + 12] ; 0x000000XX
  rol  eax, 16   ; 0x0000XXXX -> 0xXXXX0000

        ; Low word 
  mov  ah, [ebp + 16] ; 0x0000XX00
  mov  al, [ebp + 20] ; 0x000000XX

  pop  ebx
  leave
  ret
and a little test
/* file driver.c */
#include <stdio.h>
#include <stdlib.h>

/*
 * functions from dword2byte.o file
 */
unsigned char lwordhbyte  (unsigned int);
unsigned char lwordlbyte  (unsigned int);
unsigned char hwordlbyte  (unsigned int);
unsigned char hwordhbyte  (unsigned int);
unsigned int  bytestoword (unsigned char, unsigned char, 
         unsigned char, unsigned char);

int
main (void)
{
  unsigned int num = 0xFF0a5040, /* 255 10 80 64 */
 newnum;
  unsigned char HH, HL, LH, LL;

  HH = hwordhbyte (num);
  HL = hwordlbyte (num);
  LH = lwordhbyte (num);
  LL = lwordlbyte (num);
  newnum = bytestodword (HH, HL, LH, LL);
  printf ("bytes values of num %d %d %d %d (in decimal)\n", 
    HH, HL, LH, LL);
  printf ("dword value of newnum %x (in hex)\n", newnum);

  return 0;
}

Compiling:
nasm -f elf dwordtobyte.asm
gcc -o bytesfun driver.c dwordtobyte.o

segunda-feira, 14 de dezembro de 2009

Read books, don't read libraries (Linux Programming Book)

Another good (I hope so) book (:
http://www.advancedlinuxprogramming.com/alp-folder

I want something real

I want to be part of a project ):

conclusion about assembly book

It's unreadable
It's error prone
It's complicated
and is all about how computer works.. so
for this propose is the best, but
for real programming is sux

I still intent to lear more... about arrays, stack
and a lot of instructions .. my main goal is grasp
memory allocation, and afterward hardware manipulation

here is the link:
http://www.drpaulcarter.com/pcasm/

search below of "English:" keyword

cat in assembly

section .bss
char resb 1 ; unbeffered


section .text
 global _start:

_start:

 mov  ecx, char

while:
 call  read
 cmp eax, 0
 jle end_while
 
 call write
 jmp  while

end_while:
 mov  ebx, eax
 mov  eax, 1
 int  0x80  
 
read:
 mov  eax, 3
 mov  ebx, 0
 mov  ecx, char
 mov  edx, 1
 int  0x80
 
 ret

write:
 mov  ebx, eax
 mov  eax, 1
 mov  ecx, char
 mov edx, 1
 int  0x80
 
 ret 

this is almost equa of "minicat.c", it
can return 0 (end of file) or -1 (error)
usage: catasm < file

domingo, 13 de dezembro de 2009

quinta-feira, 10 de dezembro de 2009

Something equivalent in C

#include <stdio.h>

struct strc
{
  int a, b, c;
} ints = {
  0x6c6c6548,
  0x6f57206f,
  0x0a646c72,
};

int 
main (void)
{
 write (1, &ints, 12);
 return 0;
}

quarta-feira, 9 de dezembro de 2009

geekest hello world assembly

; file geekest-hello-world.asm
section .text
 global _start
_start:
 push  ebx
 mov  ebp, esp
 sub  esp, 12
 

 mov  dword [ebp - 12], 0x6c6c6548  ; lleH 
 mov  dword [ebp - 8],  0x6f57206f  ; oW o
 mov  dword [ebp - 4],  0x0a646c72  ; \ndlr
 
 mov  eax, 4   ; sys_write
 mov  ebx, 1   ; stdout
 lea  ecx, [ebp - 12] ; from here
 mov  edx, 12   ; read 12 bytes
 int  0x80   ; DO IT! 

 pop  ebx

 mov  eax, 1
 mov  ebx, 0
 int  0x80
Compiling
nasm -f elf geekest-hello-world.asm
ld -s -o geekest geekest-hello-world.o

THIS IS F*CKING AWESOME!

It's funny how the things works when you know why they works ! (: Or have a little idea

retaddr.asm
segment .text
 global retaddr
retaddr:
 enter 0,0
 lea  eax, [ebp + 8]

 leave
 ret

fakeint.c
#include <stdio.h>

int *retaddr (int);

int 
main (void)
{
 printf ("%s\n", * retaddr ("Hello World")); 
 return 0;
}

Compiling:
nasm -f elf retaddr.asm
gcc -o fake fake.c retaddr.o
        This will raise some warnings ... but
         at least here works (:

segunda-feira, 7 de dezembro de 2009

Simple is nice

How to guess how many element you have in an array, without know
the type of data in the array

Simple
#define SIZEOFAR(ar) (sizeof ar / sizeof ar[0])

domingo, 6 de dezembro de 2009

Assembly hello world

section .data
 str: db  "Hello World",10
 strL: equ  $-str

section .text
 global _start:
_start:
 mov  eax, 4
 mov  ebx, 1
 mov  ecx, str
 mov  edx, strL
 int   0x80

 mov  eax, 1
 mov  ebx, 0
 int  0x80

sábado, 5 de dezembro de 2009

Take the whole input to one single string (or explode the memory of your box)

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

#define EXIERR(n,str) fprintf(stderr, str "\n");exit n

void *
xrealloc (void *ptr, size_t size)
{
 void *value = realloc (ptr, size);
 if (value == 0)
  EXIERR(-1, "Can't xrealloc");
 return value;
}

char *
readinput (void)
{
 char *str, buf[10];
 int nbytes;
 str = NULL;
 nbytes = read(0, buf, 10);
 if (nbytes == -1)
    EXIERR(-1, "Error while trying to read from input");
 str = xrealloc (str, nbytes);
 strncpy (str, buf, nbytes);
 if (nbytes < 10) {
  /* chop the new line char */
  str[nbytes - 1] = 0;
  return str;
 }

 while ((nbytes = read (0, buf, 10)) > 0) {
  str = xrealloc (str, 
    (strlen (str) + nbytes ));
  strncat (str, buf, nbytes);
 }
 if (nbytes == -1)
    EXIERR(-1, "Error while trying to read from input");
 /* 
  * the last char is a new line 
  * chop it 
 */
 str[ strlen (str) -1 ] = 0; 
 return str;
}

int 
main (void)
{
 char *str;
 str = readinput();
 puts (str);
 free (str);
 return 0;
}  

The algorithm is:
read from input 
put the bytes in buf
allocate first nbytes to str
copy buf to str
if nbytes < 10
 end str with 0
 return str
else

read from input
 put the bytes in buf
 allocate more nbytes to str
 concatenate buf in str

if there is no more input 
 end str with 0
 return str

cheers (:

It's me again editing...

Some times this program crashes when the sorce file is passed as input.. like
$ ./a.out < source_file.c

raises a two free() error

quinta-feira, 3 de dezembro de 2009

Nice cloesure fun with perl... this is old (sep 25)

# use:
# my $date = date(startday, startmonth);
# print &$date;   # print and increase current date
# print &$date(1) # print but doesn't increase current date
#
# Behavior:
# every time that the $date is dereferenced,
# it increase the date in your inner code
# and return it, unless it called with a 
# bollean true argument; like 1. 

package Date;

sub chk {
    # return 1 if the item is found in list
    # arguments need be a reference or 
    # be passed as a refenrece
    my ($it, $lst) = @_; # (item, list)
    map  {
        return 1 if $_ == $$it;
    } @$lst;
    return 0;
}

sub date { 
    # $date = &date(startday, startmonth)
    # return a cloesure that return and 
    # increase the current date 
    # or not 
    my ($day, $mon) = (1,month(1)); # default;
       ($day, $mon) = ($_[0], month($_[1])) if @_; # get the 
                                                   # start 
                                                   # day/month
    return sub { 
        # &$date() or &$date(1);
 if ($day > lastday(&$mon(1))) {
            $day = 1; # lastday + 1 eq day first
            &$mon;    # increase the month
        }
        return ($day++, &$mon(1)) unless @_; # return in list
        return ($day,   &$mon(1));           # return but does't 
                                             # increase
    };
}

sub lastday { 
    # last(&$mon(1))
    # return the last properly day in current month
    my ($mon) = @_;     # take de current month
    return 28 if $mon == 2;    # february
    return 30 if chk(\$mon, [4,6,9,11]); # april.. november
    return 31;      # others
}

sub month { 
    # $mon = month(number)
    # return and increase the current month
    my $month = shift;
    return sub { 
        # &$month(1) or $month
        $month = 1 if $month == 13;
        return $month++ unless @_; # return it and increase
 return $month;             # return it and doesn't 
                                   # increase
    };
}

#little test
my $date = date();
for my $num (1 .. 365) {
    printf ("%2d/%2d\n", &$date);
}

cloesures are nice...

So.. here I have a function that return another funtion, i.e., a cloesure
to be brief.. cloesures closes code in its self
so I have a $date variable that is a reference(the pointer name in perl) to a function
and every time that I cancel this reference(like * does in C), the date (inside the variable) increase one day. I can have how much indepent dates I want. i.e
cloesure closes code... every date variable have a date value close inside of it