Improve error reporting on init
[ocaml-augeas.git] / augeas-c.c
1 /* Augeas OCaml bindings
2  * Copyright (C) 2008-2017 Red Hat Inc., Richard W.M. Jones
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library 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 GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  *
18  * $Id: augeas_c.c,v 1.1 2008/05/06 10:48:20 rjones Exp $
19  */
20
21 #include "config.h"
22
23 #include <augeas.h>
24
25 #include <caml/alloc.h>
26 #include <caml/memory.h>
27 #include <caml/mlvalues.h>
28 #include <caml/fail.h>
29 #include <caml/callback.h>
30 #include <caml/custom.h>
31
32 #include <stdbool.h>
33
34 #ifdef __GNUC__
35   #define NORETURN __attribute__ ((noreturn))
36 #else
37   #define NORETURN
38 #endif
39
40 extern CAMLprim value ocaml_augeas_create (value rootv, value loadpathv, value flagsv);
41 extern CAMLprim value ocaml_augeas_close (value tv);
42 extern CAMLprim value ocaml_augeas_get (value tv, value pathv);
43 extern CAMLprim value ocaml_augeas_exists (value tv, value pathv);
44 extern CAMLprim value ocaml_augeas_insert (value tv, value beforev, value pathv, value labelv);
45 extern CAMLprim value ocaml_augeas_rm (value tv, value pathv);
46 extern CAMLprim value ocaml_augeas_match (value tv, value pathv);
47 extern CAMLprim value ocaml_augeas_count_matches (value tv, value pathv);
48 extern CAMLprim value ocaml_augeas_save (value tv);
49 extern CAMLprim value ocaml_augeas_load (value tv);
50 extern CAMLprim value ocaml_augeas_set (value tv, value pathv, value valuev);
51 extern CAMLprim value ocaml_augeas_transform (value tv, value lensv, value filev, value modev);
52 extern CAMLprim value ocaml_augeas_source (value tv, value pathv)
53 #ifndef HAVE_AUG_SOURCE
54   NORETURN
55 #endif
56 ;
57
58 typedef augeas *augeas_t;
59
60 /* Map C aug_errcode_t to OCaml error_code. */
61 static const int error_map[] = {
62   /* AugErrInternal */ AUG_EINTERNAL,
63   /* AugErrPathX */    AUG_EPATHX,
64   /* AugErrNoMatch */  AUG_ENOMATCH,
65   /* AugErrMMatch */   AUG_EMMATCH,
66   /* AugErrSyntax */   AUG_ESYNTAX,
67   /* AugErrNoLens */   AUG_ENOLENS,
68   /* AugErrMXfm */     AUG_EMXFM,
69   /* AugErrNoSpan */   AUG_ENOSPAN,
70   /* AugErrMvDesc */   AUG_EMVDESC,
71   /* AugErrCmdRun */   AUG_ECMDRUN,
72   /* AugErrBadArg */   AUG_EBADARG,
73   /* AugErrLabel */    AUG_ELABEL,
74   /* AugErrCpDesc */   AUG_ECPDESC,
75 };
76 static const int error_map_len = sizeof error_map / sizeof error_map[0];
77
78 /* Raise an Augeas.Error exception, and optionally close the
79  * specified handle.
80  */
81 static void
82 raise_error_and_maybe_close (augeas_t t, const char *msg, bool close_handle)
83 {
84   value *exn = caml_named_value ("Augeas.Error");
85   value args[4];
86   const int code = aug_error (t);
87   const char *aug_err_minor;
88   const char *aug_err_details;
89   int ocaml_code = -1;
90   int i;
91
92   if (code == AUG_ENOMEM) {
93     if (close_handle)
94       aug_close (t);
95     caml_raise_out_of_memory ();
96   }
97
98   aug_err_minor = aug_error_minor_message (t);
99   aug_err_details = aug_error_details (t);
100
101   for (i = 0; i < error_map_len; ++i)
102     if (error_map[i] == code) {
103       ocaml_code = i;
104       break;
105     }
106
107   if (ocaml_code != -1)
108     args[0] = Val_int (ocaml_code);
109   else {
110     args[0] = caml_alloc (1, 0);
111     Store_field (args[0], 0, Val_int (code));
112   }
113   args[1] = caml_copy_string (msg);
114   args[2] = caml_copy_string (aug_err_minor ? : "");
115   args[3] = caml_copy_string (aug_err_details ? : "");
116
117   if (close_handle)
118     aug_close (t);
119
120   caml_raise_with_args (*exn, 4, args);
121 }
122 #define raise_error(t, msg) raise_error_and_maybe_close(t, msg, false)
123
124 static void
125 raise_init_error (const char *msg)
126 {
127   value *exn = caml_named_value ("Augeas.Error");
128   value args[4];
129
130   args[0] = caml_alloc (1, 0);
131   Store_field (args[0], 0, Val_int (-1));
132   args[1] = caml_copy_string (msg);
133   args[2] = caml_copy_string ("augeas initialization failed");
134   args[3] = caml_copy_string ("");
135
136   caml_raise_with_args (*exn, 4, args);
137 }
138
139 /* Map OCaml flags to C flags. */
140 static const int flag_map[] = {
141   /* AugSaveBackup */  AUG_SAVE_BACKUP,
142   /* AugSaveNewFile */ AUG_SAVE_NEWFILE,
143   /* AugTypeCheck */   AUG_TYPE_CHECK,
144   /* AugNoStdinc */    AUG_NO_STDINC,
145   /* AugSaveNoop */    AUG_SAVE_NOOP,
146   /* AugNoLoad */      AUG_NO_LOAD,
147   /* AugNoModlAutoload */ AUG_NO_MODL_AUTOLOAD,
148   /* AugEnableSpan */  AUG_ENABLE_SPAN,
149   /* AugNoErrClose */  AUG_NO_ERR_CLOSE,
150   /* AugTraceModuleLoading */ AUG_TRACE_MODULE_LOADING,
151 };
152
153 /* Wrap and unwrap augeas_t handles, with a finalizer. */
154 #define Augeas_t_val(rv) (*(augeas_t *)Data_custom_val(rv))
155
156 static void
157 augeas_t_finalize (value tv)
158 {
159   augeas_t t = Augeas_t_val (tv);
160   if (t) aug_close (t);
161 }
162
163 static struct custom_operations custom_operations = {
164   (char *) "augeas_t_custom_operations",
165   augeas_t_finalize,
166   custom_compare_default,
167   custom_hash_default,
168   custom_serialize_default,
169   custom_deserialize_default,
170   custom_compare_ext_default,
171 };
172
173 static value Val_augeas_t (augeas_t t)
174 {
175   CAMLparam0 ();
176   CAMLlocal1 (rv);
177   /* We could choose these so that the GC can make better decisions.
178    * See 18.9.2 of the OCaml manual.
179    */
180   const int used = 0;
181   const int max = 1;
182
183   rv = caml_alloc_custom (&custom_operations,
184                           sizeof (augeas_t), used, max);
185   Augeas_t_val(rv) = t;
186
187   CAMLreturn (rv);
188 }
189
190 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
191
192 /* val create : string -> string option -> flag list -> t */
193 CAMLprim value
194 ocaml_augeas_create (value rootv, value loadpathv, value flagsv)
195 {
196   CAMLparam1 (rootv);
197   const char *root = String_val (rootv);
198   const char *loadpath;
199   int flags = 0, i;
200   augeas_t t;
201
202   /* Optional loadpath. */
203   loadpath =
204     loadpathv == Val_int (0)
205     ? NULL
206     : String_val (Field (loadpathv, 0));
207
208   /* Convert list of flags to C. */
209   for (; flagsv != Val_int (0); flagsv = Field (flagsv, 1)) {
210     i = Int_val (Field (flagsv, 0));
211     flags |= flag_map[i];
212   }
213
214   /* Pass AUG_NO_ERR_CLOSE so we raise a detailed Augeas.Error. */
215   t = aug_init (root, loadpath, flags | AUG_NO_ERR_CLOSE);
216
217   if (t == NULL)
218     raise_init_error ("Augeas.create");
219
220   if (aug_error (t) != AUG_NOERROR) {
221     raise_error_and_maybe_close (t, "Augeas.init", true);
222   }
223
224   CAMLreturn (Val_augeas_t (t));
225 }
226
227 /* val close : t -> unit */
228 CAMLprim value
229 ocaml_augeas_close (value tv)
230 {
231   CAMLparam1 (tv);
232   augeas_t t = Augeas_t_val (tv);
233
234   if (t) {
235     aug_close (t);
236     Augeas_t_val(tv) = NULL;    /* So the finalizer doesn't double-free. */
237   }
238
239   CAMLreturn (Val_unit);
240 }
241
242 /* val get : t -> path -> value option */
243 CAMLprim value
244 ocaml_augeas_get (value tv, value pathv)
245 {
246   CAMLparam2 (tv, pathv);
247   CAMLlocal2 (optv, v);
248   augeas_t t = Augeas_t_val (tv);
249   const char *path = String_val (pathv);
250   const char *val;
251   int r;
252
253   r = aug_get (t, path, &val);
254   if (r == 1 && val) {          /* Return Some val */
255     v = caml_copy_string (val);
256     optv = caml_alloc (1, 0);
257     Field (optv, 0) = v;
258   } else if (r == 0 || !val)    /* Return None */
259     optv = Val_int (0);
260   else if (r == -1)             /* Error or multiple matches */
261     raise_error (t, "Augeas.get");
262   else
263     caml_failwith ("Augeas.get: bad return value");
264
265   CAMLreturn (optv);
266 }
267
268 /* val exists : t -> path -> bool */
269 CAMLprim value
270 ocaml_augeas_exists (value tv, value pathv)
271 {
272   CAMLparam2 (tv, pathv);
273   CAMLlocal1 (v);
274   augeas_t t = Augeas_t_val (tv);
275   const char *path = String_val (pathv);
276   int r;
277
278   r = aug_get (t, path, NULL);
279   if (r == 1)                   /* Return true. */
280     v = Val_int (1);
281   else if (r == 0)              /* Return false */
282     v = Val_int (0);
283   else if (r == -1)             /* Error or multiple matches */
284     raise_error (t, "Augeas.exists");
285   else
286     failwith ("Augeas.exists: bad return value");
287
288   CAMLreturn (v);
289 }
290
291 /* val insert : t -> ?before:bool -> path -> string -> unit */
292 CAMLprim value
293 ocaml_augeas_insert (value tv, value beforev, value pathv, value labelv)
294 {
295   CAMLparam4 (tv, beforev, pathv, labelv);
296   augeas_t t = Augeas_t_val (tv);
297   const char *path = String_val (pathv);
298   const char *label = String_val (labelv);
299   int before;
300
301   before = beforev == Val_int (0) ? 0 : Int_val (Field (beforev, 0));
302
303   if (aug_insert (t, path, label, before) == -1)
304     raise_error (t, "Augeas.insert");
305
306   CAMLreturn (Val_unit);
307 }
308
309 /* val rm : t -> path -> int */
310 CAMLprim value
311 ocaml_augeas_rm (value tv, value pathv)
312 {
313   CAMLparam2 (tv, pathv);
314   augeas_t t = Augeas_t_val (tv);
315   const char *path = String_val (pathv);
316   int r;
317
318   r = aug_rm (t, path);
319   if (r == -1)
320     raise_error (t, "Augeas.rm");
321
322   CAMLreturn (Val_int (r));
323 }
324
325 /* val matches : t -> path -> path list */
326 CAMLprim value
327 ocaml_augeas_match (value tv, value pathv)
328 {
329   CAMLparam2 (tv, pathv);
330   CAMLlocal3 (rv, v, cons);
331   augeas_t t = Augeas_t_val (tv);
332   const char *path = String_val (pathv);
333   char **matches;
334   int r, i;
335
336   r = aug_match (t, path, &matches);
337   if (r == -1)
338     raise_error (t, "Augeas.matches");
339
340   /* Copy the paths to a list. */
341   rv = Val_int (0);
342   for (i = 0; i < r; ++i) {
343     v = caml_copy_string (matches[i]);
344     free (matches[i]);
345     cons = caml_alloc (2, 0);
346     Field (cons, 1) = rv;
347     Field (cons, 0) = v;
348     rv = cons;
349   }
350
351   free (matches);
352
353   CAMLreturn (rv);
354 }
355
356 /* val count_matches : t -> path -> int */
357 CAMLprim value
358 ocaml_augeas_count_matches (value tv, value pathv)
359 {
360   CAMLparam2 (tv, pathv);
361   augeas_t t = Augeas_t_val (tv);
362   const char *path = String_val (pathv);
363   int r;
364
365   r = aug_match (t, path, NULL);
366   if (r == -1)
367     raise_error (t, "Augeas.count_matches");
368
369   CAMLreturn (Val_int (r));
370 }
371
372 /* val save : t -> unit */
373 CAMLprim value
374 ocaml_augeas_save (value tv)
375 {
376   CAMLparam1 (tv);
377   augeas_t t = Augeas_t_val (tv);
378
379   if (aug_save (t) == -1)
380     raise_error (t, "Augeas.save");
381
382   CAMLreturn (Val_unit);
383 }
384
385 /* val load : t -> unit */
386 CAMLprim value
387 ocaml_augeas_load (value tv)
388 {
389   CAMLparam1 (tv);
390   augeas_t t = Augeas_t_val (tv);
391
392   if (aug_load (t) == -1)
393     raise_error (t, "Augeas.load");
394
395   CAMLreturn (Val_unit);
396 }
397
398 /* val set : t -> -> path -> value option -> unit */
399 CAMLprim value
400 ocaml_augeas_set (value tv, value pathv, value valuev)
401 {
402   CAMLparam3 (tv, pathv, valuev);
403   augeas_t t = Augeas_t_val (tv);
404   const char *path = String_val (pathv);
405   const char *val;
406
407   val =
408     valuev == Val_int (0)
409     ? NULL
410     : String_val (Field (valuev, 0));
411
412   if (aug_set (t, path, val) == -1)
413     raise_error (t, "Augeas.set");
414
415   CAMLreturn (Val_unit);
416 }
417
418 /* val transform : t -> string -> string -> transform_mode -> unit */
419 CAMLprim value
420 ocaml_augeas_transform (value tv, value lensv, value filev, value modev)
421 {
422   CAMLparam4 (tv, lensv, filev, modev);
423   augeas_t t = Augeas_t_val (tv);
424   const char *lens = String_val (lensv);
425   const char *file = String_val (filev);
426   const int excl = Int_val (modev) == 1 ? 1 : 0;
427
428   if (aug_transform (t, lens, file, excl) == -1)
429     raise_error (t, "Augeas.transform");
430
431   CAMLreturn (Val_unit);
432 }
433
434 /* val source : t -> path -> path option */
435 CAMLprim value
436 ocaml_augeas_source (value tv, value pathv)
437 {
438 #ifdef HAVE_AUG_SOURCE
439   CAMLparam2 (tv, pathv);
440   CAMLlocal2 (optv, v);
441   augeas_t t = Augeas_t_val (tv);
442   const char *path = String_val (pathv);
443   char *file_path;
444   int r;
445
446   r = aug_source (t, path, &file_path);
447   if (r == 0) {
448     if (file_path) {    /* Return Some file_path */
449       v = caml_copy_string (file_path);
450       optv = caml_alloc (1, 0);
451       Field (optv, 0) = v;
452       free (file_path);
453     } else              /* Return None */
454       optv = Val_int (0);
455   }
456   else                  /* Error */
457     raise_error (t, "Augeas.source");
458
459   CAMLreturn (optv);
460 #else
461   caml_failwith ("Augeas.source: function not implemented");
462 #endif
463 }