Fix FS#12824 : Malfunctioning FFT plugin in Sansa Clip Zip
[maemo-rb.git] / firmware / load_code.c
blobd22d6bb3b2a20c6ae798e90c97a60959f8418200
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2010 by Thomas Martitz
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
22 #include "config.h"
23 #include "system.h"
24 #include "file.h"
25 #include "debug.h"
26 #include "load_code.h"
28 /* load binary blob from disk to memory, returning a handle */
29 void * lc_open(const char *filename, unsigned char *buf, size_t buf_size)
31 int fd = open(filename, O_RDONLY);
32 ssize_t read_size;
33 struct lc_header hdr;
34 unsigned char *buf_end = buf+buf_size;
35 off_t copy_size;
37 if (fd < 0)
39 DEBUGF("Could not open file");
40 goto error;
43 #if NUM_CORES > 1
44 /* Make sure COP cache is flushed and invalidated before loading */
46 int my_core = switch_core(CURRENT_CORE ^ 1);
47 switch_core(my_core);
49 #endif
51 /* read the header to obtain the load address */
52 read_size = read(fd, &hdr, sizeof(hdr));
54 if (read_size < 0)
56 DEBUGF("Could not read from file");
57 goto error_fd;
60 /* hdr.end_addr points to the end of the bss section,
61 * but there might be idata/icode behind that so the bytes to copy
62 * can be larger */
63 copy_size = MAX(filesize(fd), hdr.end_addr - hdr.load_addr);
65 if (hdr.load_addr < buf || (hdr.load_addr+copy_size) > buf_end)
67 DEBUGF("Binary doesn't fit into memory");
68 goto error_fd;
71 /* go back to beginning to load the whole thing (incl. header) */
72 if (lseek(fd, 0, SEEK_SET) < 0)
74 DEBUGF("lseek failed");
75 goto error_fd;
78 /* the header has the addresses where the code is linked at */
79 read_size = read(fd, hdr.load_addr, copy_size);
80 close(fd);
82 if (read_size < 0)
84 DEBUGF("Could not read from file");
85 goto error;
88 /* commit dcache and discard icache */
89 commit_discard_idcache();
90 /* return a pointer the header, reused by lc_get_header() */
91 return hdr.load_addr;
93 error_fd:
94 close(fd);
95 error:
96 return NULL;