]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/tool/mbed/mbed-sdk/libraries/mbed/common/retarget.cpp
Merge commit '1fe4406f374291ab2e86e95a97341fd9c475fcb8'
[qmk_firmware.git] / tmk_core / tool / mbed / mbed-sdk / libraries / mbed / common / retarget.cpp
1 /* mbed Microcontroller Library
2  * Copyright (c) 2006-2015 ARM Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include "platform.h"
17 #include "FileHandle.h"
18 #include "FileSystemLike.h"
19 #include "FilePath.h"
20 #include "serial_api.h"
21 #include "toolchain.h"
22 #include "semihost_api.h"
23 #include "mbed_interface.h"
24 #if DEVICE_STDIO_MESSAGES
25 #include <stdio.h>
26 #endif
27 #include <errno.h>
28
29 #if defined(__ARMCC_VERSION)
30 #   include <rt_sys.h>
31 #   define PREFIX(x)    _sys##x
32 #   define OPEN_MAX     _SYS_OPEN
33 #   ifdef __MICROLIB
34 #       pragma import(__use_full_stdio)
35 #   endif
36
37 #elif defined(__ICCARM__)
38 #   include <yfuns.h>
39 #   define PREFIX(x)        _##x
40 #   define OPEN_MAX         16
41
42 #   define STDIN_FILENO     0
43 #   define STDOUT_FILENO    1
44 #   define STDERR_FILENO    2
45
46 #else
47 #   include <sys/stat.h>
48 #   include <sys/unistd.h>
49 #   include <sys/syslimits.h>
50 #   define PREFIX(x)    x
51 #endif
52
53 using namespace mbed;
54
55 #if defined(__MICROLIB) && (__ARMCC_VERSION>5030000)
56 // Before version 5.03, we were using a patched version of microlib with proper names
57 extern const char __stdin_name[]  = ":tt";
58 extern const char __stdout_name[] = ":tt";
59 extern const char __stderr_name[] = ":tt";
60
61 #else
62 extern const char __stdin_name[]  = "/stdin";
63 extern const char __stdout_name[] = "/stdout";
64 extern const char __stderr_name[] = "/stderr";
65 #endif
66
67 /* newlib has the filehandle field in the FILE struct as a short, so
68  * we can't just return a Filehandle* from _open and instead have to
69  * put it in a filehandles array and return the index into that array
70  * (or rather index+3, as filehandles 0-2 are stdin/out/err).
71  */
72 static FileHandle *filehandles[OPEN_MAX];
73
74 FileHandle::~FileHandle() {
75     /* Remove all open filehandles for this */
76     for (unsigned int fh_i = 0; fh_i < sizeof(filehandles)/sizeof(*filehandles); fh_i++) {
77         if (filehandles[fh_i] == this) {
78             filehandles[fh_i] = NULL;
79         }
80     }
81 }
82
83 #if DEVICE_SERIAL
84 extern int stdio_uart_inited;
85 extern serial_t stdio_uart;
86 #endif
87
88 static void init_serial() {
89 #if DEVICE_SERIAL
90     if (stdio_uart_inited) return;
91     serial_init(&stdio_uart, STDIO_UART_TX, STDIO_UART_RX);
92 #endif
93 }
94
95 static inline int openmode_to_posix(int openmode) {
96     int posix = openmode;
97 #ifdef __ARMCC_VERSION
98     if (openmode & OPEN_PLUS) {
99         posix = O_RDWR;
100     } else if(openmode & OPEN_W) {
101         posix = O_WRONLY;
102     } else if(openmode & OPEN_A) {
103         posix = O_WRONLY|O_APPEND;
104     } else {
105         posix = O_RDONLY;
106     }
107     /* a, w, a+, w+ all create if file does not already exist */
108     if (openmode & (OPEN_A|OPEN_W)) {
109         posix |= O_CREAT;
110     }
111     /* w and w+ truncate */
112     if (openmode & OPEN_W) {
113         posix |= O_TRUNC;
114     }
115 #elif defined(__ICCARM__)
116     switch (openmode & _LLIO_RDWRMASK) {
117         case _LLIO_RDONLY: posix = O_RDONLY; break;
118         case _LLIO_WRONLY: posix = O_WRONLY; break;
119         case _LLIO_RDWR  : posix = O_RDWR  ; break;
120     }
121     if (openmode & _LLIO_CREAT ) posix |= O_CREAT;
122     if (openmode & _LLIO_APPEND) posix |= O_APPEND;
123     if (openmode & _LLIO_TRUNC ) posix |= O_TRUNC;
124 #endif
125     return posix;
126 }
127
128 extern "C" FILEHANDLE PREFIX(_open)(const char* name, int openmode) {
129     #if defined(__MICROLIB) && (__ARMCC_VERSION>5030000)
130     // Before version 5.03, we were using a patched version of microlib with proper names
131     // This is the workaround that the microlib author suggested us
132     static int n = 0;
133     if (!std::strcmp(name, ":tt")) return n++;
134
135     #else
136     /* Use the posix convention that stdin,out,err are filehandles 0,1,2.
137      */
138     if (std::strcmp(name, __stdin_name) == 0) {
139         init_serial();
140         return 0;
141     } else if (std::strcmp(name, __stdout_name) == 0) {
142         init_serial();
143         return 1;
144     } else if (std::strcmp(name, __stderr_name) == 0) {
145         init_serial();
146         return 2;
147     }
148     #endif
149
150     // find the first empty slot in filehandles
151     unsigned int fh_i;
152     for (fh_i = 0; fh_i < sizeof(filehandles)/sizeof(*filehandles); fh_i++) {
153         if (filehandles[fh_i] == NULL) break;
154     }
155     if (fh_i >= sizeof(filehandles)/sizeof(*filehandles)) {
156         return -1;
157     }
158
159     FileHandle *res;
160
161     /* FILENAME: ":0x12345678" describes a FileLike* */
162     if (name[0] == ':') {
163         void *p;
164         sscanf(name, ":%p", &p);
165         res = (FileHandle*)p;
166
167     /* FILENAME: "/file_system/file_name" */
168     } else {
169         FilePath path(name);
170
171         if (!path.exists())
172             return -1;
173         else if (path.isFile()) {
174             res = path.file();
175         } else {
176             FileSystemLike *fs = path.fileSystem();
177             if (fs == NULL) return -1;
178             int posix_mode = openmode_to_posix(openmode);
179             res = fs->open(path.fileName(), posix_mode); /* NULL if fails */
180         }
181     }
182
183     if (res == NULL) return -1;
184     filehandles[fh_i] = res;
185
186     return fh_i + 3; // +3 as filehandles 0-2 are stdin/out/err
187 }
188
189 extern "C" int PREFIX(_close)(FILEHANDLE fh) {
190     if (fh < 3) return 0;
191
192     FileHandle* fhc = filehandles[fh-3];
193     filehandles[fh-3] = NULL;
194     if (fhc == NULL) return -1;
195
196     return fhc->close();
197 }
198
199 #if defined(__ICCARM__)
200 extern "C" size_t    __write (int        fh, const unsigned char *buffer, size_t length) {
201 #else
202 extern "C" int PREFIX(_write)(FILEHANDLE fh, const unsigned char *buffer, unsigned int length, int mode) {
203 #endif
204     int n; // n is the number of bytes written
205     if (fh < 3) {
206 #if DEVICE_SERIAL
207         if (!stdio_uart_inited) init_serial();
208         for (unsigned int i = 0; i < length; i++) {
209             serial_putc(&stdio_uart, buffer[i]);
210         }
211 #endif
212         n = length;
213     } else {
214         FileHandle* fhc = filehandles[fh-3];
215         if (fhc == NULL) return -1;
216
217         n = fhc->write(buffer, length);
218     }
219 #ifdef __ARMCC_VERSION
220     return length-n;
221 #else
222     return n;
223 #endif
224 }
225
226 #if defined(__ICCARM__)
227 extern "C" size_t    __read (int        fh, unsigned char *buffer, size_t       length) {
228 #else
229 extern "C" int PREFIX(_read)(FILEHANDLE fh, unsigned char *buffer, unsigned int length, int mode) {
230 #endif
231     int n; // n is the number of bytes read
232     if (fh < 3) {
233         // only read a character at a time from stdin
234 #if DEVICE_SERIAL
235         if (!stdio_uart_inited) init_serial();
236         *buffer = serial_getc(&stdio_uart);
237 #endif
238         n = 1;
239     } else {
240         FileHandle* fhc = filehandles[fh-3];
241         if (fhc == NULL) return -1;
242
243         n = fhc->read(buffer, length);
244     }
245 #ifdef __ARMCC_VERSION
246     return length-n;
247 #else
248     return n;
249 #endif
250 }
251
252 #ifdef __ARMCC_VERSION
253 extern "C" int PREFIX(_istty)(FILEHANDLE fh)
254 #else
255 extern "C" int _isatty(FILEHANDLE fh)
256 #endif
257 {
258     /* stdin, stdout and stderr should be tty */
259     if (fh < 3) return 1;
260
261     FileHandle* fhc = filehandles[fh-3];
262     if (fhc == NULL) return -1;
263
264     return fhc->isatty();
265 }
266
267 extern "C"
268 #if defined(__ARMCC_VERSION)
269 int _sys_seek(FILEHANDLE fh, long position)
270 #elif defined(__ICCARM__)
271 long __lseek(int fh, long offset, int whence)
272 #else
273 int _lseek(FILEHANDLE fh, int offset, int whence)
274 #endif
275 {
276     if (fh < 3) return 0;
277
278     FileHandle* fhc = filehandles[fh-3];
279     if (fhc == NULL) return -1;
280
281 #if defined(__ARMCC_VERSION)
282     return fhc->lseek(position, SEEK_SET);
283 #else
284     return fhc->lseek(offset, whence);
285 #endif
286 }
287
288 #ifdef __ARMCC_VERSION
289 extern "C" int PREFIX(_ensure)(FILEHANDLE fh) {
290     if (fh < 3) return 0;
291
292     FileHandle* fhc = filehandles[fh-3];
293     if (fhc == NULL) return -1;
294
295     return fhc->fsync();
296 }
297
298 extern "C" long PREFIX(_flen)(FILEHANDLE fh) {
299     if (fh < 3) return 0;
300
301     FileHandle* fhc = filehandles[fh-3];
302     if (fhc == NULL) return -1;
303
304     return fhc->flen();
305 }
306 #endif
307
308
309 #if !defined(__ARMCC_VERSION) && !defined(__ICCARM__)
310 extern "C" int _fstat(int fd, struct stat *st) {
311     if ((STDOUT_FILENO == fd) || (STDERR_FILENO == fd) || (STDIN_FILENO == fd)) {
312         st->st_mode = S_IFCHR;
313         return  0;
314     }
315
316     errno = EBADF;
317     return -1;
318 }
319 #endif
320
321 namespace std {
322 extern "C" int remove(const char *path) {
323     FilePath fp(path);
324     FileSystemLike *fs = fp.fileSystem();
325     if (fs == NULL) return -1;
326
327     return fs->remove(fp.fileName());
328 }
329
330 extern "C" int rename(const char *oldname, const char *newname) {
331     FilePath fpOld(oldname);
332     FilePath fpNew(newname);
333     FileSystemLike *fsOld = fpOld.fileSystem();
334     FileSystemLike *fsNew = fpNew.fileSystem();
335
336     /* rename only if both files are on the same FS */
337     if (fsOld != fsNew || fsOld == NULL) return -1;
338
339     return fsOld->rename(fpOld.fileName(), fpNew.fileName());
340 }
341
342 extern "C" char *tmpnam(char *s) {
343     return NULL;
344 }
345
346 extern "C" FILE *tmpfile() {
347     return NULL;
348 }
349 } // namespace std
350
351 #ifdef __ARMCC_VERSION
352 extern "C" char *_sys_command_string(char *cmd, int len) {
353     return NULL;
354 }
355 #endif
356
357 extern "C" DIR *opendir(const char *path) {
358     /* root dir is FileSystemLike */
359     if (path[0] == '/' && path[1] == 0) {
360         return FileSystemLike::opendir();
361     }
362
363     FilePath fp(path);
364     FileSystemLike* fs = fp.fileSystem();
365     if (fs == NULL) return NULL;
366
367     return fs->opendir(fp.fileName());
368 }
369
370 extern "C" struct dirent *readdir(DIR *dir) {
371     return dir->readdir();
372 }
373
374 extern "C" int closedir(DIR *dir) {
375     return dir->closedir();
376 }
377
378 extern "C" void rewinddir(DIR *dir) {
379     dir->rewinddir();
380 }
381
382 extern "C" off_t telldir(DIR *dir) {
383     return dir->telldir();
384 }
385
386 extern "C" void seekdir(DIR *dir, off_t off) {
387     dir->seekdir(off);
388 }
389
390 extern "C" int mkdir(const char *path, mode_t mode) {
391     FilePath fp(path);
392     FileSystemLike *fs = fp.fileSystem();
393     if (fs == NULL) return -1;
394
395     return fs->mkdir(fp.fileName(), mode);
396 }
397
398 #if defined(TOOLCHAIN_GCC)
399 /* prevents the exception handling name demangling code getting pulled in */
400 #include "mbed_error.h"
401 namespace __gnu_cxx {
402     void __verbose_terminate_handler() {
403         error("Exception");
404     }
405 }
406 extern "C" WEAK void __cxa_pure_virtual(void);
407 extern "C" WEAK void __cxa_pure_virtual(void) {
408     exit(1);
409 }
410
411 #endif
412
413 // ****************************************************************************
414 // mbed_main is a function that is called before main()
415 // mbed_sdk_init() is also a function that is called before main(), but unlike
416 // mbed_main(), it is not meant for user code, but for the SDK itself to perform
417 // initializations before main() is called.
418
419 extern "C" WEAK void mbed_main(void);
420 extern "C" WEAK void mbed_main(void) {
421 }
422
423 extern "C" WEAK void mbed_sdk_init(void);
424 extern "C" WEAK void mbed_sdk_init(void) {
425 }
426
427 #if defined(TOOLCHAIN_ARM)
428 extern "C" int $Super$$main(void);
429
430 extern "C" int $Sub$$main(void) {
431     mbed_sdk_init();
432     mbed_main();
433     return $Super$$main();
434 }
435 #elif defined(TOOLCHAIN_GCC)
436 extern "C" int __real_main(void);
437
438 extern "C" int __wrap_main(void) {
439     mbed_sdk_init();
440     mbed_main();
441     return __real_main();
442 }
443 #elif defined(TOOLCHAIN_IAR)
444 // IAR doesn't have the $Super/$Sub mechanism of armcc, nor something equivalent
445 // to ld's --wrap. It does have a --redirect, but that doesn't help, since redirecting
446 // 'main' to another symbol looses the original 'main' symbol. However, its startup
447 // code will call a function to setup argc and argv (__iar_argc_argv) if it is defined.
448 // Since mbed doesn't use argc/argv, we use this function to call our mbed_main.
449 extern "C" void __iar_argc_argv() {
450     mbed_sdk_init();
451     mbed_main();
452 }
453 #endif
454
455 // Provide implementation of _sbrk (low-level dynamic memory allocation
456 // routine) for GCC_ARM which compares new heap pointer with MSP instead of
457 // SP.  This make it compatible with RTX RTOS thread stacks.
458 #if defined(TOOLCHAIN_GCC_ARM)
459 // Linker defined symbol used by _sbrk to indicate where heap should start.
460 extern "C" int __end__;
461
462 #if defined(TARGET_CORTEX_A)
463 extern "C" uint32_t  __HeapLimit;
464 #endif
465
466 // Turn off the errno macro and use actual global variable instead.
467 #undef errno
468 extern "C" int errno;
469
470 // For ARM7 only
471 register unsigned char * stack_ptr __asm ("sp");
472
473 // Dynamic memory allocation related syscall.
474 extern "C" caddr_t _sbrk(int incr) {
475     static unsigned char* heap = (unsigned char*)&__end__;
476     unsigned char*        prev_heap = heap;
477     unsigned char*        new_heap = heap + incr;
478
479 #if defined(TARGET_ARM7)
480     if (new_heap >= stack_ptr) {
481 #elif defined(TARGET_CORTEX_A)
482     if (new_heap >= (unsigned char*)&__HeapLimit) {     /* __HeapLimit is end of heap section */
483 #else
484     if (new_heap >= (unsigned char*)__get_MSP()) {
485 #endif
486         errno = ENOMEM;
487         return (caddr_t)-1;
488     }
489
490     heap = new_heap;
491     return (caddr_t) prev_heap;
492 }
493 #endif
494
495
496 #ifdef TOOLCHAIN_GCC_CW
497 // TODO: Ideally, we would like to define directly "_ExitProcess"
498 extern "C" void mbed_exit(int return_code) {
499 #elif defined TOOLCHAIN_GCC_ARM
500 extern "C" void _exit(int return_code) {
501 #else
502 namespace std {
503 extern "C" void exit(int return_code) {
504 #endif
505
506 #if DEVICE_STDIO_MESSAGES
507     fflush(stdout);
508     fflush(stderr);
509 #endif
510
511 #if DEVICE_SEMIHOST
512     if (mbed_interface_connected()) {
513         semihost_exit();
514     }
515 #endif
516     if (return_code) {
517         mbed_die();
518     }
519
520     while (1);
521 }
522
523 #if !defined(TOOLCHAIN_GCC_ARM) && !defined(TOOLCHAIN_GCC_CW)
524 } //namespace std
525 #endif
526
527
528 namespace mbed {
529
530 void mbed_set_unbuffered_stream(FILE *_file) {
531 #if defined (__ICCARM__)
532     char buf[2];
533     std::setvbuf(_file,buf,_IONBF,NULL);    
534 #else
535     setbuf(_file, NULL);
536 #endif
537 }
538
539 int mbed_getc(FILE *_file){
540 #if defined (__ICCARM__)
541     /*This is only valid for unbuffered streams*/
542     int res = std::fgetc(_file);
543     if (res>=0){
544         _file->_Mode = (unsigned short)(_file->_Mode & ~ 0x1000);/* Unset read mode */
545         _file->_Rend = _file->_Wend;
546         _file->_Next = _file->_Wend;
547     }    
548     return res;
549 #else    
550     return std::fgetc(_file);
551 #endif   
552 }
553
554 char* mbed_gets(char*s, int size, FILE *_file){
555 #if defined (__ICCARM__)
556     /*This is only valid for unbuffered streams*/
557     char *str = fgets(s,size,_file);
558     if (str!=NULL){
559         _file->_Mode = (unsigned short)(_file->_Mode & ~ 0x1000);/* Unset read mode */
560         _file->_Rend = _file->_Wend;
561         _file->_Next = _file->_Wend;
562     }
563     return str;
564 #else    
565     return std::fgets(s,size,_file);
566 #endif
567 }
568
569 } // namespace mbed