• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Capstone Disassembly Engine */
2 /* By Nguyen Anh Quynh <aquynh@gmail.com>, 2013-2014 */
3 
4 #if defined(CAPSTONE_HAS_OSXKERNEL)
5 #include <libkern/libkern.h>
6 #else
7 #include <stdlib.h>
8 #endif
9 #include <string.h>
10 
11 #include "utils.h"
12 
13 // create a cache for fast id lookup
make_id2insn(insn_map * insns,unsigned int size)14 static unsigned short *make_id2insn(insn_map *insns, unsigned int size)
15 {
16 	// NOTE: assume that the max id is always put at the end of insns array
17 	unsigned short max_id = insns[size - 1].id;
18 	unsigned short i;
19 
20 	unsigned short *cache = (unsigned short *)cs_mem_malloc(sizeof(*cache) * (max_id + 1));
21 
22 	for (i = 1; i < size; i++)
23 		cache[insns[i].id] = i;
24 
25 	return cache;
26 }
27 
28 // look for @id in @insns, given its size in @max. first time call will update @cache.
29 // return 0 if not found
insn_find(insn_map * insns,unsigned int max,unsigned int id,unsigned short ** cache)30 unsigned short insn_find(insn_map *insns, unsigned int max, unsigned int id, unsigned short **cache)
31 {
32 	if (id > insns[max - 1].id)
33 		return 0;
34 
35 	if (*cache == NULL)
36 		*cache = make_id2insn(insns, max);
37 
38 	return (*cache)[id];
39 }
40 
name2id(name_map * map,int max,const char * name)41 int name2id(name_map* map, int max, const char *name)
42 {
43 	int i;
44 
45 	for (i = 0; i < max; i++) {
46 		if (!strcmp(map[i].name, name)) {
47 			return map[i].id;
48 		}
49 	}
50 
51 	// nothing match
52 	return -1;
53 }
54 
55 // count number of positive members in a list.
56 // NOTE: list must be guaranteed to end in 0
count_positive(unsigned char * list)57 unsigned int count_positive(unsigned char *list)
58 {
59 	unsigned int c;
60 
61 	for (c = 0; list[c] > 0; c++);
62 
63 	return c;
64 }
65 
cs_strdup(const char * str)66 char *cs_strdup(const char *str)
67 {
68 	size_t len = strlen(str)+ 1;
69 	void *new = cs_mem_malloc(len);
70 
71 	if (new == NULL)
72 		return NULL;
73 
74 	return (char *)memmove(new, str, len);
75 }
76 
77 // we need this since Windows doesnt have snprintf()
cs_snprintf(char * buffer,size_t size,const char * fmt,...)78 int cs_snprintf(char *buffer, size_t size, const char *fmt, ...)
79 {
80 	int ret;
81 
82 	va_list ap;
83 	va_start(ap, fmt);
84 	ret = cs_vsnprintf(buffer, size, fmt, ap);
85 	va_end(ap);
86 
87 	return ret;
88 }
89