実行時、バイナリからCOMET II以外の値を読み込んだ場合はエラーが発生するよう変更
[YACASL2.git] / src / assemble.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <ctype.h>
5 #include <assert.h>
6
7 #include "assemble.h"
8 #include "cerr.h"
9
10 /**
11  * アセンブルモード: src, label, onlylabel, asdetail, onlyassemble
12  */
13 ASMODE asmode = {false, false, false, false, false};
14
15 /**
16  * アセンブルのプロパティ: ptr, lptr, *prog
17  */
18 ASPTR *asptr;
19
20 /**
21  * アセンブルのエラー定義
22  */
23 static CERR cerr_assemble[] = {
24     { 101, "label already defined" },
25     { 102, "label table is full" },
26     { 103, "label not found" },
27     { 106, "operand mismatch in assemble command" },
28     { 107, "no label in START" },
29     { 108, "not command of operand \"r\"" },
30     { 109, "not command of operand \"r1,r2\"" },
31     { 110, "not command of operand \"r,adr[,x]\"" },
32     { 111, "not command of operand \"adr[,x]\"" },
33     { 112, "not command of no operand" },
34     { 113, "operand too many in COMET II command" },
35     { 119, "out of COMET II memory" },
36     { 120, "GR0 in operand x" },
37     { 122, "cannot create hash table" },
38     { 124, "more than one character in literal" },
39     { 125, "not GR in operand x" },
40 };
41
42 WORD getadr(const char *prog, const char *str, PASS pass);
43
44 WORD getgr(const char *str, bool is_x);
45
46 WORD getliteral(const char *str, PASS pass);
47
48 bool assemblecmd(const CMDLINE *cmdl, PASS pass);
49
50 bool macrocmd(const CMDLINE *cmdl, PASS pass);
51
52 void writeIN(const char *ibuf, const char *len, PASS pass);
53
54 void writeOUT(const char *obuf, const char *len, PASS pass);
55
56 void writeRPUSH(PASS pass);
57
58 void writeRPOP(PASS pass);
59
60 bool cometcmd(const CMDLINE *cmdl, PASS pass);
61
62 bool writememory(WORD word, WORD adr, PASS pass);
63
64 void writestr(const char *str, bool literal, PASS pass);
65
66 void writeDC(const char *str, PASS pass);
67
68 bool assembletok(const CMDLINE *cmdl, PASS pass);
69
70 bool assembleline(const char *line, PASS pass);
71
72 void printline(FILE *stream, const char *filename, int lineno, char *line);
73
74 /**
75  * 汎用レジスタを表す文字列「GR[0-7]」から、レジスタ番号[0-7]をWORD値で返す
76  * 文字列が汎用レジスタを表さない場合は、0xFFFFを返す
77  * is_xがtrueの場合は指標レジスタ。GR0が指定された場合は、COMET IIの仕様によりエラー発生
78  */
79 WORD getgr(const char *str, bool is_x)
80 {
81     assert(str != NULL);
82     WORD r;
83     /* 「GR[0-7]」以外の文字列では、0xFFFFを返して終了 */
84     if(!(strlen(str) == 3 && strncmp(str, "GR", 2) == 0 &&
85          (*(str+2) >= '0' && *(str+2) <= '0' + (GRSIZE - 1))))
86     {
87         return 0xFFFF;
88     }
89     r = (WORD)(*(str+2) - '0');
90     /* GR0は指標レジスタとして用いることができない */
91     if(is_x == true && r == 0x0) {
92         setcerr(120, NULL);    /* GR0 in operand x */
93         return 0x0;
94     }
95     return r;
96 }
97
98 /**
99  * 定数の前に等号(=)をつけて記述されるリテラルを返す
100  * リテラルには、10進定数/16進定数/文字定数が含まれる
101  */
102 WORD getliteral(const char *str, PASS pass)
103 {
104     WORD adr = asptr->lptr;
105     assert(*str == '=');
106     if(*(++str) == '\'') {    /* 文字定数 */
107         writestr(str, true, pass);
108     } else {
109         writememory(nh2word(str), (asptr->lptr)++, pass);
110     }
111     return adr;
112 }
113
114 /**
115  * アセンブラ命令をメモリに書込
116  * 実行に成功した場合はtrue、それ以外の場合はfalseを返す
117  */
118 bool assemblecmd(const CMDLINE *cmdl, PASS pass)
119 {
120     int i = 0;
121     ASCMDID cmdid = 0;
122     bool status = false;
123     ASCMD ascmd[] = {
124         { START, 0, 1, "START" },
125         { END, 0, 0, "END" },
126         { DC, 1, OPDSIZE, "DC" },
127         { DS, 1, 1, "DS" },
128         { 0, 0, 0, NULL }
129     };
130
131     do {
132         if(strcmp(cmdl->cmd, ascmd[i].cmd) == 0) {
133             if(cmdl->opd->opdc < ascmd[i].opdc_min || cmdl->opd->opdc > ascmd[i].opdc_max) {
134                 setcerr(106, NULL);    /* operand count mismatch */
135                 return false;
136             }
137             cmdid = ascmd[i].cmdid;
138             break;
139         }
140     } while(ascmd[++i].cmdid != 0);
141     /* アセンブラ命令 */
142     switch(cmdid)
143     {
144     case START:
145         if(cmdl->label == NULL) {
146             setcerr(107, NULL);    /* no label in START */
147             return false;
148         }
149         /* プログラム名の設定 */
150         asptr->prog = strdup_chk(cmdl->label, "asptr.prog");
151         /* オペランドがある場合、実行開始アドレスを設定 */
152         if(pass == SECOND && cmdl->opd->opdc == 1) {
153             if((execptr->start = getlabel(asptr->prog, cmdl->opd->opdv[0])) == 0xFFFF) {
154                 setcerr(103, cmdl->opd->opdv[0]);    /* label not found */
155             }
156         }
157         status = true;
158         break;
159     case END:
160         /* 1回目のアセンブルの場合は、リテラル領域開始アドレスを設定 */
161         if(pass == FIRST) {
162             asptr->lptr = asptr->ptr;
163         }
164         /* 2回目のアセンブルの場合は、リテラル領域終了アドレスを実行終了アドレスとして設定 */
165         else if(pass == SECOND) {
166             execptr->end = asptr->lptr;
167         }
168         /* プログラム名のクリア */
169         asptr->prog = NULL;
170         status = true;
171         break;
172     case DS:
173         for(i = 0; i < atoi(cmdl->opd->opdv[0]); i++) {
174             writememory(0x0, (asptr->ptr)++, pass);
175             if(cerr->num > 0) {
176                 return false;
177             }
178         }
179         status = true;
180         break;
181     case DC:
182         for(i = 0; i < cmdl->opd->opdc; i++) {
183             writeDC(cmdl->opd->opdv[i], pass);
184             if(cerr->num > 0) {
185                 return false;
186             }
187         }
188         status = true;
189         break;
190     default:
191         return false;
192     }
193     if(cerr->num > 0) {
194         status = false;
195     }
196     return status;
197 }
198
199 /**
200  *  macrocmd
201  *  マクロ命令をメモリに書込
202  *  書込に成功した場合はtrue、それ以外の場合はfalseを返す
203  */
204 bool macrocmd(const CMDLINE *cmdl, PASS pass)
205 {
206     int i = 0;
207     MACROCMDID cmdid = 0;
208      MACROCMD macrocmd[] = {
209         { IN, 2, 2, "IN" },
210         { OUT, 2, 2, "OUT" },
211         { RPUSH, 0, 0, "RPUSH" },
212         { RPOP, 0, 0, "RPOP" },
213         { 0, 0, 0, NULL }
214     };
215
216     do {
217         if(strcmp(cmdl->cmd, macrocmd[i].cmd) == 0) {
218             if(cmdl->opd->opdc < macrocmd[i].opdc_min ||
219                cmdl->opd->opdc > macrocmd[i].opdc_max)
220             {
221                 setcerr(106, NULL);    /* operand count mismatch */
222                 return false;
223             }
224             cmdid = macrocmd[i].cmdid;
225             break;
226         }
227     } while(macrocmd[++i].cmdid != 0);
228     switch(cmdid)
229     {
230     case IN:
231         writeIN(cmdl->opd->opdv[0], cmdl->opd->opdv[1], pass);
232         return true;
233     case OUT:
234         writeOUT(cmdl->opd->opdv[0], cmdl->opd->opdv[1], pass);
235         return true;
236     case RPUSH:
237         writeRPUSH(pass);
238         return true;
239     case RPOP:
240         writeRPOP(pass);
241         return true;
242     default:
243         return false;
244     }
245 }
246
247 /**
248  * マクロ命令「IN IBUF,LEN」をメモリに書込
249  *      PUSH 0,GR1
250  *      PUSH 0,GR2
251  *      LAD GR1,IBUF
252  *      LAD GR2,LEN
253  *      SVC 1
254  *      POP GR2
255  *      POP GR1
256  */
257 void writeIN(const char *ibuf, const char *len, PASS pass)
258 {
259     char *line = malloc_chk(LINESIZE+1, "writeIN.line");
260
261     assembleline("    PUSH 0,GR1", pass);
262     assembleline("    PUSH 0,GR2", pass);
263     sprintf(line, "    LAD GR1,%s", ibuf);
264     assembleline(line, pass);
265     sprintf(line, "    LAD GR2,%s", len);
266     assembleline(line, pass);
267     assembleline("    SVC 1", pass);
268     assembleline("    POP GR2", pass);
269     assembleline("    POP GR1", pass);
270
271     free_chk(line, "writeIN.line");
272 }
273
274 /**
275  *  マクロ命令「OUT OBUF,LEN」をメモリに書込
276  *      PUSH 0,GR1
277  *      PUSH 0,GR2
278  *      LAD GR1,OBUF
279  *      LAD GR2,LEN
280  *      SVC 2
281  *      LAD GR1,=#A
282  *      LAD GR2,=1
283  *      SVC 2
284  *      POP GR2
285  *      POP GR1
286  */
287 void writeOUT(const char *obuf, const char *len, PASS pass)
288 {
289     char *line = malloc_chk(LINESIZE+1, "writeOUT.line");
290
291     assembleline("    PUSH 0,GR1", pass);
292     assembleline("    PUSH 0,GR2", pass);
293     sprintf(line, "    LAD GR1,%s", obuf);
294     assembleline(line, pass);
295     sprintf(line, "    LAD GR2,%s", len);
296     assembleline(line, pass);
297     assembleline("    SVC 2", pass);
298     assembleline("    LAD GR1,=#A", pass);
299     assembleline("    LAD GR2,=1", pass);
300     assembleline("    SVC 2", pass);
301     assembleline("    POP GR2", pass);
302     assembleline("    POP GR1", pass);
303     free_chk(line, "writeOUT.line");
304 }
305
306 /** マクロ命令「RPUSH」をメモリに書き込む
307  *       PUSH 0,GR1
308  *       PUSH 0,GR2
309  *       PUSH 0,GR3
310  *       PUSH 0,GR4
311  *       PUSH 0,GR5
312  *       PUSH 0,GR6
313  *       PUSH 0,GR7
314  */
315 void writeRPUSH(PASS pass)
316 {
317     int i;
318     char *line = malloc_chk(LINESIZE+1, "writeRPUSH.line");
319
320     for(i = 1; i <= GRSIZE-1; i++) {
321         sprintf(line, "    PUSH 0,GR%d", i);
322         assembleline(line, pass);
323     }
324     free_chk(line, "writeRPUSH.line");
325 }
326
327 /**
328  * マクロ命令「RPOP」をメモリに書き込む
329  *      POP GR7
330  *      POP GR6
331  *      POP GR5
332  *      POP GR4
333  *      POP GR3
334  *      POP GR3
335  *      POP GR2
336  *      POP GR1
337  */
338 void writeRPOP(PASS pass)
339 {
340     int i;
341     char *line = malloc_chk(LINESIZE+1, "writeRPOP.line");
342
343     for(i = GRSIZE-1; i >= 1; i--) {
344         sprintf(line, "    POP GR%d", i);
345         assembleline(line, pass);
346     }
347     free_chk(line, "writeRPOP.line");
348 }
349
350 /**
351  * 機械語命令をメモリに書込
352  * 書込に、成功した場合はtrue、失敗した場合はfalse、を返す
353  */
354 bool cometcmd(const CMDLINE *cmdl, PASS pass)
355 {
356     WORD cmd, adr, r1, r2, x;
357     bool status = false;
358
359     /* オペランドなし */
360     if(cmdl->opd->opdc == 0) {
361         if((cmd = getcmdcode(cmdl->cmd, NONE)) == 0xFFFF) {
362             setcerr(112, cmdl->cmd);    /* not command of no operand */
363             return false;
364         }
365         if(writememory(cmd, (asptr->ptr)++, pass) == true) {
366             status = true;
367         }
368     }
369     /* 第1オペランドは汎用レジスタ */
370     else if((r1 = getgr(cmdl->opd->opdv[0], false)) != 0xFFFF) {
371         /* オペランド数1 */
372         if(cmdl->opd->opdc == 1) {
373             if((cmd = getcmdcode(cmdl->cmd, R_)) == 0xFFFF) {
374                 setcerr(108, cmdl->cmd);    /* not command of operand "r" */
375                 return false;
376             }
377             cmd |= (r1 << 4);
378             if(writememory(cmd, (asptr->ptr)++, pass) == true) {
379                 status = true;
380             }
381         }
382         /* オペランド数2。第2オペランドは汎用レジスタ */
383         else if(cmdl->opd->opdc == 2 && (r2 = getgr(cmdl->opd->opdv[1], false)) != 0xFFFF) {
384             if((cmd = getcmdcode(cmdl->cmd, R1_R2)) == 0xFFFF) {
385                 setcerr(109, cmdl->cmd);    /* not command of operand "r1,r2" */
386                 return false;
387             }
388             cmd |= ((r1 << 4) | r2);
389             if(cerr->num == 0 && writememory(cmd, (asptr->ptr)++, pass) == true) {
390                 status = true;
391             }
392         }
393         /* オペランド数2または3。第2オペランドはアドレス、 */
394         /* 第3オペランドは指標レジスタとして用いる汎用レジスタ */
395         else if(cmdl->opd->opdc == 2 || cmdl->opd->opdc == 3) {
396             if((cmd = getcmdcode(cmdl->cmd, R_ADR_X_)) == 0xFFFF &&
397                (cmd = getcmdcode(cmdl->cmd, R_ADR_X)) == 0xFFFF)
398             {
399                 setcerr(110, cmdl->cmd);    /* not command of operand "r,adr[,x]" */
400                 return false;
401             }
402             cmd |= (r1 << 4);
403             /* オペランド数3 */
404             if(cmdl->opd->opdc == 3) {
405                 if((x = getgr(cmdl->opd->opdv[2], true)) == 0xFFFF) {
406                     setcerr(125, cmdl->cmd);    /* not GR in operand x */
407                     return false;
408                 }
409                 cmd |= x;
410             }
411             adr = getadr(asptr->prog, cmdl->opd->opdv[1], pass);
412             writememory(cmd, (asptr->ptr)++, pass);
413             writememory(adr, (asptr->ptr)++, pass);
414             if(cerr->num == 0) {
415                 status = true;
416             }
417         } else {
418             setcerr(113, cmdl->cmd);    /* operand too many in COMET II command */
419             return false;
420         }
421     }
422     /* オペランド数1または2。第1オペランドはアドレス */
423     else if(cmdl->opd->opdc == 1 || cmdl->opd->opdc == 2) {
424         if((cmd = getcmdcode(cmdl->cmd, ADR_X)) == 0xFFFF) {
425             setcerr(111, cmdl->cmd);    /* not command of operand "adr[,x]" */
426             return false;
427         }
428         /* オペランド数2の場合、第2オペランドは指標レジスタとして用いる汎用レジスタ */
429         if(cmdl->opd->opdc == 2) {
430             x = getgr(cmdl->opd->opdv[1], true);
431             if(cerr->num > 0) {
432                 return false;
433             }
434             cmd |= x;
435         }
436         /* CALLの場合はプログラムの入口名を表すラベルを取得 */
437         /* CALL以外の命令の場合と、プログラムの入口名を取得できない場合は、 */
438         /* 同一プログラム内のラベルを取得 */
439         if(pass == SECOND && cmd == 0x8000) {        /* CALL命令 */
440             adr = getlabel(NULL, cmdl->opd->opdv[0]);
441         }
442         if(cmd != 0x8000 || (pass == SECOND && adr == 0xFFFF)) {
443             adr = getadr(asptr->prog, cmdl->opd->opdv[0], pass);
444         }
445         writememory(cmd, (asptr->ptr)++, pass);
446         writememory(adr, (asptr->ptr)++, pass);
447         if(cerr->num == 0) {
448             status = true;
449         }
450     }
451     return status;
452 }
453
454 /**
455  * COMET IIのメモリにアドレス値を書き込む
456  */
457 bool writememory(WORD word, WORD adr, PASS pass)
458 {
459     bool status = false;
460
461     /* COMET IIメモリオーバーの場合 */
462     if(adr >= sys->memsize) {
463         setcerr(119, word2n(adr));    /* out of COMET II memory */
464     }
465     if(cerr->num == 0) {
466         (sys->memory)[adr] = word;
467         if(pass == SECOND && asmode.asdetail == true) {
468             fprintf(stdout, "\t#%04X\t#%04X\n", adr, word);
469         }
470         status = true;
471     }
472     return status;
473 }
474
475 /**
476  * 文字をメモリに書き込む
477  */
478 void writestr(const char *str, bool literal, PASS pass)
479 {
480     assert(cerr->num == 0 && *str == '\'');
481     const char *p = str + 1;
482     bool lw = false;
483
484     for(; ;) {
485         /* 閉じ「'」がないまま文字列が終了した場合 */
486         if(*p == '\0') {
487             setcerr(123, str);    /* unclosed quote */
488             break;
489         }
490         /* 「'」の場合、次の文字が「'」でない場合は正常終了 */
491         if(*p == '\'' && *(++p) != '\'') {
492             break;
493         } else if(literal == true && lw == true) {
494             setcerr(124, str);    /* more than one character in literal */
495             break;
496         }
497         /*リテラルの場合はリテラル領域に書込 */
498         if(literal == true) {
499             writememory(*(p++), (asptr->lptr)++, pass);
500             lw = true;
501         } else {
502             writememory(*(p++), (asptr->ptr)++, pass);
503         }
504     }
505 }
506
507 /**
508  * DC命令の内容を書き込む
509  */
510 void writeDC(const char *str, PASS pass)
511 {
512     WORD adr = 0x0;
513     if(*str == '\'') {
514         writestr(str, false, pass);
515     } else {
516         if(*str == '#' || isdigit(*str) || *str == '-') {
517             adr = nh2word(str);
518         } else {
519             if(pass == SECOND && (adr = getlabel(asptr->prog, str)) == 0xFFFF) {
520                 setcerr(103, str);    /* label not found */
521             }
522         }
523         writememory(adr, (asptr->ptr)++, pass);
524     }
525 }
526
527 /**
528  * 1行をアセンブル
529  */
530 bool assembletok(const CMDLINE *cmdl, PASS pass)
531 {
532     bool status = false;
533     /* 命令がない場合 */
534     if(cmdl->cmd == NULL){
535         /* ラベルが定義されていて命令がない場合はエラー */
536         if(cmdl->label != NULL) {
537             setcerr(105, NULL);    /* no command in the line */
538         }
539     }
540     /* アセンブラ命令の処理 */
541     else if(cerr->num == 0 && assemblecmd(cmdl, pass) == true) {
542         ;
543     }
544     /* マクロ命令の書込 */
545     else if(cerr->num == 0 && macrocmd(cmdl, pass) == true) {
546         ;
547     }
548     /* 機械語命令の書込 */
549     else if(cerr->num == 0 && cometcmd(cmdl, pass) == true) {
550         ;
551     }
552     else if(cerr->num == 0) {
553         setcerr(113, cmdl->cmd);    /* operand too many in COMET II command */
554     }
555     /* エラーが発生していないか確認 */
556     if(cerr->num == 0) {
557         status = true;
558     }
559     return status;
560 }
561
562 /**
563  * ファイルストリームの現在行を番号付きで表示する
564  */
565 void printline(FILE *stream, const char *filename, int lineno, char *line)
566 {
567     fprintf(stream, "%s:%5d:%s", filename, lineno, line);
568 }
569
570 /**
571  * アドレスを返す
572  * アドレスには、リテラル/10進定数/16進定数/アドレス定数が含まれる
573  */
574 WORD getadr(const char *prog, const char *str, PASS pass)
575 {
576     WORD adr = 0x0;
577     if(*str == '=') {
578         adr = getliteral(str, pass);
579     } else if(isdigit(*str) || *str == '-' || *str == '#') {
580         adr = nh2word(str);
581     } else {
582         if(pass == SECOND && (adr = getlabel(prog, str)) == 0xFFFF) {
583             if(prog != NULL) {
584                 setcerr(103, str);    /* label not found */
585             }
586         }
587     }
588     return adr;
589 }
590
591
592 /**
593  * 1行をアセンブル
594  */
595 bool assembleline(const char *line, PASS pass)
596 {
597     CMDLINE *cmdl;
598
599     if((cmdl = linetok(line)) != NULL) {
600         if(pass == FIRST && cmdl->label != NULL) {
601             if(addlabel(asptr->prog, cmdl->label, asptr->ptr) == false) {
602                 return false;
603             }
604         }
605         if(assembletok(cmdl, pass) == false) {
606             return false;
607         }
608     }
609     return true;
610 }
611
612 /**
613  * アセンブルのエラーをエラーリストに追加
614  */
615 void addcerrlist_assemble()
616 {
617     addcerrlist_tok();
618     addcerrlist_word();
619     addcerrlist(ARRAYSIZE(cerr_assemble), cerr_assemble);
620 }
621
622 /**
623  * 指定された名前のファイルをアセンブル
624  * 2回実行される
625  */
626 bool assemble(const char *file, PASS pass)
627 {
628     int lineno = 0;
629     bool status = true;
630     CMDLINE *cmdl;
631     char *line;
632     FILE *fp;
633
634     if((fp = fopen(file, "r")) == NULL) {
635         perror(file);
636         return false;
637     }
638     for(; ;) {
639         cmdl = malloc_chk(sizeof(CMDLINE), "cmdl");
640         line = malloc_chk(LINESIZE + 1, "line");
641         if((line = fgets(line, LINESIZE, fp)) == NULL) {
642             break;
643         }
644         lineno++;
645         if((pass == FIRST && asmode.src == true) ||
646            (pass == SECOND && asmode.asdetail == true))
647         {
648             printline(stdout, file, lineno, line);
649         }
650         if(assembleline(line, pass) == false) {
651             break;
652         }
653         if(cerr->num > 0) {
654             break;
655         }
656         free_chk(line, "line");
657         free_chk(cmdl, "cmdl");
658     }
659     if(cerr->num > 0) {
660         fprintf(stderr, "Assemble error - %d: %s\n", cerr->num, cerr->msg);
661         printline(stderr, file, lineno, line);
662         status = false;
663     }
664     fclose(fp);
665     return status;
666 }
667
668 /**
669  * 引数で指定したファイルにアセンブル結果を書込
670  */
671 void outassemble(const char *file)
672 {
673     FILE *fp;
674
675     if((fp = fopen(file, "w")) == NULL) {
676         perror(file);
677         exit(-1);
678     }
679     fwrite(sys->memory, sizeof(WORD), execptr->end, fp);
680     fclose(fp);
681 }