summaryrefslogtreecommitdiff
path: root/masm/strtab.c
blob: bd914b0cafa4eb09d05692f5b56f32d3fc993c66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <merror.h>
#include <string.h>
#include <stdlib.h>

#include "asm.h"

int strtab_get_str(struct elf_str_table *strtab, const char *str, size_t *res)
{
	for (size_t i = 0; i < strtab->size; i ++) {
		if (strcmp(strtab->ptr + i, str) == 0) {
			if (res != NULL)
				*res = i;
			return M_SUCCESS;
		}
	}

	return M_ERROR;
}

int strtab_write_str(struct elf_str_table *strtab, const char *str, size_t *res)
{
	if (strtab_get_str(strtab, str, res) == M_SUCCESS)
		return M_SUCCESS;

	size_t len = strlen(str);
	char *new = realloc(strtab->ptr, strtab->size + len + 1);
	if (new == NULL)
		return M_ERROR;
	strtab->ptr = new;
	memcpy(strtab->ptr + strtab->size, str, len + 1);

	if (res != NULL)
		*res = strtab->size;

	strtab->size += len + 1;
	return M_SUCCESS;
}

int strtab_init(struct elf_str_table *strtab)
{
	strtab->size = 1;
	strtab->ptr = malloc(1);
	if (strtab->ptr == NULL) {
		PERROR("cannot alloc");
		return M_ERROR;
	}
	*strtab->ptr = '\0';
	return M_SUCCESS;
}

void strtab_free(struct elf_str_table *strtab)
{
	free(strtab->ptr);
}