more error handling
[project/uci.git] / libuci.c
1 /*
2 * libuci - Library for the Unified Configuration Interface
3 * Copyright (C) 2008 Felix Fietkau <nbd@openwrt.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License version 2.1
7 * as published by the Free Software Foundation
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14
15 /*
16 * This file contains some common code for the uci library
17 */
18
19 #include <sys/types.h>
20 #include <stdbool.h>
21 #include <string.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include "libuci.h"
25
26 #define DEBUG
27 #include "err.h"
28
29 static const char *uci_errstr[] = {
30 [UCI_OK] = "Success",
31 [UCI_ERR_MEM] = "Out of memory",
32 [UCI_ERR_INVAL] = "Invalid argument",
33 [UCI_ERR_NOTFOUND] = "Entry not found",
34 [UCI_ERR_PARSE] = "Parse error",
35 [UCI_ERR_UNKNOWN] = "Unknown error",
36 };
37
38
39 /*
40 * UCI wrapper for malloc, which uses exception handling
41 */
42 static void *uci_malloc(struct uci_context *ctx, size_t size)
43 {
44 void *ptr;
45
46 ptr = malloc(size);
47 if (!ptr)
48 UCI_THROW(ctx, UCI_ERR_MEM);
49 memset(ptr, 0, size);
50
51 return ptr;
52 }
53
54 /*
55 * UCI wrapper for realloc, which uses exception handling
56 */
57 static void *uci_realloc(struct uci_context *ctx, void *ptr, size_t size)
58 {
59 ptr = realloc(ptr, size);
60 if (!ptr)
61 UCI_THROW(ctx, UCI_ERR_MEM);
62
63 return ptr;
64 }
65
66 /*
67 * UCI wrapper for strdup, which uses exception handling
68 */
69 static char *uci_strdup(struct uci_context *ctx, const char *str)
70 {
71 char *ptr;
72
73 ptr = strdup(str);
74 if (!ptr)
75 UCI_THROW(ctx, UCI_ERR_MEM);
76
77 return ptr;
78 }
79
80 #include "list.c"
81 #include "parse.c"
82
83 /* externally visible functions */
84
85 struct uci_context *uci_alloc(void)
86 {
87 struct uci_context *ctx;
88
89 ctx = (struct uci_context *) malloc(sizeof(struct uci_context));
90 memset(ctx, 0, sizeof(struct uci_context));
91 uci_list_init(&ctx->root);
92
93 return ctx;
94 }
95
96 int uci_cleanup(struct uci_context *ctx)
97 {
98 UCI_HANDLE_ERR(ctx);
99 uci_parse_cleanup(ctx);
100 return 0;
101 }
102
103 void uci_perror(struct uci_context *ctx, const char *str)
104 {
105 int err;
106
107 if (!ctx)
108 err = UCI_ERR_INVAL;
109 else
110 err = ctx->errno;
111
112 if ((err < 0) || (err >= UCI_ERR_LAST))
113 err = UCI_ERR_UNKNOWN;
114
115 switch (err) {
116 case UCI_ERR_PARSE:
117 if (ctx->pctx) {
118 fprintf(stderr, "%s: %s at line %d, byte %d\n", str, uci_errstr[err], ctx->pctx->line, ctx->pctx->byte);
119 break;
120 }
121 /* fall through */
122 default:
123 fprintf(stderr, "%s: %s\n", str, uci_errstr[err]);
124 break;
125 }
126 }
127
128