Archive for the ‘Programming’ Category
Really, Code::Blocks Rocks!!!
Really, Code::Blocks Rocks!!!
Well… after a long time I post here again, because of this IDE… yeah… a many time that I try to test it and after tests of my friend Marcio that use and talk about the tool I decided test too. I’m very surprise with this IDE, the installation is very easy and work with this IDE is very easy too… I install it in my VM with WinXP and I testing the OpenGL app and it works very fine… The OpenGL app works fine in my VM too, in considerable time… I decided now use the Code::Blocks for developing my personal project at this time!!! Its convinced me!!!
Today, after reading some pages of the Programming Challenges Book I’m trying applying some memoization and dynamic programming techniques for solve some problems in SPOJs and UVA’s online-judge of life. Its a very utility tool for solving many problems. But I need more training for good application of this. I like this…
In play: Bruce Dickinson – The Very Best Of (CD 1) – 02: Tattooed Millionarie
The Practice of Perl
Well.. a sugestive title for an post, but I decide for this title because of Perl is one of my prefer programming languages, my “swiss army knife”… and dont first time that I using perl for solving my problem… ehehehhehehehhee…
But why I talking about perl here??? Because of one problem, for more exactly, the problem 5 of Project Euler (http://projecteuler.net/), a site with mathematical problems that resolve with the use of algorithms. The problem 5 it follows below:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?
I trying resolve this using C, but I dont have an simple compiler in my work machine,because in my opinion, Visual C is much complex for this task… (some of my friends dont think it…)
But I think… I have perl interpretor in my machine and write this program in perl dont much harder and I starting the port of C for Perl and write this piece of code for solving my problem:
for ( my $n = 20; 1; $n++ ) {
for ( 1..20 ) {
if ( $n % $_ ) {
last;
}
if ( $_ == 20 ) {
die $n;
}
}
}
Well… is an idiot program, extremaly simple but I have the answer of problem with this… dont consider the execution time, “only” 20 min of the pure brute force for answering the problem… ehehhehehehehehhehe…
And perl with your practical syntax save my world one more time!!!!
In Play: Gorguts – The Erosion of Sanity – 04: Orphans of Sickness
Tutorial Basico de GDB
O post de hoje sera dedicado a esse famoso debugger do mundo UNIX e que pode ser utilizado em ambiente windows tambem, sim… vamos tratar do GNU Debugger ou GDB, software muito util para fazer analises e encontrar erros decorrentes em nossos programas.
Claro que a intenção desse post é ser bem basico, passando apenas informações necessarias para a iniciação, caso alguem queira saber mais, existe uma documentacao excelente, um exemplo disso e o livro Debugging with GDB
Entao chega de conversa e vamos ao que interessa..
Primeiro caso: Compilando para debugar
Iremos utilizar como exemplo, um programa que conta de 0 a 10, como queremos debugar esse programa, para isso utilizamos o seguinte comando
[jumpi@painkiller testes]$ gcc -g contador.c
Com esse comando geramos um arquivo de saida (a.out), que vai conter as informações necessarias para o debugging
Agora e hora de debugar, na linha de comando digitamos:
[jumpi@painkiller testes]$ gdb a.out
GNU gdb Red Hat Linux (6.5-15.fc6rh)
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type “show copying” to see the conditions.
There is absolutely no warranty for GDB. Type “show warranty” for details.
This GDB was configured as “i386-redhat-linux-gnu”…Using host libthread_db library “/lib/libthread_db.so.1″.
(gdb)
Com esse comando, entramos em modo de debugging e o gdb nos apresenta o prompt onde entramos com os comandos necessarios para o debugging.
Hora de definir o breakpoint: no gdb, podemos utilizar numero de linha ou ate mesmo o nome da funcao na qual se deseja inserir o breakpoint, no nosso caso vamos definir um breakpoint na funcao main com o seguinte comando
(gdb) break main
Breakpoint 1 at 0×8048395: file contador.c, line 7.
(gdb)
E agora rodamos o programa dentro do debugger com o seguinte comando
(gdb) run
Starting program: /home/jumpi/testes/a.out
Breakpoint 1, main () at contador.c:7
7 for (i=0; i<=10; i++) {
(gdb)
E ele para exatamente na linha onde foi inserido o breakpoint, no caso como definimos por funcao, entao ele para na primeira linha da funcao, numericamente falando, na linha 7
Agora temos 2 comandos que podemos utilizar para verificar as informacoes, step e next, no caso, step vai fazendo passo a passo, ou seja, linha por linha e o next é utilizado quando desejo passar por subrotinas, no nosso caso vamos utilizar o step e ver o que acontece
(gdb) step
8 printf(“Numero :%d\n”,i);
(gdb) step
Numero :0
7 for (i=0; i<=10; i++) {
(gdb) step
8 printf(“Numero :%d\n”,i);
(gdb) step
Numero :1
Ele vai executando cada passo da funcao solicitada, como estamos dentro de um laco, ele executa o laco ate o seu termino.
Suponha que eu quero verificar o valor da variavel no momento, nesse caso como eu possuo apenas a variavel i, vamos imprimir o seu valor, eu posso utilizar o comando print ou display da seguinte maneira
(gdb) print i
$1 = 4
(gdb) display i
1: i = 4
(gdb)
No caso, com print ele mostra a variavel temporaria que armazena o resultado e com display ele mostra a variavel definida pelo usuario no codigo.
Podemos setar tambem o valor das variaveis com o comando set variable da seguinte maneira
(gdb) set variable i=20
(gdb) display i
2: i = 20
(gdb)
Segundo caso: Utilizando o gdb para analisar coredumps
Coredumps sao arquivos que contem a informacao sobre um determinado erro gerado quando um programa e executado e utilizando o gdb podemos descobrir qual a anomalia do nosso programa
[jumpi@painkiller testes]$ gcc -g contador.c
[jumpi@painkiller testes]$ ./a.out
Numero
null)
Segmentation fault (core dumped)
[jumpi@painkiller testes]$
Isso significa que o programa gerou um erro e um coredump foi criado, quando verificamos o conteudo do diretorio procurando por core
[jumpi@painkiller testes]$ ls core*
core.6180
[jumpi@painkiller testes]$
Verificamos que o core foi criado, agora vamos utiliza-lo para servir como base de informacao para o nosso debugging no gdb
[jumpi@painkiller testes]$ gdb a.out core.6180
GNU gdb Red Hat Linux (6.5-15.fc6rh)
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type “show copying” to see the conditions.
There is absolutely no warranty for GDB. Type “show warranty” for details.
This GDB was configured as “i386-redhat-linux-gnu”…Using host libthread_db library “/lib/libthread_db.so.1″.
warning: Can’t read pathname for load map: Input/output error.
Reading symbols from /lib/libc.so.6…done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2…done.
Loaded symbols for /lib/ld-linux.so.2
Core was generated by `./a.out’.
Program terminated with signal 11, Segmentation fault.
#0 0×0077bf9b in strlen () from /lib/libc.so.6
(gdb)
Carregado o gdb com o arquivo de core, podemos utilizar o comando backtrace ou bt, para verificarmos as chamadas de funções e separarmos por frames
(gdb) bt
#0 0×0077bf9b in strlen () from /lib/libc.so.6
#1 0×0074e1ff in vfprintf () from /lib/libc.so.6
#2 0×007539c3 in printf () from /lib/libc.so.6
#3 0×080483b1 in main () at contador.c:7
(gdb)
Bem, no nosso caso eu verifico que tem um problema no frame 3, na linha 7, entao o comando frame seguido do numero do frame para verificar o que ocorre
(gdb) frame 3
#3 0×080483b1 in main () at contador.c:7
7 printf(“Numero :%s\n”,i);
(gdb)
E assim verifico que por descuido, coloquei um %s, onde era um %i…
Bem, utilizei apenas uma pequena fração para demonstrar do que o GDB é capaz, ele pode ser muito util para uma serie de outras coisas, sem contar que existem muitos outros detalhes mais especificos que nao foram abordados aqui nesse post, porem espero que seja util a vocês tambem… Ate a proxima!!! ![]()
No play: Cacophony – Speed Metal Symphony – 06: Desert Island
Yes, nos tambem temos int 3!!!! (tecnicas antidebugging no linux)
Well, seguindo o embalo do meu amigo de trabalho, a.k.a. Vandeco, tambem tentarei mostrar aqui uma tecnica antidebugging, so que em um S.O. diferente… no nosso caso vamos fazer o teste no linux e vamos verificar que int 3 e usual, sim… nao tenho duvidas, porem nao basta para livrar o nosso codigo do debugging alheio…
Tentarei demonstrar de forma resumida um exemplo de como burlar o debug do gdb
Primeiro exemplo de codigo, introduzir um breakpoint falso
#include <signal.h>
void handler (int signo) {
}
int main() {
signal(handler, SIGTRAP);
__asm__(“int3″);
printf(“Ola!!”);
}
[jumpi@painkiller testes]$ gcc -g debug-teste.c
[jumpi@painkiller testes]$
[jumpi@painkiller testes]$ gdb
GNU gdb Red Hat Linux (6.5-15.fc6rh)
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type “show copying” to see the conditions.
There is absolutely no warranty for GDB. Type “show warranty” for details.
This GDB was configured as “i386-redhat-linux-gnu”.
(gdb) file a.out
Reading symbols from /home/jumpi/testes/a.out…done.
Using host libthread_db library “/lib/libthread_db.so.1″.
(gdb) run
Starting program: /home/jumpi/testes/a.out
Program received signal SIGTRAP, Trace/breakpoint trap.
main () at debug-teste.c:11
11 printf(“Ola!!”);
(gdb) c
Continuing.
Ola!!
Program exited with code 05.
(gdb) quit
Ou seja, com isso forçamos um int 3 no codigo como se fosse um breakpoint e com o SIGTRAP capturamos o sinal, que faz com que ele pense que havia um breakpoint onde na verdade nao havia, simples e interessante…
Enfim, existem diversas outras tecnicas de debugging e antidebugging, como fazer controle da ptrace(), usando file descriptor ou ate mesmo por identificacao de processos. Porem fica para uma proxima ocasiao…
No play: Arsis – United in Regret – 04: I Speak Through Shadows
Java Elliptic Curve Cryptography
http://blogs.sun.com/andreas/entry/elliptic_curve_cryptography_in_java
Woooooow… Feature implementada no Mustang (JDK 1.6)… que permite com que se trabalhe com algoritimos de criptografia usando curvas elipticas (ECDSA e ECDH) que sao variacoes de DSA e DH so que utilizando curvas elipticas…
Preciso arrumar um tempo para testar… Hora de ir em cliente trabalhar agora…