[ create a new paste ] login | about

Link: http://codepad.org/Ju75Fb9j    [ raw code | fork ]

C, pasted on Aug 28:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
/*
**-------------------------------------------------------------------
**
** Mini Linguagem:
**   Sintax tipo C/Script, compilada( x86 ) 32 bits.
**
** ARQUIVO:
**   mini_0003.c
**
** PRINCIPAL FUNCAO:
**   int Parse (ASM *a, char *text);
**
** PALAVRAS RESERVADAS:
**   int, char *, struct *,
**   if, for, break.
**
** COMPILE:
**   gcc mini.c -o mini -Wall
**
** BUILD/VERSION:
**   0004 - 27/08/2015 - 20:45
** ----------------------------------------------
**
** 01: Implementada chamada de funcao com parametro ( tipo string )
**     sim o TRADICIONAL C ( printf("Hello World\n"); ) pode ser usado.
**     VEJA NO FINAL DESTE ARQUIVO A IMPLEMENTACAO DE ( lib_printf() ).
**
** Funcoes implementadas para chamada com string:
**
**   a: FUNCAO( struct FS *fs_new (char *s); )
**      cria uma lista encadeada com "string"
**
**   b: FUNCAO ( void asm_mov_var_reg (ASM *a, void *var, int reg); )
**      copia uma variavel para um REGISTRO
**
** FUNCOES/LIB EXTERNAL(usadas no script):
**
**   int    soma    (int a, int b);
**   void   var     (void);
**   void   print   (int i);
**   void   printf  (char *format, ...)
**
** ----------------------------------------------
**
** BY: Francisco G. A. - "gokernel" ( gokernel@hotmail.com )
**
**-------------------------------------------------------------------
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>        // to: isdigit();

#ifdef _WIN32
    #include <windows.h>
#endif
#ifdef __linux__
    #include <unistd.h>
    #include <sys/mman.h> // to: mprotect()
#endif

//-------------------------------------------------------------------
//########################  DEFINE/ENUM  ############################
//-------------------------------------------------------------------
//
#define ASM_DEFAULT_SIZE  50000
#define PROG_SIZE         50000
#define UCHAR             unsigned char

enum {
    TOK_INT = 255, TOK_CHAR, TOK_STRUCT, TOK_IF, TOK_FOR, TOK_BREAK,
    //----------------------------
    TOK_ID,           // identifier
    TOK_NUMBER,
    TOK_STRING,
    TOK_PLUS_PLUS,    // ++
    TOK_MINUS_MINUS   // --
};
enum {
    TYPE_LONG = 1,
    TYPE_FLOAT,
    TYPE_STRING,
    TYPE_POINTER,
    TYPE_STRUCT,
    TYPE_PSTRUCT      // struct data *p;
};
// register 32 bit
enum { EAX = 0, ECX, EDX, EBX, ESP, EBP, ESI, EDI };

// Lib Prototype:
int  lib_soma   (int a, int b);
void lib_var    (void); // mostra a lista de variaveis criadas
void lib_print  (int i);
void lib_printf (char *format, ...); // sim o TRADICIONAL C: printf

//-------------------------------------------------------------------
//###########################  STRUCT  ##############################
//-------------------------------------------------------------------
//
typedef struct ASM        ASM;
typedef struct ASM_label  ASM_label;
typedef struct ASM_jump   ASM_jump;
typedef struct VAR        VAR;
typedef struct LIB        LIB;

struct ASM {
    UCHAR     *p;         // to increment ...
    UCHAR     *code;      // code_len=: p - code
    ASM_label *label;
    ASM_jump  *jump;
    int       label_len;  // len of ( label ) array to realloc
    int       jump_len;   // len of ( jump  ) array to realloc
};
struct ASM_label {
    char  *text;
    int   pos;
};
struct ASM_jump {
    char  *text;
    int   pos;
    int   type;
};
struct VAR {
    char  *name;
    int   type;
    void  *info;  // any information ... struct type use this
    union {
        long  l;  //: type long integer
        float f;  //: type float
        char  *s; //: type pointer of char
        void  *p; //: type pointer
    }value;
};
struct FS { // fixed string
    char        *s;
    struct FS   *next;
};
struct LIB {
    char  *name;
    UCHAR *code;
}lib[]={
    { "soma",   (UCHAR *)lib_soma },
    { "var",    (UCHAR *)lib_var },
    { "print",  (UCHAR *)lib_print },
    { "printf", (UCHAR *)lib_printf }, // sim o TRADICIONAL C: printf

//  { "nome_funcao", (UCHAR *)lib_sua_funcao_em_puro_C },
    { NULL, NULL }
};

//-------------------------------------------------------------------
//###########################  PROTOTYPE  ###########################
//-------------------------------------------------------------------
//
void word_int     (ASM *a);
//
void expression   (ASM *a);
void expr0        (ASM *a);
void expr1        (ASM *a);
void expr2        (ASM *a);
void expr3        (ASM *a); //: atom
//
void g  (ASM *a, UCHAR c);                                // gen/emit apenas: 1 OPCODE
void g2 (ASM *a, UCHAR c1, UCHAR c2);                     // gen/emit: 2 OPCODEs
void g3 (ASM *a, UCHAR c1, UCHAR c2, UCHAR c3);           // gen/emit: 3 OPCODEs
void g4 (ASM *a, UCHAR c1, UCHAR c2, UCHAR c3, UCHAR c4); // gen/emit: 4 OPCODEs
//
void asm_imul_eax_esp   (ASM *a); // Multipliva no ANALIZADOR DE EXPRESSAO.
void asm_idivl_eax_esp  (ASM *a); // Divide     no ANALIZADOR DE EXPRESSAO.
void asm_add_eax_esp    (ASM *a); // Soma       no ANALIZADOR DE EXPRESSAO.
void asm_sub_eax_esp    (ASM *a); // Subtrai    no ANALIZADOR DE EXPRESSAO.
void asm_pushl_var      (ASM *a, void *var);          // envia para pilha uma variavel
void asm_push_number    (ASM *a, long value);         // envia para a pilha um numero
void asm_popl_var       (ASM *a, void *var);          // POP: copia o TOPO DA PILHA para uma variavel
void asm_sub_stack      (ASM *a, char c);             // habilita chamar funcoes com parametros
void asm_call           (ASM *a, void *func);         // chama uma funcao/lib
void asm_mov_reg_var    (ASM *a, int reg, void *var); // copia um REGISTRO para uma variavel
void asm_mov_var_reg    (ASM *a, void *var, int reg); // copia uma variavel para um REGISTRO
void asm_pop_eax        (ASM *a);
//
void CreateVarInt (char *name, int value);
int  VarFind      (char *name); // if not exist return -1
void erro_line    (char *s);

void proc_func    (ASM *a, UCHAR *code);

struct FS *fs_new (char *s); // Fixed String

//-------------------------------------------------------------------
//###########################  VARIABLE  ############################
//-------------------------------------------------------------------
//
VAR *Gvar = NULL; // global

static struct FS *fs = NULL; // Fixed String

static char
    *str,
    prog[PROG_SIZE], token[1024]
    ;

static int
    tok, erro, line, Gvar_len, stack
    ;

static int lex (void)
{
    char *p = token;

    *p = 0;

top:
    switch (*str) {
    //##################  SPACE  ################
    case '\n': line++;
    case ' ': case 9: case 13:
        str++; goto top;
        break;

    //################  STRING  #################
    case '"':
        str++; // '"'
        while (*str && *str != '"' && *str != '\r' && *str != '\n')
            *p++ = *str++;
        *p = 0;
        if (*str=='"') str++; else erro = 1;

        return TOK_STRING;

    //##########  WORD, IDENTIFIER ...  #########
    case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
    case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
    case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
    case 'v': case 'w': case 'x': case 'y': case 'z':
    case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
    case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
    case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
    case 'V': case 'W': case 'X': case 'Y': case 'Z':
    case '_':
        while (
        (*str >= 'a' && *str <= 'z') || (*str >= 'A' && *str <= 'Z') ||
        (*str >= '0' && *str <= '9') || *str == '_')
        {
            *p++ = *str++;
        }
        *p = 0;

        if (!strcmp(token, "int"))    return TOK_INT;
        if (!strcmp(token, "char"))   return TOK_CHAR;
        if (!strcmp(token, "struct")) return TOK_STRUCT;
        if (!strcmp(token, "if"))     return TOK_IF;
        if (!strcmp(token, "for"))    return TOK_FOR;
        if (!strcmp(token, "break"))  return TOK_BREAK;

        return TOK_ID;

    //#################  NUMBER  ################
    case '0': case '1': case '2': case '3': case '4': case '5': case '6':
    case '7': case '8': case '9':
        while ((*str >= '0' && *str <= '9') || *str == '.')
            *p++ = *str++;
        *p = 0;

        return TOK_NUMBER;

    //########  C suported character ...  #######
    case ',':
    case '=':
    case ';':
    case '&':
    case '+':
    case '-':
    case '*':
    case '/':
    case '.':
    case '#':
    case '!':
    case '{': case '}': case '(': case ')': case '<': case '>': case '[': case ']':

        //##########  REMOVE COMMENTS  ##########
        if (*str == '/'){
            if (str[1] == '*') { // comment block
                str += 2;
                do {
                    while (*str && *str != '*') {
                        if (*str == '\n') line++; //<<<<<<<<<<  line++  >>>>>>>>>>
                        str++;
                    }
                    str++;
                } while (*str && *str != '/');

                if (*str=='/') str++;
                else          erro = 1;

                goto top;

            } else if (str[1] == '/') { // comment line
                str += 2;
                while ((*str) && (*str != '\n') && (*str != '\r'))
                    str++;

                goto top;
            }
        }

        if (*str== '#') { str++; goto top; }
        if (*str=='+' && str[1]=='+') { str += 2; return TOK_PLUS_PLUS; }

        if (*str=='-') {

            if (str[1]=='-') { str += 2; return TOK_MINUS_MINUS; }

            if (isdigit(str[1])) { // number: -100
                *p++ = *str++;
                while ((*str >= '0' && *str <= '9') || *str == '.')
                    *p++ = *str++;
                *p = 0;
                return TOK_NUMBER;
            }
        }

        return *str++;

    case 0: return 0;

    default:
        printf ("ERRO LINE(%d): Ilegal char: (%c) %d\n", line, *str, *str);
        erro = 1;
    }
    return 0;
}
static int stmt (ASM *a)
{
    tok = lex();

    switch (tok) {
    case '{':
        while (tok && tok != '}') stmt(a);
        break;
    case TOK_INT: word_int(a); break;
    case ';':
    case '}':
        return 1;
    case 0: return 0;
    default:
        expression(a);
    }
    return 1;
}
void expression (ASM *a)
{
    if (tok==TOK_ID) {
        int i;
        char temp[255];

        // chama uma funcao/lib SEM RETORNO ... E RETORNA
        //
        // func_name();
        //
        LIB *l = lib;
        while (l->name) {
            if (!strcmp(l->name, token)) {
                proc_func (a, l->code);
                return;
            }
            l++;
        }

        strcpy (temp, token); // save

        if ((i=VarFind(token))!=-1) {
            tok=lex();
            if (tok=='=') {
                tok=lex();

                // chama uma funcao/lib COM RETORNO... E RETORNA
                //
                // i = func_name();
                //
                LIB *l = lib;
                while (l->name) {
                    if (!strcmp(l->name, token)) {

                        //
                        // chama a funcao e armazena o retorno em %EAX
                        //
                        proc_func (a, l->code);

                    // OBS:
                    //   todo retorno eh armazenado em %eax, exceto tipo (float e double).

                        // AGORA, copia %EAX para a VARIAVEL
                        //
                        asm_mov_reg_var(a, EAX, &Gvar[i].value.l);

                        return;
                    }
                    l++;
                }

                // OU UMA EXPRESSION:
                //
                // i = a * b + c * d;
                //
                expr0(a);
                //
                // Copia o TOPO DA PILHA ( %ESP ) para a variavel
                //
                asm_popl_var(a, &Gvar[i].value.l);
            }
            else erro_line("EXPRESSION NEED =\n");
        }
        else
        {
            erro_line("EXPRESSION:\n");
            printf ("Ilegal Word: '%s'\n", temp);
        }
    }
    else
    {
        erro_line("EXPRESSION:\n");
        if(*token) printf("TOKEN(%s)",token); else printf("%c = %d\n", tok, tok);
    }
}
// +, - : soma
void expr0 (ASM *a)
{
    int op;

    expr1(a);
    while ((op=tok) == '+' || op == '-') {
        tok=lex();
        expr1(a);
        switch (op) {
        case '+': asm_add_eax_esp(a); break;
        case '-': asm_sub_eax_esp(a); break;
        }
    }
}
// *, / : multiplica
void expr1 (ASM *a)
{
    int op;

    expr2(a);
    while ((op=tok) == '*' || op == '/') {
        tok=lex();
        expr2(a);
        switch (op) {
        case '*': asm_imul_eax_esp(a);   break;
        case '/': asm_idivl_eax_esp (a); break;
        }
    }
}
// (
void expr2 (ASM *a)
{
    if (tok=='(') {
        tok=lex();
        expr0(a);
        if (tok != ')') {
            printf ("ERRO )\n");
            erro_line (" ");
        }
        tok=lex();
    }
    else expr3(a); // atom:
}
// atom:
void expr3 (ASM *a)
{
    if (tok==TOK_ID) {
        int i;

        if ((i=VarFind(token))!=-1) {
            asm_pushl_var (a, &Gvar[i].value.l);
            tok=lex();
        }else{
            char buf[255];
            sprintf(buf, "%s: '%s'", "EXPRESSION VAR NOT FOUND:", token);
            erro_line(buf);
        }
    }
    else if (tok==TOK_NUMBER) {
        asm_push_number (a, atoi(token));
        tok=lex();
    }
    else erro_line("Expression");
}

// SINTAX:
//
// int a, b, c, d;
// int a = 100, b = 200, c = 1500;
//
void word_int (ASM *a)
{
    char name[255];
    int value;

    while ((tok=lex())) {
        if (tok==TOK_ID) {

            strcpy (name, token);
            value = 0;

            tok = lex();

            if (tok == '=') {
                if ((tok=lex())==TOK_NUMBER) {
                    value = atoi (token);
                    tok=lex(); // get nent char: ',' or ';'
                } else {
                    erro_line("NOT IS NUMBER: Word int please set only with number");
                    if (*token) printf("ERRO WORD: '%s'\n", token);
                    return;
                }
            }

            if (tok==',' || tok==';') {

                CreateVarInt (name, value); // create here

            } else {
                erro_line("ERRO: word int need chars( , or ; )");
                if (*token) printf("ERRO WORD: '%s'\n", token);
                return;
            }
        }
        if (tok==';') break;
    }
    if (tok != ';') {
        printf ("ERRO: word int need char ';'\n");
        erro = 1;
    }
}

void proc_func (ASM *a, UCHAR *code)
{
    int count=0, pos=0;

    if ((tok=lex())!='(') {
        erro_line ("Function need char: '('\n");
        return;
    }

    while ((tok=lex())) {
        if (tok==TOK_ID || tok==TOK_NUMBER || tok=='(') {

            // Processa uma expressao e armazena no TOPO DA PILHA ( %ESP ):
            //
            expr0(a);

            // UM POP EH NECESSASIO(para zerar a pilha) ...
            // Armazena o valor do TOP DA PILHA ( %ESP ) em %EAX
            //
            asm_pop_eax(a);

            // AGORA, passa os parametros:
            // Copia %EAX para a posicao da pilha ( de acordo com o parametro INTEIRO )
            //
            if (count == 0) {
                g3 (a,0x89,0x04,0x24); // 89 04 24           mov    %eax,(%esp)
            } else {
                g4 (a,0x89,0x44,0x24,(char)pos); // 89 44 24     04    mov    %eax,0x4(%esp)
            }
            count++;
            pos += 4;
        }
        else if (tok==TOK_STRING) {
            struct FS *s = fs_new (token);

            if (s) {

                // copia a variavel ( FIXED STRING ) para o registrador ( %EAX )
                //
                asm_mov_var_reg(a, &s->s, EAX);

                // AGORA, passa os parametros:
                // Copia %EAX para a posicao da pilha ( de acordo com o parametro )
                //
                if (count == 0) {
                    g3 (a,0x89,0x04,0x24); // 89 04 24           mov    %eax,(%esp)
                } else {
                    g4 (a,0x89,0x44,0x24,(char)pos); // 89 44 24     04    mov    %eax,0x4(%esp)
                }
                count++;
                pos += 4;
            }
        }
        if (count > 15) break;
        if (tok==';')   break;
    }
    asm_call (a, code);
}


void CreateVarInt (char *name, int value)
{
    register int i;
    VAR v;

    for(i=0;i<Gvar_len;i++)
        if(!strcmp(Gvar[i].name, name)){
            if(Gvar[i].type == TYPE_LONG)
                Gvar[i].value.l = value;
            return;
        }

    v.name = strdup (name);
    v.type = TYPE_LONG;
    v.value.l = value;
    v.info = NULL;

    Gvar = (VAR*) realloc (Gvar, (Gvar_len+1) * sizeof (VAR));
    Gvar[Gvar_len++] = v;
}
// if not exist return -1
int VarFind (char *name)
{
    register int i;

    for(i=0;i<Gvar_len;i++)
        if (!strcmp(Gvar[i].name, name)) return i;

    return -1;
}
struct FS *fs_new (char *s)
{
    struct FS *n;
    struct FS *p = fs;

    while (p) {
        if (!strcmp(p->s,s)) return p;
        p = p->next;
    }

    n = (struct FS*)malloc(sizeof(struct FS));
    n->s = strdup(s);
    // add on top
    n->next = fs;
    fs = n;

    return n;
}

//-------------------------------------------------------------------
//###########################  ASM API  #############################
//-------------------------------------------------------------------
//
ASM *asm_new (unsigned int size)
{
    ASM *a = (ASM*)malloc(sizeof(ASM));

    if (a && (a->code=(UCHAR*)malloc(size)) != NULL) {

        a->p = a->code;
        a->label = NULL;  // this use realloc
        a->jump  = NULL;  // this use realloc
        a->label_len = 0;
        a->jump_len  = 0;

        return a;
    }

    return NULL;
}
//-------------------------------------------------------------------
// This function use the code of Fabrice Bellard:
//
//   LIB:  tcc-0.9.25
//   FILE: libtcc.c
//   FUNC: void set_pages_executable (void *ptr, unsigned long length);
//   LINE: 400
//
// Set executable: a->code
//
//-------------------------------------------------------------------
void asm_set_executable (void *ptr, unsigned long len)
{
#ifdef _WIN32
    unsigned long old_protect;

    if (!VirtualProtect(ptr, len, PAGE_EXECUTE_READWRITE, &old_protect))
    {
        printf ("ERROR: asm_set_executable() ... NOT FOUND - VirtualProtect()\n");
        exit (-1);
    }
#endif

#ifdef __linux__
    unsigned long start, end, PageSize;

    PageSize = sysconf (_SC_PAGESIZE);
    start = (unsigned long)ptr & ~(PageSize - 1);
    end = (unsigned long)ptr + len;
    end = (end + PageSize - 1) & ~(PageSize - 1);
    if (mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
    {
        printf ("ERROR: asm_set_executable() ... NOT FOUND - mprotec()\n");
        exit (-1);
    }
#endif
}
void asm_get_addr (ASM *a, void *ptr) {
    *(void**)a->p = ptr;
    a->p += sizeof(void*);
}

//--------------------------------
//##########  gen/emit  ##########
//--------------------------------
void g (ASM *a, UCHAR c) {
    *a->p++ = c;
}
void g2 (ASM *a, UCHAR c1, UCHAR c2) {
    a->p[0] = c1;
    a->p[1] = c2;
    a->p += 2;
}
void g3 (ASM *a, UCHAR c1, UCHAR c2, UCHAR c3) {
    a->p[0] = c1;
    a->p[1] = c2;
    a->p[2] = c3;
    a->p += 3;
}
void g4 (ASM *a, UCHAR c1, UCHAR c2, UCHAR c3, UCHAR c4) {
    a->p[0] = c1;
    a->p[1] = c2;
    a->p[2] = c3;
    a->p[3] = c4;
    a->p += 4;
}
//--------------------------------
void asm_begin (ASM *a) {
    a->p[0] = 0x55;                 //: 55      push  %ebp
    a->p[1] = 0x89; a->p[2] = 0xe5; //: 89 e5   mov   %esp,%ebp
    a->p += 3;
}
void asm_end (ASM *a) {
    a->p[0] = 0xc9;  // leave
    a->p[1] = 0xc3;  // ret
    a->p += 2;

//    if (a->jump_len)
//        asm_change_label (a);
}
//------------------------------------------------
void asm_imul_eax_esp (ASM *a) {
    stack--;
    g(a,0x58);                  // 58               pop  %eax
    g4(a,0x0f,0xaf,0x04,0x24);  // 0f af 04 24      imul   (%esp),%eax
    g3(a,0x89,0x04,0x24);       // 89 04 24         mov    %eax,(%esp)
}
void asm_idivl_eax_esp (ASM *a) {
    stack--;
    stack--;
    g(a,0x59);        // 59       pop    %ecx
    g(a,0x58);        // 58       pop    %eax
    g(a,0x99);        // 99       cltd
    g2(a,0xf7,0xf9);  // f7 f9    idiv   %ecx
    g(a,0x50);        // 50       push   %eax
    stack++;
}
void asm_add_eax_esp (ASM *a) {
    stack--;
    g(a,0x58);              // 58         pop  %eax
    g3(a,0x01,0x04,0x24);   // 01 04 24   add   %eax,(%esp)
}
void asm_sub_eax_esp (ASM *a) {
    stack--;
    g(a,0x58);            // 58           pop  %eax
    g3(a,0x29,0x04,0x24); // 29 04 24     sub    %eax,(%esp)
}
//------------------------------------------------

// push variable on: %esp:
//
void asm_pushl_var (ASM *a, void *var) {
    stack++;
    g2(a,0xff,0x35); asm_get_addr(a,var); // ff 35    60 40 40 00   pushl   0x404060
}
// push number on: %esp:
//
void asm_push_number (ASM *a, long value) {
    stack++;
    if (value == (char)value) {
        g(a,0x6a);  // 6a   64    push   $0x64
        *a->p = value;
        a->p += sizeof(char);
    } else {
        g(a,0x68); // 68    00 e1 f5 05    push  $0x5f5e100
        *(long*)a->p = value;
        a->p += sizeof(long);
    }
}
// pop variable from( %esp )
//
void asm_popl_var (ASM *a, void *var) {
    stack--;
    g2(a,0x8f,0x05); asm_get_addr(a, var); // 8f 05    60 40 40 00    popl   0x404060
}
void asm_pop_eax (ASM *a) {
    stack--;
    *a->p++ = 0x58;  // 58     pop   %eax
}
void asm_sub_stack (ASM *a, char c) {
    g3(a,0x83,0xec,(char)c); // 83 ec 08   sub  $0x8,%esp
}
void asm_call (ASM *a, void *func) {
    // b8   7a 13 40 00       mov    $0x40137a,%eax
    // ff d0                	call   *%eax
    //
    g(a,0xb8); asm_get_addr(a, func);
    g2(a,0xff,0xd0);
}

// move: %register to variable
void asm_mov_reg_var (ASM *a, int reg, void *var) {
    if (reg >= 0 && reg <= 7) {
        switch (reg) {
        case EAX: g(a,0xa3);       break; // a3       10 40 40 00   mov   %eax,0x404010
        case ECX: g2(a,0x89,0x0d); break; // 89 0d    60 40 40 00   mov   %ecx,0x404060
        case EDX: g2(a,0x89,0x15); break; // 89 15    60 40 40 00   mov   %edx,0x404060
        }
        asm_get_addr(a,var);
    }
}
// move: variable to %register
void asm_mov_var_reg (ASM *a, void *var, int reg) {
    if (reg >= 0 && reg <= 7) {
        switch (reg) {
        case EAX: g(a,0xa1);       break; // a1       60 40 40 00   mov   0x404060,%eax
        case ECX: g2(a,0x8b,0x0d); break;	// 8b 0d    70 40 40 00   mov   0x404070,%ecx
        case EDX: g2(a,0x8b,0x15); break; // 8b 15    70 40 40 00   mov   0x404070,%edx
        }
        asm_get_addr (a, var);
    }
}


void erro_line (char *s) {
    printf ("ERRO LINE %d - %s\n", line, s);
    erro = 1;
}
int Parse (ASM *a, char *text)
{
    str = text;
    line = 1;
    erro = 0;

    asm_begin(a);

    //
    // Habilita chamar funcoes com parametro.
    //
    // Teste chamar um "script" que chame uma funcao com parametro
    // e COMENTE ESTA LINHA ( vai quebra o seu programa ). ;). SERIO.
    //
    asm_sub_stack (a, 80); //: 80 / 4 ==: MAXIMO DE 20 PARAMETROS

    while (!erro && stmt(a)) { }
    asm_end(a);

    if (erro) printf("<<<<<<<  ERRO  >>>>>>>\n");

    return erro;
}

int main (int argc, char *argv[])
{
    ASM *a;
    FILE *fp;

    if (argc >= 2 && (a=asm_new(ASM_DEFAULT_SIZE))!=NULL && (fp=fopen(argv[1], "rb"))!=NULL) {
        int c, i = 0;

        while ((c=getc(fp))!=EOF) prog[i++] = c; // store prog[];
        prog[i] = 0;
        fclose(fp);

        if ( !Parse(a,prog) ) {

            asm_set_executable (a->code, (int)(a->p - a->code)+5);

            ( (void(*)()) a->code ) (); // <<<<<<< execute here >>>>>>>
        }

        //--------------------------------
        //##########  Free ASM  ##########
        //--------------------------------
        if (a->label) {
            for(i=0;i<a->label_len;i++)
                if (a->label[i].text) free(a->label[i].text);

            free (a->label);
        }
        if (a->jump) {
            for(i=0;i<a->jump_len;i++)
                if (a->jump[i].text) free(a->jump[i].text);

            free(a->jump);
        }
        free(a->code);
        free(a);

        printf ("\nExiting With Sucess: STACK = %d !!!\n", stack);
    }
    else printf ("USAGE: mini <file.cs>\n");

    return 0;
}

//-------------------------------------------------------------------
//#############################  LIB  ###############################
//-------------------------------------------------------------------
//
int  lib_soma (int a, int b) { return a + b; }

void lib_var (void) {
    int i;
    printf("\nVar List:\n---------------\n");
    for(i=0;i<Gvar_len;i++)
        printf("Gvar(%s) = %ld\n", Gvar[i].name, Gvar[i].value.l);
}

void lib_print (int i) { printf ("%d\n", i); }

void lib_printf (char *format, ...)
{
    char msg[1024] = { 0 };
    register unsigned int i;
    va_list ap;

    va_start (ap,format);
    vsprintf (msg, format, ap);
    va_end (ap);

    for (i = 0; i < strlen(msg); i++) {
        if (msg[i] == '\\' && msg[i+1] == 'n') { // new line
            putc (10, stdout); // new line
            i++;
        }
        else if (msg[i] == '\\' && msg[i+1] == 't') { // tab
            putc ('\t', stdout); // tab
            i++;
        } else {
            putc (msg[i], stdout);
        }
    }
}


Create a new paste based on this one


Comments: