1 /* radare - LGPL - Copyright 2008-2017 - pancake */
2
3 #include "r_lib.h"
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include "../io_memory.h"
7
__check(RIO * io,const char * pathname,bool many)8 static bool __check(RIO *io, const char *pathname, bool many) {
9 return (!strncmp (pathname, "malloc://", 9)) || (!strncmp (pathname, "hex://", 6));
10 }
11
__open(RIO * io,const char * pathname,int rw,int mode)12 static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) {
13 if (__check (io, pathname, 0)) {
14 RIOMalloc *mal = R_NEW0 (RIOMalloc);
15 if (!mal) {
16 return NULL;
17 }
18 if (!strncmp (pathname, "hex://", 6)) {
19 mal->size = strlen (pathname);
20 mal->buf = calloc (1, mal->size + 1);
21 if (!mal->buf) {
22 free (mal);
23 return NULL;
24 }
25 mal->offset = 0;
26 mal->size = r_hex_str2bin (pathname + 6, mal->buf);
27 if ((int)mal->size < 1) {
28 R_FREE (mal->buf);
29 }
30 } else {
31 mal->size = r_num_math (NULL, pathname + 9);
32 if (((int)mal->size) <= 0) {
33 free (mal);
34 eprintf ("Cannot allocate (%s) 0 bytes\n", pathname + 9);
35 return NULL;
36 }
37 mal->offset = 0;
38 mal->buf = calloc (1, mal->size + 1);
39 }
40 if (mal->buf) {
41 return r_io_desc_new (io, &r_io_plugin_malloc, pathname, R_PERM_RW | rw, mode, mal);
42 }
43 eprintf ("Cannot allocate (%s) %d byte(s)\n", pathname + 9, mal->size);
44 free (mal);
45 }
46 return NULL;
47 }
48
49 RIOPlugin r_io_plugin_malloc = {
50 .name = "malloc",
51 .desc = "Memory allocation plugin",
52 .uris = "malloc://,hex://",
53 .license = "LGPL3",
54 .open = __open,
55 .close = io_memory_close,
56 .read = io_memory_read,
57 .check = __check,
58 .lseek = io_memory_lseek,
59 .write = io_memory_write,
60 .resize = io_memory_resize,
61 };
62
63 #ifndef R2_PLUGIN_INCORE
64 R_API RLibStruct radare_plugin = {
65 .type = R_LIB_TYPE_IO,
66 .data = &r_io_plugin_malloc,
67 .version = R2_VERSION
68 };
69 #endif
70