From 2f8b658a4d02a5be4ce5c87a05ccad54584bc51e Mon Sep 17 00:00:00 2001 From: Leo C Date: Thu, 12 Apr 2018 13:15:27 +0200 Subject: [PATCH] fat cp: mem alloc --- avr/cmd_fat.c | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/avr/cmd_fat.c b/avr/cmd_fat.c index 456447a..cad7cdc 100644 --- a/avr/cmd_fat.c +++ b/avr/cmd_fat.c @@ -523,8 +523,12 @@ char *path_basename(PATH_T *p) static uint8_t flags; -PATH_T *from; -PATH_T *to; +PATH_T from_static; +PATH_T to_static; +PATH_T *from = &from_static; +PATH_T *to = &to_static; +static uint8_t *blockbuf; +static int blockbuf_size; #define F_FLAG (1<<3) // overwrite existing file ignoring write protection #define I_FLAG (1<<1) // prompt before overwrite (overrides a previous -n option) @@ -557,15 +561,17 @@ void copy_file(FILINFO *fs, uint_fast8_t dne) //char *p; FRESULT fr; - int buf_size = get_freemem() / 512 * 512; - uint8_t * buf = (uint8_t *) malloc(buf_size); - if (buf == NULL) { - free(buf); - err(PSTR("cp: Out of Memory!\n")); - return; + if (blockbuf == NULL) { + blockbuf_size = get_freemem() / 512 * 512; + if (blockbuf_size != 0) + blockbuf = (uint8_t *) malloc(blockbuf_size); + if (blockbuf == NULL) { + err(PSTR("Not enough memory!\n")); + return; + } } -debug("==== copy_file(): dne: %u, buf_zize: %d\n", dne, buf_size); +debug("==== copy_file(): dne: %u, blockbuf_size: %d\n", dne, blockbuf_size); debug(" from:'%s' to:'%s'\n", from->p_path, to->p_path); @@ -600,9 +606,9 @@ debug(" from:'%s' to:'%s'\n", from->p_path, to->p_path); return; } - while ((fr = f_read(&from_fd, buf, buf_size, &rcount)) == FR_OK && + while ((fr = f_read(&from_fd, blockbuf, blockbuf_size, &rcount)) == FR_OK && rcount > 0) { - fr = f_write(&to_fd, buf, rcount, &wcount); + fr = f_write(&to_fd, blockbuf, rcount, &wcount); if (fr || wcount < rcount) { err(PSTR("%s: %S"), to->p_path, rctostr(fr)); break; @@ -617,6 +623,7 @@ debug(" from:'%s' to:'%s'\n", from->p_path, to->p_path); f_close(&from_fd); if ((fr = f_close(&to_fd)) != FR_OK) err(PSTR("%s: %S"), to->p_path, rctostr(fr)); + } #if 1 @@ -822,6 +829,7 @@ command_ret_t do_cp(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, if (argc < 2) return CMD_RET_USAGE; +#if 0 from = (PATH_T *) malloc(sizeof(PATH_T)); to = (PATH_T *) malloc(sizeof(PATH_T)); if (from == NULL || to == NULL) { @@ -829,6 +837,7 @@ command_ret_t do_cp(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, command_ret = CMD_RET_FAILURE; goto cleanup; } +#endif from->p_end = from->p_path; *from->p_path = '\0'; to->p_end = to->p_path; *to->p_path = '\0'; @@ -894,8 +903,9 @@ debug(" from:'%s' to:'%s'\n", from->p_path, to->p_path); } cleanup: - free(to); - free(from); + free(blockbuf); + blockbuf = NULL; + blockbuf_size = 0; return command_ret; } -- 2.39.2