* src/pic/device.c (find_device): prevent buffer underflow error
[fw/sdcc] / src / pic / device.c
1 /*-------------------------------------------------------------------------
2
3    device.c - Accomodates subtle variations in PIC devices
4    Written By -  Scott Dattalo scott@dattalo.com
5
6    This program is free software; you can redistribute it and/or modify it
7    under the terms of the GNU General Public License as published by the
8    Free Software Foundation; either version 2, or (at your option) any
9    later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 -------------------------------------------------------------------------*/
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <ctype.h>
24
25 #include "common.h"   // Include everything in the SDCC src directory
26 #include "newalloc.h"
27
28
29 #include "main.h"
30 #include "pcode.h"
31 #include "ralloc.h"
32 #include "device.h"
33
34 extern int Gstack_base_addr;
35 extern int Gstack_size;
36
37 #define MAX_PICLIST 200
38 static PIC_device *Pics[MAX_PICLIST];
39 static int num_of_supported_PICS = 0;
40
41 static PIC_device *pic=NULL;
42
43 int maxRAMaddress = 0;
44
45 #define CONFIG_WORD_ADDRESS 0x2007
46 #define CONFIG2_WORD_ADDRESS 0x2008
47 #define DEFAULT_CONFIG_WORD 0x3fff
48 #define DEFAULT_CONFIG2_WORD 0x3ffc
49
50 #define DEVICE_FILE_NAME "pic14devices.txt"
51 #define PIC14_STRING_LEN 256
52 #define SPLIT_WORDS_MAX 16
53
54 static unsigned int config_word = DEFAULT_CONFIG_WORD;
55 static unsigned int config2_word = DEFAULT_CONFIG2_WORD;
56 static memRange *rangeRAM = NULL;
57
58
59 /* parse a value from the configuration file */
60 static int parse_config_value(char *str)
61 {
62         if (str[strlen(str) - 1] == 'K')
63                 return atoi(str) * 1024;        /* like "1K" */
64                 
65         else if (STRNCASECMP(str, "0x", 2) == 0)
66                 return strtol(str+2, NULL, 16); /* like "0x400" */
67         
68         else
69                 return atoi(str);               /* like "1024" */
70 }
71
72
73 /* split a line into words */
74 static int split_words(char result_word[SPLIT_WORDS_MAX][PIC14_STRING_LEN], char *str)
75 {
76         char *pos = str;
77         int num_words = 0;
78         int ccount;
79         
80         while (*pos != '\0' && num_words < SPLIT_WORDS_MAX) {
81                 /* remove leading spaces */
82                 while (isspace(*pos) || *pos == ',')
83                         pos++;
84         
85                 /* copy everything up until the first space or comma */
86                 for (ccount = 0; *pos != '\0' && !isspace(*pos) && *pos != ',' && ccount < PIC14_STRING_LEN-1; ccount++, pos++)
87                         result_word[num_words][ccount] = *pos;
88                 result_word[num_words][ccount] = '\0';
89                 
90                 num_words++;
91         }
92         
93         return num_words;
94 }
95
96
97 /* remove annoying prefixes from the processor name */
98 static char *sanitise_processor_name(char *name)
99 {
100         char *proc_pos = name;
101
102         if (name == NULL)
103                 return NULL;
104         
105         if (STRNCASECMP(proc_pos, "pic", 3) == 0)
106                 proc_pos += 3;
107
108         else if (tolower(*proc_pos) == 'p')
109                 proc_pos += 1;
110                                 
111         return proc_pos;
112 }
113
114
115 /* create a structure for a pic processor */
116 static PIC_device *create_pic(char *pic_name, int maxram, int bankmsk, int confsiz, int program, int data, int eeprom, int io)
117 {
118         PIC_device *new_pic;
119         char *simple_pic_name = sanitise_processor_name(pic_name);
120         
121         new_pic = Safe_calloc(1, sizeof(PIC_device));
122         new_pic->name = Safe_calloc(strlen(simple_pic_name)+1, sizeof(char));
123         strcpy(new_pic->name, simple_pic_name);
124                         
125         new_pic->defMaxRAMaddrs = maxram;
126         new_pic->bankMask = bankmsk;
127         new_pic->hasSecondConfigReg = confsiz > 1;
128         
129         new_pic->programMemSize = program;
130         new_pic->dataMemSize = data;
131         new_pic->eepromMemSize = eeprom;
132         new_pic->ioPins = io;
133
134         new_pic->ram = rangeRAM;
135         
136         Pics[num_of_supported_PICS] = new_pic;
137         num_of_supported_PICS++;
138                         
139         return new_pic;
140 }
141
142
143 /* mark some registers as being duplicated across banks */
144 static void register_map(int num_words, char word[SPLIT_WORDS_MAX][PIC14_STRING_LEN])
145 {
146         memRange *r;
147         int pcount;
148         
149         if (num_words < 3) {
150                 fprintf(stderr, "WARNING: not enough values in %s regmap directive\n", DEVICE_FILE_NAME);
151                 return;
152         }
153
154         for (pcount = 2; pcount < num_words; pcount++) {
155                 r = Safe_calloc(1, sizeof(memRange));
156                 
157                 r->start_address = parse_config_value(word[pcount]);
158                 r->end_address = parse_config_value(word[pcount]);
159                 r->alias = parse_config_value(word[1]);
160                 r->bank = (r->start_address >> 7) & 3;
161                 // add memRange to device entry for future lookup (sharebanks)
162                 r->next = rangeRAM;
163                 rangeRAM = r;
164         }
165 }
166
167
168 /* define ram areas - may be duplicated across banks */
169 static void ram_map(int num_words, char word[SPLIT_WORDS_MAX][PIC14_STRING_LEN])
170 {
171         memRange *r;
172         
173         if (num_words < 4) {
174                 fprintf(stderr, "WARNING: not enough values in %s memmap directive\n", DEVICE_FILE_NAME);
175                 return;
176         }
177
178         r = Safe_calloc(1, sizeof(memRange));
179         //fprintf (stderr, "%s: %s %s %s\n", __FUNCTION__, word[1], word[2], word[3]);
180         
181         r->start_address = parse_config_value(word[1]);
182         r->end_address = parse_config_value(word[2]);
183         r->alias = parse_config_value(word[3]);
184         r->bank = (r->start_address >> 7) & 3;
185                 
186         // add memRange to device entry for future lookup (sharebanks)
187         r->next = rangeRAM;
188         rangeRAM = r;
189 }
190
191 extern set *includeDirsSet;
192 extern set *userIncDirsSet;
193 extern set *libDirsSet;
194 extern set *libPathsSet;
195
196 /* read the file with all the pic14 definitions and pick out the definition for a processor
197  * if specified. if pic_name is NULL reads everything */
198 static PIC_device *find_device(char *pic_name)
199 {
200         FILE *pic_file;
201         char pic_buf[PIC14_STRING_LEN];
202         char *pic_buf_pos;
203         int found_processor = FALSE;
204         int done = FALSE;
205         char processor_name[SPLIT_WORDS_MAX][PIC14_STRING_LEN];
206         int num_processor_names = 0;
207         int pic_maxram = 0;
208         int pic_bankmsk = 0;
209         int pic_confsiz = 0;
210         int pic_program = 0;
211         int pic_data = 0;
212         int pic_eeprom = 0;
213         int pic_io = 0;
214         char *simple_pic_name;
215         char *dir;
216         char filename[512];
217         int len = 512;
218         
219         /* allow abbreviations of the form "f877" - convert to "16f877" */
220         simple_pic_name = sanitise_processor_name(pic_name);
221         num_of_supported_PICS = 0;
222         
223         /* open the piclist file */
224         /* first scan all include directories */
225         pic_file = NULL;
226         //fprintf( stderr, "%s: searching %s\n", __FUNCTION__, DEVICE_FILE_NAME );
227         for (dir = setFirstItem(includeDirsSet);
228                 !pic_file && dir;
229                 dir = setNextItem(includeDirsSet))
230         {
231           //fprintf( stderr, "searching1 %s\n", dir );
232           SNPRINTF(&filename[0], len, "%s%s%s", dir, DIR_SEPARATOR_STRING, DEVICE_FILE_NAME);
233           pic_file = fopen( filename, "rt" );
234           if (pic_file) break;
235         } // for
236         for (dir = setFirstItem(userIncDirsSet);
237                 !pic_file && dir;
238                 dir = setNextItem(userIncDirsSet))
239         {
240           //fprintf( stderr, "searching2 %s\n", dir );
241           SNPRINTF(&filename[0], len, "%s%s%s", dir, DIR_SEPARATOR_STRING, DEVICE_FILE_NAME);
242           pic_file = fopen( filename, "rt" );
243           if (pic_file) break;
244         } // for
245         for (dir = setFirstItem(libDirsSet);
246                 !pic_file && dir;
247                 dir = setNextItem(libDirsSet))
248         {
249           //fprintf( stderr, "searching3 %s\n", dir );
250           SNPRINTF(&filename[0], len, "%s%s%s", dir, DIR_SEPARATOR_STRING, DEVICE_FILE_NAME);
251           pic_file = fopen( filename, "rt" );
252           if (pic_file) break;
253         } // for
254         for (dir = setFirstItem(libPathsSet);
255                 !pic_file && dir;
256                 dir = setNextItem(libPathsSet))
257         {
258           //fprintf( stderr, "searching4 %s\n", dir );
259           SNPRINTF(&filename[0], len, "%s%s%s", dir, DIR_SEPARATOR_STRING, DEVICE_FILE_NAME);
260           pic_file = fopen( filename, "rt" );
261           if (pic_file) break;
262         } // for
263         if (!pic_file) {
264           pic_file = fopen(DATADIR LIB_DIR_SUFFIX DIR_SEPARATOR_STRING "pic" DIR_SEPARATOR_STRING DEVICE_FILE_NAME, "rt");
265         }
266         if (pic_file == NULL) {
267                 /* this second attempt is used when initially building the libraries */
268                 pic_file = fopen(".." DIR_SEPARATOR_STRING ".." DIR_SEPARATOR_STRING ".." DIR_SEPARATOR_STRING ".." 
269                                 DIR_SEPARATOR_STRING "src" DIR_SEPARATOR_STRING "pic" DIR_SEPARATOR_STRING 
270                                 DEVICE_FILE_NAME, "rt");
271                 if (pic_file == NULL) {
272                         fprintf(stderr, "can't find %s\n", DATADIR LIB_DIR_SUFFIX DIR_SEPARATOR_STRING "pic" 
273                                         DIR_SEPARATOR_STRING DEVICE_FILE_NAME);
274                         return NULL;
275                 }
276         }
277         
278         /* read line by line */
279         pic_buf[sizeof(pic_buf)-1] = '\0';
280         while (fgets(pic_buf, sizeof(pic_buf)-1, pic_file) != NULL && !done) {
281                 unsigned llen;
282                 llen = strlen (pic_buf);
283                 
284                 /* remove trailing spaces */
285                 while (llen && isspace(pic_buf[llen-1])) {
286                         pic_buf[llen-1] = '\0';
287                         llen--;
288                 }
289                 
290                 /* remove leading spaces */
291                 for (pic_buf_pos = pic_buf; isspace(*pic_buf_pos); pic_buf_pos++)
292                 {}
293                 
294                 /* ignore comment / empty lines */
295                 if (*pic_buf_pos != '\0' && *pic_buf_pos != '#') {
296                         
297                         /* split into fields */
298                         char pic_word[SPLIT_WORDS_MAX][PIC14_STRING_LEN];
299                         int num_pic_words;
300                         int wcount;
301                         
302                         num_pic_words = split_words(pic_word, pic_buf_pos);
303                         
304                         if (STRCASECMP(pic_word[0], "processor") == 0) {
305                         
306                                 if (pic_name == NULL) {
307                                         /* this is the mode where we read all the processors in - store the names for now */
308                                         if (num_processor_names > 0) {
309                                                 /* store away all the previous processor definitions */
310                                                 int dcount;
311                                                 
312                                                 for (dcount = 1; dcount < num_processor_names; dcount++)
313                                                         create_pic(processor_name[dcount], pic_maxram, pic_bankmsk,
314                                                                    pic_confsiz, pic_program, pic_data, pic_eeprom, pic_io);
315                                         }
316                                         
317                                         num_processor_names = split_words(processor_name, pic_buf_pos);
318                                 }
319                                 else {
320                                         /* if we've just completed reading a processor definition stop now */
321                                         if (found_processor)
322                                                 done = TRUE;
323                                         else {
324                                                 /* check if this processor name is a match */
325                                                 for (wcount = 1; wcount < num_pic_words; wcount++) {
326                                                         
327                                                         /* skip uninteresting prefixes */
328                                                         char *found_name = sanitise_processor_name(pic_word[wcount]);
329
330                                                         if (STRCASECMP(found_name, simple_pic_name) == 0)
331                                                                 found_processor = TRUE;
332                                                 }
333                                         }
334                                 }
335                         }
336                         
337                         else {
338                                 if (found_processor || pic_name == NULL) {
339                                         /* only parse a processor section if we've found the one we want */
340                                         if (STRCASECMP(pic_word[0], "maxram") == 0 && num_pic_words > 1) {
341                                                 pic_maxram = parse_config_value(pic_word[1]);
342                                                 setMaxRAM(pic_maxram);
343                                         }
344                                         else if (STRCASECMP(pic_word[0], "bankmsk") == 0 && num_pic_words > 1)
345                                                 pic_bankmsk = parse_config_value(pic_word[1]);
346                         
347                                         else if (STRCASECMP(pic_word[0], "confsiz") == 0 && num_pic_words > 1)
348                                                 pic_confsiz = parse_config_value(pic_word[1]);
349                         
350                                         else if (STRCASECMP(pic_word[0], "program") == 0 && num_pic_words > 1)
351                                                 pic_program = parse_config_value(pic_word[1]);
352                         
353                                         else if (STRCASECMP(pic_word[0], "data") == 0 && num_pic_words > 1)
354                                                 pic_data = parse_config_value(pic_word[1]);
355                         
356                                         else if (STRCASECMP(pic_word[0], "eeprom") == 0 && num_pic_words > 1)
357                                                 pic_eeprom = parse_config_value(pic_word[1]);
358                         
359                                         else if (STRCASECMP(pic_word[0], "io") == 0 && num_pic_words > 1)
360                                                 pic_io = parse_config_value(pic_word[1]);
361                         
362                                         else if (STRCASECMP(pic_word[0], "regmap") == 0 && num_pic_words > 2) {
363                                                 if (found_processor)
364                                                         register_map(num_pic_words, pic_word);
365                                         }
366                                         else if (STRCASECMP(pic_word[0], "memmap") == 0 && num_pic_words > 2) {
367                                                 if (found_processor)
368                                                         ram_map(num_pic_words, pic_word);
369                                         }
370                                         else {
371                                                 fprintf(stderr, "WARNING: %s: bad syntax `%s'\n", DEVICE_FILE_NAME, pic_word[0]);
372                                         }
373                                 }
374                         }
375                 }
376         }
377         
378         fclose(pic_file);
379
380         /* if we're in read-the-lot mode then create the final processor definition */
381         if (pic_name == NULL) {
382             
383                 if (num_processor_names > 0) {
384                         /* store away all the previous processor definitions */
385                         int dcount;
386                 
387                         for (dcount = 1; dcount < num_processor_names; dcount++)
388                                 create_pic(processor_name[dcount], pic_maxram, pic_bankmsk,
389                                            pic_confsiz, pic_program, pic_data, pic_eeprom, pic_io);
390                 }
391         }
392         else {
393                 /* in search mode */
394                 if (found_processor) {
395                         /* create a new pic entry */
396                         return create_pic(pic_name, pic_maxram, pic_bankmsk,
397                                           pic_confsiz, pic_program, pic_data, pic_eeprom, pic_io);
398                 }
399         }
400         
401         return NULL;
402 }
403
404 void setMaxRAM(int size)
405 {
406         maxRAMaddress = size;
407         
408         if (maxRAMaddress < 0) {
409                 fprintf(stderr, "invalid maxram 0x%x setting in %s\n",
410                         maxRAMaddress, DEVICE_FILE_NAME);
411                 return;
412         }
413 }
414
415 /*-----------------------------------------------------------------*
416 *-----------------------------------------------------------------*/
417
418 int isREGinBank(regs *reg, int bank)
419 {
420         
421         if(!reg || !pic)
422                 return 0;
423         
424         if((int)((reg->address | reg->alias) & pic->bankMask & bank) == bank)
425                 return 1;
426         
427         return 0;
428 }
429
430 /*-----------------------------------------------------------------*
431 *-----------------------------------------------------------------*/
432 int REGallBanks(regs *reg)
433 {
434         
435         if(!reg || !pic)
436                 return 0;
437         
438         return ((reg->address | reg->alias) & pic->bankMask);
439         
440 }
441
442 /*-----------------------------------------------------------------*
443  *  void list_valid_pics(int ncols, int list_alias)
444  *
445  * Print out a formatted list of valid PIC devices
446  *
447  * ncols - number of columns in the list.
448  *
449  * list_alias - if non-zero, print all of the supported aliases
450  *              for a device (e.g. F84, 16F84, etc...)
451  *-----------------------------------------------------------------*/
452 void list_valid_pics(int ncols)
453 {
454         int col=0,longest;
455         int i,k,l;
456         
457         if (num_of_supported_PICS == 0)
458                 find_device(NULL);          /* load all the definitions */
459         
460         /* decrement the column number if it's greater than zero */
461         ncols = (ncols > 1) ? ncols-1 : 4;
462         
463         /* Find the device with the longest name */
464         for(i=0,longest=0; i<num_of_supported_PICS; i++) {
465                 k = strlen(Pics[i]->name);
466                 if(k>longest)
467                         longest = k;
468         }
469         
470 #if 1
471         /* heading */
472         fprintf(stderr, "\nPIC14 processors and their characteristics:\n\n");
473         fprintf(stderr, " processor");
474         for(k=0; k<longest-1; k++)
475                 fputc(' ',stderr);
476         fprintf(stderr, "program     RAM      EEPROM    I/O\n");
477         fprintf(stderr, "-----------------------------------------------------\n");
478         
479         for(i=0;  i < num_of_supported_PICS; i++) {
480                 fprintf(stderr,"  %s", Pics[i]->name);
481                 l = longest + 2 - strlen(Pics[i]->name);
482                 for(k=0; k<l; k++)
483                         fputc(' ',stderr);
484         
485                 fprintf(stderr, "     ");
486                 if (Pics[i]->programMemSize % 1024 == 0)
487                         fprintf(stderr, "%4dK", Pics[i]->programMemSize / 1024);
488                 else
489                         fprintf(stderr, "%5d", Pics[i]->programMemSize);
490         
491                 fprintf(stderr, "     %5d     %5d     %4d\n", 
492                         Pics[i]->dataMemSize, Pics[i]->eepromMemSize, Pics[i]->ioPins);
493         }
494
495         col = 0;
496         
497         fprintf(stderr, "\nPIC14 processors supported:\n");
498         for(i=0;  i < num_of_supported_PICS; i++) {
499                         
500                 fprintf(stderr,"%s", Pics[i]->name);
501                 if(col<ncols) {
502                         l = longest + 2 - strlen(Pics[i]->name);
503                         for(k=0; k<l; k++)
504                                 fputc(' ',stderr);
505                                 
506                         col++;
507                                 
508                 } else {
509                         fputc('\n',stderr);
510                         col = 0;
511                 }
512                 
513         }
514 #endif
515         if(col != 0)
516                 fputc('\n',stderr);
517 }
518
519 /*-----------------------------------------------------------------*
520 *  
521 *-----------------------------------------------------------------*/
522 PIC_device *init_pic(char *pic_type)
523 {
524         char long_name[PIC14_STRING_LEN];
525         
526         pic = find_device(pic_type);
527         
528         if (pic == NULL) {
529                 /* check for shortened "16xxx" form */
530                 sprintf(long_name, "16%s", pic_type);
531                 pic = find_device(long_name);
532                 if (pic == NULL) {
533                         if(pic_type != NULL && pic_type[0] != '\0')
534                                 fprintf(stderr, "'%s' was not found.\n", pic_type);
535                         else
536                                 fprintf(stderr, "No processor has been specified (use -pPROCESSOR_NAME)\n");
537                 
538                         list_valid_pics(7);
539                         exit(1);
540                 }
541         }
542         return pic;
543 }
544
545 /*-----------------------------------------------------------------*
546 *  
547 *-----------------------------------------------------------------*/
548 int picIsInitialized(void)
549 {
550         if(pic && maxRAMaddress > 0)
551                 return 1;
552         
553         return 0;
554         
555 }
556
557 /*-----------------------------------------------------------------*
558 *  char *processor_base_name(void) - Include file is derived from this.
559 *-----------------------------------------------------------------*/
560 char *processor_base_name(void)
561 {
562         
563         if(!pic)
564                 return NULL;
565         
566         return pic->name;
567 }
568
569 /*-----------------------------------------------------------------*
570 *-----------------------------------------------------------------*/
571 int validAddress(int address, int reg_size)
572 {
573         if (maxRAMaddress < 0) {
574                 fprintf(stderr, "missing maxram setting in %s\n", DEVICE_FILE_NAME);
575                 return 0;
576         }
577         //  fprintf(stderr, "validAddress: Checking 0x%04x\n",address);
578         assert (reg_size > 0);
579         if(address + (reg_size - 1) > maxRAMaddress)
580                 return 0;
581         
582         return 1;
583 }
584
585 #if 0
586 /* The following code should be (and is) implemented in the linker. */
587
588 /*-----------------------------------------------------------------*
589 *-----------------------------------------------------------------*/
590 void mapRegister(regs *reg)
591 {
592         
593         unsigned i;
594         int alias;
595         
596         if(!reg || !reg->size) {
597                 fprintf(stderr,"WARNING: %s:%s:%d Bad register\n",__FILE__,__FUNCTION__,__LINE__);
598                 return;
599         }
600         
601         if (maxRAMaddress < 0) {
602                 fprintf(stderr, "missing maxram setting in %s\n", DEVICE_FILE_NAME);
603                 return;
604         }
605         
606         for(i=0; i<reg->size; i++) {
607                 
608                 assert(reg->address >= 0 && reg->address < maxRAMaddress);
609                 
610                 alias = finalMapping[reg->address].alias;
611                 reg->alias = alias;
612                 
613                 do {
614                         
615                         //fprintf(stdout,"mapping %s to address 0x%02x, reg size = %d\n",reg->name, (reg->address+alias+i),reg->size);
616                         
617                         finalMapping[reg->address + alias + i].reg = reg;
618                         finalMapping[reg->address + alias + i].instance = i;
619                         
620                         /* Decrement alias */
621                         if(alias)
622                                 alias -= ((alias & (alias - 1)) ^ alias);
623                         else
624                                 alias--;
625                         
626                 } while (alias>=0);
627         }
628         
629         //fprintf(stderr,"%s - %s addr = 0x%03x, size %d\n",__FUNCTION__,reg->name, reg->address,reg->size);
630         
631         reg->isMapped = 1;
632         
633 }
634
635 /*-----------------------------------------------------------------*
636 *-----------------------------------------------------------------*/
637 int assignRegister(regs *reg, int start_address)
638 {
639         int i;
640         
641         //fprintf(stderr,"%s -  %s start_address = 0x%03x\n",__FUNCTION__,reg->name, start_address);
642         if(reg->isFixed) {
643                 
644                 if (validAddress(reg->address,reg->size)) {
645                         //fprintf(stderr,"%s -  %s address = 0x%03x\n",__FUNCTION__,reg->name, reg->address);
646                         mapRegister(reg);
647                         return reg->address;
648                 }
649                 
650                 if (getenv("SDCCPICDEBUG")) {
651                         fprintf(stderr, "WARNING: Ignoring Out of Range register assignment at fixed address %d, %s\n",
652                             reg->address, reg->name);
653                 }
654                 
655         } else {
656                 
657         /* This register does not have a fixed address requirement
658         * so we'll search through all availble ram address and
659                 * assign the first one */
660                 
661                 for (i=start_address; i<=maxRAMaddress; i++) {
662                         
663                         if (validAddress(i,reg->size)) {
664                                 reg->address = i;
665                                 mapRegister(reg);
666                                 return i;
667                         }
668                 }
669                 
670                 fprintf(stderr, "WARNING: No more RAM available for %s\n",reg->name);
671                 
672         }
673         
674         return -1;
675 }
676
677 /*-----------------------------------------------------------------*
678 *-----------------------------------------------------------------*/
679 void assignFixedRegisters(set *regset)
680 {
681         regs *reg;
682         
683         for (reg = setFirstItem(regset) ; reg ; 
684         reg = setNextItem(regset)) {
685                 
686                 if(reg->isFixed) 
687                         assignRegister(reg,0);
688         }
689         
690 }
691
692 /*-----------------------------------------------------------------*
693 *-----------------------------------------------------------------*/
694 void assignRelocatableRegisters(set *regset, int used)
695 {
696         
697         regs *reg;
698         int address = 0;
699         
700         for (reg = setFirstItem(regset) ; reg ; 
701         reg = setNextItem(regset)) {
702                 
703                 //fprintf(stdout,"assigning %s (%d) isFixed=%d, wasUsed=%d\n",reg->name,reg->size,reg->isFixed,reg->wasUsed);
704                 
705                 if((!reg->isExtern) && (!reg->isFixed) && ( used || reg->wasUsed)) {
706                         /* If register have been reused then shall not print it a second time. */
707                         set *s;
708                         int done = 0;
709                         for (s = regset; s; s = s->next) {
710                                 regs *r;
711                                 r = s->item;
712                                 if (r == reg)
713                                         break;
714                                 if((!r->isFixed) && ( used || r->wasUsed)) {
715                                         if (r->rIdx == reg->rIdx) {
716                                                 reg->address = r->address;
717                                                 done = 1;
718                                                 break;
719                                         }
720                                 }
721                         }
722                         if (!done)
723                                 address = assignRegister(reg,address);
724                 }
725         }
726         
727 }
728 #endif
729
730 /* Keep track of whether we found an assignment to the __config words. */
731 static int pic14_hasSetConfigWord = 0;
732
733 /*-----------------------------------------------------------------*
734  *  void assignConfigWordValue(int address, int value)
735  *
736  * Most midrange PICs have one config word at address 0x2007.
737  * Newer PIC14s have a second config word at address 0x2008.
738  * This routine will assign values to those addresses.
739  *
740  *-----------------------------------------------------------------*/
741
742 void pic14_assignConfigWordValue(int address, int value)
743 {
744         if (CONFIG_WORD_ADDRESS == address)
745                 config_word = value;
746         
747         else if (CONFIG2_WORD_ADDRESS == address)
748                 config2_word = value;
749         
750         //fprintf(stderr,"setting config word 0x%x to 0x%x\n", address, value);
751         pic14_hasSetConfigWord = 1;
752 }
753
754 /*-----------------------------------------------------------------*
755  * int pic14_emitConfigWord (FILE * vFile)
756  * 
757  * Emit the __config directives iff we found a previous assignment
758  * to the config word.
759  *-----------------------------------------------------------------*/
760 extern char *iComments2;
761 int pic14_emitConfigWord (FILE * vFile)
762 {
763   if (pic14_hasSetConfigWord)
764   {
765     fprintf (vFile, "%s", iComments2);
766     fprintf (vFile, "; config word \n");
767     fprintf (vFile, "%s", iComments2);
768     if (pic14_getHasSecondConfigReg())
769     {
770       fprintf (vFile, "\t__config _CONFIG1, 0x%x\n", pic14_getConfigWord(0x2007));
771       fprintf (vFile, "\t__config _CONFIG2, 0x%x\n", pic14_getConfigWord(0x2008));
772     }
773     else
774       fprintf (vFile, "\t__config 0x%x\n", pic14_getConfigWord(0x2007));
775
776     return 1;
777   }
778   return 0;
779 }
780
781 /*-----------------------------------------------------------------*
782  * int pic14_getConfigWord(int address)
783  *
784  * Get the current value of a config word.
785  *
786  *-----------------------------------------------------------------*/
787
788 int pic14_getConfigWord(int address)
789 {
790         switch (address)
791         {
792         case CONFIG_WORD_ADDRESS:
793                 return config_word;
794         
795         case CONFIG2_WORD_ADDRESS:
796                 return config2_word;
797         
798         default:
799                 return 0;
800         }
801 }
802
803 /*-----------------------------------------------------------------*
804 *  
805 *-----------------------------------------------------------------*/
806 unsigned pic14_getMaxRam(void)
807 {
808         return pic->defMaxRAMaddrs;
809 }
810
811
812 /*-----------------------------------------------------------------*
813 *  int getHasSecondConfigReg(void) - check if the device has a 
814 *  second config register, rather than just one.
815 *-----------------------------------------------------------------*/
816 int pic14_getHasSecondConfigReg(void)
817 {
818         if(!pic)
819                 return 0;
820         else
821                 return pic->hasSecondConfigReg;
822 }
823
824 /*-----------------------------------------------------------------*
825  * True iff the device has memory aliased in every bank.
826  * If true, low and high will be set to the low and high address
827  * occupied by the (last) sharebank found.
828  *-----------------------------------------------------------------*/
829 int pic14_hasSharebank(int *low, int *high, int *size)
830 {
831         memRange *r;
832
833         assert(pic);
834         r = pic->ram;
835
836         while (r) {
837             //fprintf (stderr, "%s: region %x..%x, bank %x, alias %x, pic->bankmask %x, min_size %d\n",  __FUNCTION__, r->start_address, r->end_address, r->bank, r->alias, pic->bankMask, size ? *size : 0);
838             // find sufficiently large shared region
839             if ((r->alias == pic->bankMask)
840                     && (r->end_address != r->start_address) // ignore SFRs
841                     && (!size || (*size <= (r->end_address - r->start_address + 1))))
842             {
843                 if (low) *low = r->start_address;
844                 if (high) *high = r->end_address;
845                 if (size) *size = r->end_address - r->start_address + 1;
846                 return 1;
847             } // if
848             r = r->next;
849         } // while
850
851         if (low) *low = 0x0;
852         if (high) *high = 0x0;
853         if (size) *size = 0x0;
854         //fprintf (stderr, "%s: no shared bank found\n", __FUNCTION__);
855         return 0;
856 }
857
858 /*
859  * True iff the memory region [low, high] is aliased in all banks.
860  */
861 int pic14_isShared(int low, int high)
862 {
863         memRange *r;
864
865         assert(pic);
866         r = pic->ram;
867
868         while (r) {
869             //fprintf (stderr, "%s: region %x..%x, bank %x, alias %x, pic->bankmask %x\n", __FUNCTION__, r->start_address, r->end_address, r->bank, r->alias, pic->bankMask);
870             if ((r->alias == pic->bankMask) && (r->start_address <= low) && (r->end_address >= high)) {
871                 return 1;
872             } // if
873             r = r->next;
874         } // while
875
876         return 0;
877 }
878
879 /*
880  * True iff all RAM is aliased in all banks (no BANKSELs required except for
881  * SFRs).
882  */
883 int pic14_allRAMShared(void)
884 {
885         memRange *r;
886
887         assert(pic);
888         r = pic->ram;
889
890         while (r) {
891             if (r->alias != pic->bankMask) return 0;
892             r = r->next;
893         } // while
894         
895         return 1;
896 }
897
898 /*
899  * True iff the pseudo stack is a sharebank --> let linker place it.
900  * [low, high] denotes a size byte long block of (shared or banked)
901  * memory to be used.
902  */
903 int pic14_getSharedStack(int *low, int *high, int *size)
904 {
905     int haveShared;
906     int l, h, s;
907
908     s = options.stack_size ? options.stack_size : 0x10;
909     haveShared = pic14_hasSharebank(&l, &h, &s);
910     if ((options.stack_loc != 0) || !haveShared)
911     {
912         // sharebank not available or not to be used
913         s = options.stack_size ? options.stack_size : 0x10;
914         l = options.stack_loc ? options.stack_loc : 0x20;
915         h = l + s - 1;
916         if (low) *low = l;
917         if (high) *high = h;
918         if (size) *size = s;
919         // return 1 iff [low, high] is present in all banks
920         //fprintf(stderr, "%s: low %x, high %x, size %x, shared %d\n", __FUNCTION__, l, h, s, pic14_isShared(l, h));
921         return (pic14_isShared(l, h));
922     } else {
923         // sharebanks available for use by the stack
924         if (options.stack_size) s = options.stack_size;
925         else if (!s || s > 16) s = 16; // limit stack to 16 bytes in SHAREBANK
926
927         // provide addresses for sharebank
928         if (low) *low = l;
929         if (high) *high = l + s - 1;
930         if (size) *size = s;
931         //fprintf(stderr, "%s: low %x, high %x, size %x, shared 1\n", __FUNCTION__, l, h, s);
932         return 1;
933     }
934 }
935
936 PIC_device * pic14_getPIC(void)
937 {
938     return pic;
939 }