]> granicus.if.org Git - zfs/blob - module/zfs/zcp.c
1a39330d363a069eccfe1974fab1dd1d52cbb348
[zfs] / module / zfs / zcp.c
1 /*
2  * CDDL HEADER START
3  *
4  * This file and its contents are supplied under the terms of the
5  * Common Development and Distribution License ("CDDL"), version 1.0.
6  * You may only use this file in accordance with the terms of version
7  * 1.0 of the CDDL.
8  *
9  * A full copy of the text of the CDDL should have accompanied this
10  * source.  A copy of the CDDL is also available via the Internet at
11  * http://www.illumos.org/license/CDDL.
12  *
13  * CDDL HEADER END
14  */
15
16 /*
17  * Copyright (c) 2016, 2017 by Delphix. All rights reserved.
18  */
19
20 /*
21  * ZFS Channel Programs (ZCP)
22  *
23  * The ZCP interface allows various ZFS commands and operations ZFS
24  * administrative operations (e.g. creating and destroying snapshots, typically
25  * performed via an ioctl to /dev/zfs by the zfs(8) command and
26  * libzfs/libzfs_core) to be run * programmatically as a Lua script.  A ZCP
27  * script is run as a dsl_sync_task and fully executed during one transaction
28  * group sync.  This ensures that no other changes can be written concurrently
29  * with a running Lua script.  Combining multiple calls to the exposed ZFS
30  * functions into one script gives a number of benefits:
31  *
32  * 1. Atomicity.  For some compound or iterative operations, it's useful to be
33  * able to guarantee that the state of a pool has not changed between calls to
34  * ZFS.
35  *
36  * 2. Performance.  If a large number of changes need to be made (e.g. deleting
37  * many filesystems), there can be a significant performance penalty as a
38  * result of the need to wait for a transaction group sync to pass for every
39  * single operation.  When expressed as a single ZCP script, all these changes
40  * can be performed at once in one txg sync.
41  *
42  * A modified version of the Lua 5.2 interpreter is used to run channel program
43  * scripts. The Lua 5.2 manual can be found at:
44  *
45  *      http://www.lua.org/manual/5.2/
46  *
47  * If being run by a user (via an ioctl syscall), executing a ZCP script
48  * requires root privileges in the global zone.
49  *
50  * Scripts are passed to zcp_eval() as a string, then run in a synctask by
51  * zcp_eval_sync().  Arguments can be passed into the Lua script as an nvlist,
52  * which will be converted to a Lua table.  Similarly, values returned from
53  * a ZCP script will be converted to an nvlist.  See zcp_lua_to_nvlist_impl()
54  * for details on exact allowed types and conversion.
55  *
56  * ZFS functionality is exposed to a ZCP script as a library of function calls.
57  * These calls are sorted into submodules, such as zfs.list and zfs.sync, for
58  * iterators and synctasks, respectively.  Each of these submodules resides in
59  * its own source file, with a zcp_*_info structure describing each library
60  * call in the submodule.
61  *
62  * Error handling in ZCP scripts is handled by a number of different methods
63  * based on severity:
64  *
65  * 1. Memory and time limits are in place to prevent a channel program from
66  * consuming excessive system or running forever.  If one of these limits is
67  * hit, the channel program will be stopped immediately and return from
68  * zcp_eval() with an error code. No attempt will be made to roll back or undo
69  * any changes made by the channel program before the error occured.
70  * Consumers invoking zcp_eval() from elsewhere in the kernel may pass a time
71  * limit of 0, disabling the time limit.
72  *
73  * 2. Internal Lua errors can occur as a result of a syntax error, calling a
74  * library function with incorrect arguments, invoking the error() function,
75  * failing an assert(), or other runtime errors.  In these cases the channel
76  * program will stop executing and return from zcp_eval() with an error code.
77  * In place of a return value, an error message will also be returned in the
78  * 'result' nvlist containing information about the error. No attempt will be
79  * made to roll back or undo any changes made by the channel program before the
80  * error occured.
81  *
82  * 3. If an error occurs inside a ZFS library call which returns an error code,
83  * the error is returned to the Lua script to be handled as desired.
84  *
85  * In the first two cases, Lua's error-throwing mechanism is used, which
86  * longjumps out of the script execution with luaL_error() and returns with the
87  * error.
88  *
89  * See zfs-program(8) for more information on high level usage.
90  */
91
92 #include <sys/lua/lua.h>
93 #include <sys/lua/lualib.h>
94 #include <sys/lua/lauxlib.h>
95
96 #include <sys/dsl_prop.h>
97 #include <sys/dsl_synctask.h>
98 #include <sys/dsl_dataset.h>
99 #include <sys/zcp.h>
100 #include <sys/zcp_iter.h>
101 #include <sys/zcp_prop.h>
102 #include <sys/zcp_global.h>
103 #include <util/sscanf.h>
104
105 #ifndef KM_NORMALPRI
106 #define KM_NORMALPRI    0
107 #endif
108
109 #define ZCP_NVLIST_MAX_DEPTH 20
110
111 uint64_t zfs_lua_check_instrlimit_interval = 100;
112 uint64_t zfs_lua_max_instrlimit = ZCP_MAX_INSTRLIMIT;
113 uint64_t zfs_lua_max_memlimit = ZCP_MAX_MEMLIMIT;
114
115 /*
116  * Forward declarations for mutually recursive functions
117  */
118 static int zcp_nvpair_value_to_lua(lua_State *, nvpair_t *, char *, int);
119 static int zcp_lua_to_nvlist_impl(lua_State *, int, nvlist_t *, const char *,
120     int);
121
122 typedef struct zcp_alloc_arg {
123         boolean_t       aa_must_succeed;
124         int64_t         aa_alloc_remaining;
125         int64_t         aa_alloc_limit;
126 } zcp_alloc_arg_t;
127
128 typedef struct zcp_eval_arg {
129         lua_State       *ea_state;
130         zcp_alloc_arg_t *ea_allocargs;
131         cred_t          *ea_cred;
132         nvlist_t        *ea_outnvl;
133         int             ea_result;
134         uint64_t        ea_instrlimit;
135 } zcp_eval_arg_t;
136
137 /*ARGSUSED*/
138 static int
139 zcp_eval_check(void *arg, dmu_tx_t *tx)
140 {
141         return (0);
142 }
143
144 /*
145  * The outer-most error callback handler for use with lua_pcall(). On
146  * error Lua will call this callback with a single argument that
147  * represents the error value. In most cases this will be a string
148  * containing an error message, but channel programs can use Lua's
149  * error() function to return arbitrary objects as errors. This callback
150  * returns (on the Lua stack) the original error object along with a traceback.
151  *
152  * Fatal Lua errors can occur while resources are held, so we also call any
153  * registered cleanup function here.
154  */
155 static int
156 zcp_error_handler(lua_State *state)
157 {
158         const char *msg;
159
160         zcp_cleanup(state);
161
162         VERIFY3U(1, ==, lua_gettop(state));
163         msg = lua_tostring(state, 1);
164         luaL_traceback(state, state, msg, 1);
165         return (1);
166 }
167
168 int
169 zcp_argerror(lua_State *state, int narg, const char *msg, ...)
170 {
171         va_list alist;
172
173         va_start(alist, msg);
174         const char *buf = lua_pushvfstring(state, msg, alist);
175         va_end(alist);
176
177         return (luaL_argerror(state, narg, buf));
178 }
179
180 /*
181  * Install a new cleanup function, which will be invoked with the given
182  * opaque argument if a fatal error causes the Lua interpreter to longjump out
183  * of a function call.
184  *
185  * If an error occurs, the cleanup function will be invoked exactly once and
186  * then unreigstered.
187  */
188 void
189 zcp_register_cleanup(lua_State *state, zcp_cleanup_t cleanfunc, void *cleanarg)
190 {
191         zcp_run_info_t *ri = zcp_run_info(state);
192         /*
193          * A cleanup function should always be explicitly removed before
194          * installing a new one to avoid accidental clobbering.
195          */
196         ASSERT3P(ri->zri_cleanup, ==, NULL);
197
198         ri->zri_cleanup = cleanfunc;
199         ri->zri_cleanup_arg = cleanarg;
200 }
201
202 void
203 zcp_clear_cleanup(lua_State *state)
204 {
205         zcp_run_info_t *ri = zcp_run_info(state);
206
207         ri->zri_cleanup = NULL;
208         ri->zri_cleanup_arg = NULL;
209 }
210
211 /*
212  * If it exists, execute the currently set cleanup function then unregister it.
213  */
214 void
215 zcp_cleanup(lua_State *state)
216 {
217         zcp_run_info_t *ri = zcp_run_info(state);
218
219         if (ri->zri_cleanup != NULL) {
220                 ri->zri_cleanup(ri->zri_cleanup_arg);
221                 zcp_clear_cleanup(state);
222         }
223 }
224
225 /*
226  * Convert the lua table at the given index on the Lua stack to an nvlist
227  * and return it.
228  *
229  * If the table can not be converted for any reason, NULL is returned and
230  * an error message is pushed onto the Lua stack.
231  */
232 static nvlist_t *
233 zcp_table_to_nvlist(lua_State *state, int index, int depth)
234 {
235         nvlist_t *nvl;
236         /*
237          * Converting a Lua table to an nvlist with key uniqueness checking is
238          * O(n^2) in the number of keys in the nvlist, which can take a long
239          * time when we return a large table from a channel program.
240          * Furthermore, Lua's table interface *almost* guarantees unique keys
241          * on its own (details below). Therefore, we don't use fnvlist_alloc()
242          * here to avoid the built-in uniqueness checking.
243          *
244          * The *almost* is because it's possible to have key collisions between
245          * e.g. the string "1" and the number 1, or the string "true" and the
246          * boolean true, so we explicitly check that when we're looking at a
247          * key which is an integer / boolean or a string that can be parsed as
248          * one of those types. In the worst case this could still devolve into
249          * O(n^2), so we only start doing these checks on boolean/integer keys
250          * once we've seen a string key which fits this weird usage pattern.
251          *
252          * Ultimately, we still want callers to know that the keys in this
253          * nvlist are unique, so before we return this we set the nvlist's
254          * flags to reflect that.
255          */
256         VERIFY0(nvlist_alloc(&nvl, 0, KM_SLEEP));
257
258         /*
259          * Push an empty stack slot where lua_next() will store each
260          * table key.
261          */
262         lua_pushnil(state);
263         boolean_t saw_str_could_collide = B_FALSE;
264         while (lua_next(state, index) != 0) {
265                 /*
266                  * The next key-value pair from the table at index is
267                  * now on the stack, with the key at stack slot -2 and
268                  * the value at slot -1.
269                  */
270                 int err = 0;
271                 char buf[32];
272                 const char *key = NULL;
273                 boolean_t key_could_collide = B_FALSE;
274
275                 switch (lua_type(state, -2)) {
276                 case LUA_TSTRING:
277                         key = lua_tostring(state, -2);
278
279                         /* check if this could collide with a number or bool */
280                         long long tmp;
281                         int parselen;
282                         if ((sscanf(key, "%lld%n", &tmp, &parselen) > 0 &&
283                             parselen == strlen(key)) ||
284                             strcmp(key, "true") == 0 ||
285                             strcmp(key, "false") == 0) {
286                                 key_could_collide = B_TRUE;
287                                 saw_str_could_collide = B_TRUE;
288                         }
289                         break;
290                 case LUA_TBOOLEAN:
291                         key = (lua_toboolean(state, -2) == B_TRUE ?
292                             "true" : "false");
293                         if (saw_str_could_collide) {
294                                 key_could_collide = B_TRUE;
295                         }
296                         break;
297                 case LUA_TNUMBER:
298                         VERIFY3U(sizeof (buf), >,
299                             snprintf(buf, sizeof (buf), "%lld",
300                             (longlong_t)lua_tonumber(state, -2)));
301                         key = buf;
302                         if (saw_str_could_collide) {
303                                 key_could_collide = B_TRUE;
304                         }
305                         break;
306                 default:
307                         fnvlist_free(nvl);
308                         (void) lua_pushfstring(state, "Invalid key "
309                             "type '%s' in table",
310                             lua_typename(state, lua_type(state, -2)));
311                         return (NULL);
312                 }
313                 /*
314                  * Check for type-mismatched key collisions, and throw an error.
315                  */
316                 if (key_could_collide && nvlist_exists(nvl, key)) {
317                         fnvlist_free(nvl);
318                         (void) lua_pushfstring(state, "Collision of "
319                             "key '%s' in table", key);
320                         return (NULL);
321                 }
322                 /*
323                  * Recursively convert the table value and insert into
324                  * the new nvlist with the parsed key.  To prevent
325                  * stack overflow on circular or heavily nested tables,
326                  * we track the current nvlist depth.
327                  */
328                 if (depth >= ZCP_NVLIST_MAX_DEPTH) {
329                         fnvlist_free(nvl);
330                         (void) lua_pushfstring(state, "Maximum table "
331                             "depth (%d) exceeded for table",
332                             ZCP_NVLIST_MAX_DEPTH);
333                         return (NULL);
334                 }
335                 err = zcp_lua_to_nvlist_impl(state, -1, nvl, key,
336                     depth + 1);
337                 if (err != 0) {
338                         fnvlist_free(nvl);
339                         /*
340                          * Error message has been pushed to the lua
341                          * stack by the recursive call.
342                          */
343                         return (NULL);
344                 }
345                 /*
346                  * Pop the value pushed by lua_next().
347                  */
348                 lua_pop(state, 1);
349         }
350
351         /*
352          * Mark the nvlist as having unique keys. This is a little ugly, but we
353          * ensured above that there are no duplicate keys in the nvlist.
354          */
355         nvl->nvl_nvflag |= NV_UNIQUE_NAME;
356
357         return (nvl);
358 }
359
360 /*
361  * Convert a value from the given index into the lua stack to an nvpair, adding
362  * it to an nvlist with the given key.
363  *
364  * Values are converted as follows:
365  *
366  *   string -> string
367  *   number -> int64
368  *   boolean -> boolean
369  *   nil -> boolean (no value)
370  *
371  * Lua tables are converted to nvlists and then inserted. The table's keys
372  * are converted to strings then used as keys in the nvlist to store each table
373  * element.  Keys are converted as follows:
374  *
375  *   string -> no change
376  *   number -> "%lld"
377  *   boolean -> "true" | "false"
378  *   nil -> error
379  *
380  * In the case of a key collision, an error is thrown.
381  *
382  * If an error is encountered, a nonzero error code is returned, and an error
383  * string will be pushed onto the Lua stack.
384  */
385 static int
386 zcp_lua_to_nvlist_impl(lua_State *state, int index, nvlist_t *nvl,
387     const char *key, int depth)
388 {
389         /*
390          * Verify that we have enough remaining space in the lua stack to parse
391          * a key-value pair and push an error.
392          */
393         if (!lua_checkstack(state, 3)) {
394                 (void) lua_pushstring(state, "Lua stack overflow");
395                 return (1);
396         }
397
398         index = lua_absindex(state, index);
399
400         switch (lua_type(state, index)) {
401         case LUA_TNIL:
402                 fnvlist_add_boolean(nvl, key);
403                 break;
404         case LUA_TBOOLEAN:
405                 fnvlist_add_boolean_value(nvl, key,
406                     lua_toboolean(state, index));
407                 break;
408         case LUA_TNUMBER:
409                 fnvlist_add_int64(nvl, key, lua_tonumber(state, index));
410                 break;
411         case LUA_TSTRING:
412                 fnvlist_add_string(nvl, key, lua_tostring(state, index));
413                 break;
414         case LUA_TTABLE: {
415                 nvlist_t *value_nvl = zcp_table_to_nvlist(state, index, depth);
416                 if (value_nvl == NULL)
417                         return (EINVAL);
418
419                 fnvlist_add_nvlist(nvl, key, value_nvl);
420                 fnvlist_free(value_nvl);
421                 break;
422         }
423         default:
424                 (void) lua_pushfstring(state,
425                     "Invalid value type '%s' for key '%s'",
426                     lua_typename(state, lua_type(state, index)), key);
427                 return (EINVAL);
428         }
429
430         return (0);
431 }
432
433 /*
434  * Convert a lua value to an nvpair, adding it to an nvlist with the given key.
435  */
436 void
437 zcp_lua_to_nvlist(lua_State *state, int index, nvlist_t *nvl, const char *key)
438 {
439         /*
440          * On error, zcp_lua_to_nvlist_impl pushes an error string onto the Lua
441          * stack before returning with a nonzero error code. If an error is
442          * returned, throw a fatal lua error with the given string.
443          */
444         if (zcp_lua_to_nvlist_impl(state, index, nvl, key, 0) != 0)
445                 (void) lua_error(state);
446 }
447
448 int
449 zcp_lua_to_nvlist_helper(lua_State *state)
450 {
451         nvlist_t *nv = (nvlist_t *)lua_touserdata(state, 2);
452         const char *key = (const char *)lua_touserdata(state, 1);
453         zcp_lua_to_nvlist(state, 3, nv, key);
454         return (0);
455 }
456
457 void
458 zcp_convert_return_values(lua_State *state, nvlist_t *nvl,
459     const char *key, zcp_eval_arg_t *evalargs)
460 {
461         int err;
462         lua_pushcfunction(state, zcp_lua_to_nvlist_helper);
463         lua_pushlightuserdata(state, (char *)key);
464         lua_pushlightuserdata(state, nvl);
465         lua_pushvalue(state, 1);
466         lua_remove(state, 1);
467         err = lua_pcall(state, 3, 0, 0); /* zcp_lua_to_nvlist_helper */
468         if (err != 0) {
469                 zcp_lua_to_nvlist(state, 1, nvl, ZCP_RET_ERROR);
470                 evalargs->ea_result = SET_ERROR(ECHRNG);
471         }
472 }
473
474 /*
475  * Push a Lua table representing nvl onto the stack.  If it can't be
476  * converted, return EINVAL, fill in errbuf, and push nothing. errbuf may
477  * be specified as NULL, in which case no error string will be output.
478  *
479  * Most nvlists are converted as simple key->value Lua tables, but we make
480  * an exception for the case where all nvlist entries are BOOLEANs (a string
481  * key without a value). In Lua, a table key pointing to a value of Nil
482  * (no value) is equivalent to the key not existing, so a BOOLEAN nvlist
483  * entry can't be directly converted to a Lua table entry. Nvlists of entirely
484  * BOOLEAN entries are frequently used to pass around lists of datasets, so for
485  * convenience we check for this case, and convert it to a simple Lua array of
486  * strings.
487  */
488 int
489 zcp_nvlist_to_lua(lua_State *state, nvlist_t *nvl,
490     char *errbuf, int errbuf_len)
491 {
492         nvpair_t *pair;
493         lua_newtable(state);
494         boolean_t has_values = B_FALSE;
495         /*
496          * If the list doesn't have any values, just convert it to a string
497          * array.
498          */
499         for (pair = nvlist_next_nvpair(nvl, NULL);
500             pair != NULL; pair = nvlist_next_nvpair(nvl, pair)) {
501                 if (nvpair_type(pair) != DATA_TYPE_BOOLEAN) {
502                         has_values = B_TRUE;
503                         break;
504                 }
505         }
506         if (!has_values) {
507                 int i = 1;
508                 for (pair = nvlist_next_nvpair(nvl, NULL);
509                     pair != NULL; pair = nvlist_next_nvpair(nvl, pair)) {
510                         (void) lua_pushinteger(state, i);
511                         (void) lua_pushstring(state, nvpair_name(pair));
512                         (void) lua_settable(state, -3);
513                         i++;
514                 }
515         } else {
516                 for (pair = nvlist_next_nvpair(nvl, NULL);
517                     pair != NULL; pair = nvlist_next_nvpair(nvl, pair)) {
518                         int err = zcp_nvpair_value_to_lua(state, pair,
519                             errbuf, errbuf_len);
520                         if (err != 0) {
521                                 lua_pop(state, 1);
522                                 return (err);
523                         }
524                         (void) lua_setfield(state, -2, nvpair_name(pair));
525                 }
526         }
527         return (0);
528 }
529
530 /*
531  * Push a Lua object representing the value of "pair" onto the stack.
532  *
533  * Only understands boolean_value, string, int64, nvlist,
534  * string_array, and int64_array type values.  For other
535  * types, returns EINVAL, fills in errbuf, and pushes nothing.
536  */
537 static int
538 zcp_nvpair_value_to_lua(lua_State *state, nvpair_t *pair,
539     char *errbuf, int errbuf_len)
540 {
541         int err = 0;
542
543         if (pair == NULL) {
544                 lua_pushnil(state);
545                 return (0);
546         }
547
548         switch (nvpair_type(pair)) {
549         case DATA_TYPE_BOOLEAN_VALUE:
550                 (void) lua_pushboolean(state,
551                     fnvpair_value_boolean_value(pair));
552                 break;
553         case DATA_TYPE_STRING:
554                 (void) lua_pushstring(state, fnvpair_value_string(pair));
555                 break;
556         case DATA_TYPE_INT64:
557                 (void) lua_pushinteger(state, fnvpair_value_int64(pair));
558                 break;
559         case DATA_TYPE_NVLIST:
560                 err = zcp_nvlist_to_lua(state,
561                     fnvpair_value_nvlist(pair), errbuf, errbuf_len);
562                 break;
563         case DATA_TYPE_STRING_ARRAY: {
564                 char **strarr;
565                 uint_t nelem;
566                 (void) nvpair_value_string_array(pair, &strarr, &nelem);
567                 lua_newtable(state);
568                 for (int i = 0; i < nelem; i++) {
569                         (void) lua_pushinteger(state, i + 1);
570                         (void) lua_pushstring(state, strarr[i]);
571                         (void) lua_settable(state, -3);
572                 }
573                 break;
574         }
575         case DATA_TYPE_UINT64_ARRAY: {
576                 uint64_t *intarr;
577                 uint_t nelem;
578                 (void) nvpair_value_uint64_array(pair, &intarr, &nelem);
579                 lua_newtable(state);
580                 for (int i = 0; i < nelem; i++) {
581                         (void) lua_pushinteger(state, i + 1);
582                         (void) lua_pushinteger(state, intarr[i]);
583                         (void) lua_settable(state, -3);
584                 }
585                 break;
586         }
587         case DATA_TYPE_INT64_ARRAY: {
588                 int64_t *intarr;
589                 uint_t nelem;
590                 (void) nvpair_value_int64_array(pair, &intarr, &nelem);
591                 lua_newtable(state);
592                 for (int i = 0; i < nelem; i++) {
593                         (void) lua_pushinteger(state, i + 1);
594                         (void) lua_pushinteger(state, intarr[i]);
595                         (void) lua_settable(state, -3);
596                 }
597                 break;
598         }
599         default: {
600                 if (errbuf != NULL) {
601                         (void) snprintf(errbuf, errbuf_len,
602                             "Unhandled nvpair type %d for key '%s'",
603                             nvpair_type(pair), nvpair_name(pair));
604                 }
605                 return (EINVAL);
606         }
607         }
608         return (err);
609 }
610
611 int
612 zcp_dataset_hold_error(lua_State *state, dsl_pool_t *dp, const char *dsname,
613     int error)
614 {
615         if (error == ENOENT) {
616                 (void) zcp_argerror(state, 1, "no such dataset '%s'", dsname);
617                 return (0); /* not reached; zcp_argerror will longjmp */
618         } else if (error == EXDEV) {
619                 (void) zcp_argerror(state, 1,
620                     "dataset '%s' is not in the target pool '%s'",
621                     dsname, spa_name(dp->dp_spa));
622                 return (0); /* not reached; zcp_argerror will longjmp */
623         } else if (error == EIO) {
624                 (void) luaL_error(state,
625                     "I/O error while accessing dataset '%s'", dsname);
626                 return (0); /* not reached; luaL_error will longjmp */
627         } else if (error != 0) {
628                 (void) luaL_error(state,
629                     "unexpected error %d while accessing dataset '%s'",
630                     error, dsname);
631                 return (0); /* not reached; luaL_error will longjmp */
632         }
633         return (0);
634 }
635
636 /*
637  * Note: will longjmp (via lua_error()) on error.
638  * Assumes that the dsname is argument #1 (for error reporting purposes).
639  */
640 dsl_dataset_t *
641 zcp_dataset_hold(lua_State *state, dsl_pool_t *dp, const char *dsname,
642     void *tag)
643 {
644         dsl_dataset_t *ds;
645         int error = dsl_dataset_hold(dp, dsname, tag, &ds);
646         (void) zcp_dataset_hold_error(state, dp, dsname, error);
647         return (ds);
648 }
649
650 static int zcp_debug(lua_State *);
651 static zcp_lib_info_t zcp_debug_info = {
652         .name = "debug",
653         .func = zcp_debug,
654         .pargs = {
655             { .za_name = "debug string", .za_lua_type = LUA_TSTRING},
656             {NULL, 0}
657         },
658         .kwargs = {
659             {NULL, 0}
660         }
661 };
662
663 static int
664 zcp_debug(lua_State *state)
665 {
666         const char *dbgstring;
667         zcp_run_info_t *ri = zcp_run_info(state);
668         zcp_lib_info_t *libinfo = &zcp_debug_info;
669
670         zcp_parse_args(state, libinfo->name, libinfo->pargs, libinfo->kwargs);
671
672         dbgstring = lua_tostring(state, 1);
673
674         zfs_dbgmsg("txg %lld ZCP: %s", ri->zri_tx->tx_txg, dbgstring);
675
676         return (0);
677 }
678
679 static int zcp_exists(lua_State *);
680 static zcp_lib_info_t zcp_exists_info = {
681         .name = "exists",
682         .func = zcp_exists,
683         .pargs = {
684             { .za_name = "dataset", .za_lua_type = LUA_TSTRING},
685             {NULL, 0}
686         },
687         .kwargs = {
688             {NULL, 0}
689         }
690 };
691
692 static int
693 zcp_exists(lua_State *state)
694 {
695         zcp_run_info_t *ri = zcp_run_info(state);
696         dsl_pool_t *dp = ri->zri_pool;
697         zcp_lib_info_t *libinfo = &zcp_exists_info;
698
699         zcp_parse_args(state, libinfo->name, libinfo->pargs, libinfo->kwargs);
700
701         const char *dsname = lua_tostring(state, 1);
702
703         dsl_dataset_t *ds;
704         int error = dsl_dataset_hold(dp, dsname, FTAG, &ds);
705         if (error == 0) {
706                 dsl_dataset_rele(ds, FTAG);
707                 lua_pushboolean(state, B_TRUE);
708         } else if (error == ENOENT) {
709                 lua_pushboolean(state, B_FALSE);
710         } else if (error == EXDEV) {
711                 return (luaL_error(state, "dataset '%s' is not in the "
712                     "target pool", dsname));
713         } else if (error == EIO) {
714                 return (luaL_error(state, "I/O error opening dataset '%s'",
715                     dsname));
716         } else if (error != 0) {
717                 return (luaL_error(state, "unexpected error %d", error));
718         }
719
720         return (1);
721 }
722
723 /*
724  * Allocate/realloc/free a buffer for the lua interpreter.
725  *
726  * When nsize is 0, behaves as free() and returns NULL.
727  *
728  * If ptr is NULL, behaves as malloc() and returns an allocated buffer of size
729  * at least nsize.
730  *
731  * Otherwise, behaves as realloc(), changing the allocation from osize to nsize.
732  * Shrinking the buffer size never fails.
733  *
734  * The original allocated buffer size is stored as a uint64 at the beginning of
735  * the buffer to avoid actually reallocating when shrinking a buffer, since lua
736  * requires that this operation never fail.
737  */
738 static void *
739 zcp_lua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
740 {
741         zcp_alloc_arg_t *allocargs = ud;
742         int flags = (allocargs->aa_must_succeed) ?
743             KM_SLEEP : (KM_NOSLEEP | KM_NORMALPRI);
744
745         if (nsize == 0) {
746                 if (ptr != NULL) {
747                         int64_t *allocbuf = (int64_t *)ptr - 1;
748                         int64_t allocsize = *allocbuf;
749                         ASSERT3S(allocsize, >, 0);
750                         ASSERT3S(allocargs->aa_alloc_remaining + allocsize, <=,
751                             allocargs->aa_alloc_limit);
752                         allocargs->aa_alloc_remaining += allocsize;
753                         vmem_free(allocbuf, allocsize);
754                 }
755                 return (NULL);
756         } else if (ptr == NULL) {
757                 int64_t *allocbuf;
758                 int64_t allocsize = nsize + sizeof (int64_t);
759
760                 if (!allocargs->aa_must_succeed &&
761                     (allocsize <= 0 ||
762                     allocsize > allocargs->aa_alloc_remaining)) {
763                         return (NULL);
764                 }
765
766                 allocbuf = vmem_alloc(allocsize, flags);
767                 if (allocbuf == NULL) {
768                         return (NULL);
769                 }
770                 allocargs->aa_alloc_remaining -= allocsize;
771
772                 *allocbuf = allocsize;
773                 return (allocbuf + 1);
774         } else if (nsize <= osize) {
775                 /*
776                  * If shrinking the buffer, lua requires that the reallocation
777                  * never fail.
778                  */
779                 return (ptr);
780         } else {
781                 ASSERT3U(nsize, >, osize);
782
783                 uint64_t *luabuf = zcp_lua_alloc(ud, NULL, 0, nsize);
784                 if (luabuf == NULL) {
785                         return (NULL);
786                 }
787                 (void) memcpy(luabuf, ptr, osize);
788                 VERIFY3P(zcp_lua_alloc(ud, ptr, osize, 0), ==, NULL);
789                 return (luabuf);
790         }
791 }
792
793 /* ARGSUSED */
794 static void
795 zcp_lua_counthook(lua_State *state, lua_Debug *ar)
796 {
797         /*
798          * If we're called, check how many instructions the channel program has
799          * executed so far, and compare against the limit.
800          */
801         lua_getfield(state, LUA_REGISTRYINDEX, ZCP_RUN_INFO_KEY);
802         zcp_run_info_t *ri = lua_touserdata(state, -1);
803
804         ri->zri_curinstrs += zfs_lua_check_instrlimit_interval;
805         if (ri->zri_maxinstrs != 0 && ri->zri_curinstrs > ri->zri_maxinstrs) {
806                 ri->zri_timed_out = B_TRUE;
807                 (void) lua_pushstring(state,
808                     "Channel program timed out.");
809                 (void) lua_error(state);
810         }
811 }
812
813 static int
814 zcp_panic_cb(lua_State *state)
815 {
816         panic("unprotected error in call to Lua API (%s)\n",
817             lua_tostring(state, -1));
818         return (0);
819 }
820
821 static void
822 zcp_eval_sync(void *arg, dmu_tx_t *tx)
823 {
824         int err;
825         zcp_run_info_t ri;
826         zcp_eval_arg_t *evalargs = arg;
827         lua_State *state = evalargs->ea_state;
828
829         /*
830          * Open context should have setup the stack to contain:
831          * 1: Error handler callback
832          * 2: Script to run (converted to a Lua function)
833          * 3: nvlist input to function (converted to Lua table or nil)
834          */
835         VERIFY3U(3, ==, lua_gettop(state));
836
837         /*
838          * Store the zcp_run_info_t struct for this run in the Lua registry.
839          * Registry entries are not directly accessible by the Lua scripts but
840          * can be accessed by our callbacks.
841          */
842         ri.zri_space_used = 0;
843         ri.zri_pool = dmu_tx_pool(tx);
844         ri.zri_cred = evalargs->ea_cred;
845         ri.zri_tx = tx;
846         ri.zri_timed_out = B_FALSE;
847         ri.zri_cleanup = NULL;
848         ri.zri_cleanup_arg = NULL;
849         ri.zri_curinstrs = 0;
850         ri.zri_maxinstrs = evalargs->ea_instrlimit;
851
852         lua_pushlightuserdata(state, &ri);
853         lua_setfield(state, LUA_REGISTRYINDEX, ZCP_RUN_INFO_KEY);
854         VERIFY3U(3, ==, lua_gettop(state));
855
856         /*
857          * Tell the Lua interpreter to call our handler every count
858          * instructions. Channel programs that execute too many instructions
859          * should die with ETIME.
860          */
861         (void) lua_sethook(state, zcp_lua_counthook, LUA_MASKCOUNT,
862             zfs_lua_check_instrlimit_interval);
863
864         /*
865          * Tell the Lua memory allocator to stop using KM_SLEEP before handing
866          * off control to the channel program. Channel programs that use too
867          * much memory should die with ENOSPC.
868          */
869         evalargs->ea_allocargs->aa_must_succeed = B_FALSE;
870
871         /*
872          * Call the Lua function that open-context passed us. This pops the
873          * function and its input from the stack and pushes any return
874          * or error values.
875          */
876         err = lua_pcall(state, 1, LUA_MULTRET, 1);
877
878         /*
879          * Let Lua use KM_SLEEP while we interpret the return values.
880          */
881         evalargs->ea_allocargs->aa_must_succeed = B_TRUE;
882
883         /*
884          * Remove the error handler callback from the stack. At this point,
885          * if there is a cleanup function registered, then it was registered
886          * but never run or removed, which should never occur.
887          */
888         ASSERT3P(ri.zri_cleanup, ==, NULL);
889         lua_remove(state, 1);
890
891         switch (err) {
892         case LUA_OK: {
893                 /*
894                  * Lua supports returning multiple values in a single return
895                  * statement.  Return values will have been pushed onto the
896                  * stack:
897                  * 1: Return value 1
898                  * 2: Return value 2
899                  * 3: etc...
900                  * To simplify the process of retrieving a return value from a
901                  * channel program, we disallow returning more than one value
902                  * to ZFS from the Lua script, yielding a singleton return
903                  * nvlist of the form { "return": Return value 1 }.
904                  */
905                 int return_count = lua_gettop(state);
906
907                 if (return_count == 1) {
908                         evalargs->ea_result = 0;
909                         zcp_convert_return_values(state, evalargs->ea_outnvl,
910                             ZCP_RET_RETURN, evalargs);
911                 } else if (return_count > 1) {
912                         evalargs->ea_result = SET_ERROR(ECHRNG);
913                         (void) lua_pushfstring(state, "Multiple return "
914                             "values not supported");
915                         zcp_convert_return_values(state, evalargs->ea_outnvl,
916                             ZCP_RET_ERROR, evalargs);
917                 }
918                 break;
919         }
920         case LUA_ERRRUN:
921         case LUA_ERRGCMM: {
922                 /*
923                  * The channel program encountered a fatal error within the
924                  * script, such as failing an assertion, or calling a function
925                  * with incompatible arguments. The error value and the
926                  * traceback generated by zcp_error_handler() should be on the
927                  * stack.
928                  */
929                 VERIFY3U(1, ==, lua_gettop(state));
930                 if (ri.zri_timed_out) {
931                         evalargs->ea_result = SET_ERROR(ETIME);
932                 } else {
933                         evalargs->ea_result = SET_ERROR(ECHRNG);
934                 }
935
936                 zcp_convert_return_values(state, evalargs->ea_outnvl,
937                     ZCP_RET_ERROR, evalargs);
938
939                 if (evalargs->ea_result == ETIME &&
940                     evalargs->ea_outnvl != NULL) {
941                         (void) nvlist_add_uint64(evalargs->ea_outnvl,
942                             ZCP_ARG_INSTRLIMIT, ri.zri_curinstrs);
943                 }
944                 break;
945         }
946         case LUA_ERRERR: {
947                 /*
948                  * The channel program encountered a fatal error within the
949                  * script, and we encountered another error while trying to
950                  * compute the traceback in zcp_error_handler(). We can only
951                  * return the error message.
952                  */
953                 VERIFY3U(1, ==, lua_gettop(state));
954                 if (ri.zri_timed_out) {
955                         evalargs->ea_result = SET_ERROR(ETIME);
956                 } else {
957                         evalargs->ea_result = SET_ERROR(ECHRNG);
958                 }
959
960                 zcp_convert_return_values(state, evalargs->ea_outnvl,
961                     ZCP_RET_ERROR, evalargs);
962                 break;
963         }
964         case LUA_ERRMEM:
965                 /*
966                  * Lua ran out of memory while running the channel program.
967                  * There's not much we can do.
968                  */
969                 evalargs->ea_result = SET_ERROR(ENOSPC);
970                 break;
971         default:
972                 VERIFY0(err);
973         }
974 }
975
976 int
977 zcp_eval(const char *poolname, const char *program, uint64_t instrlimit,
978     uint64_t memlimit, nvpair_t *nvarg, nvlist_t *outnvl)
979 {
980         int err;
981         lua_State *state;
982         zcp_eval_arg_t evalargs;
983
984         if (instrlimit > zfs_lua_max_instrlimit)
985                 return (SET_ERROR(EINVAL));
986         if (memlimit == 0 || memlimit > zfs_lua_max_memlimit)
987                 return (SET_ERROR(EINVAL));
988
989         zcp_alloc_arg_t allocargs = {
990                 .aa_must_succeed = B_TRUE,
991                 .aa_alloc_remaining = (int64_t)memlimit,
992                 .aa_alloc_limit = (int64_t)memlimit,
993         };
994
995         /*
996          * Creates a Lua state with a memory allocator that uses KM_SLEEP.
997          * This should never fail.
998          */
999         state = lua_newstate(zcp_lua_alloc, &allocargs);
1000         VERIFY(state != NULL);
1001         (void) lua_atpanic(state, zcp_panic_cb);
1002
1003         /*
1004          * Load core Lua libraries we want access to.
1005          */
1006         VERIFY3U(1, ==, luaopen_base(state));
1007         lua_pop(state, 1);
1008         VERIFY3U(1, ==, luaopen_coroutine(state));
1009         lua_setglobal(state, LUA_COLIBNAME);
1010         VERIFY0(lua_gettop(state));
1011         VERIFY3U(1, ==, luaopen_string(state));
1012         lua_setglobal(state, LUA_STRLIBNAME);
1013         VERIFY0(lua_gettop(state));
1014         VERIFY3U(1, ==, luaopen_table(state));
1015         lua_setglobal(state, LUA_TABLIBNAME);
1016         VERIFY0(lua_gettop(state));
1017
1018         /*
1019          * Load globally visible variables such as errno aliases.
1020          */
1021         zcp_load_globals(state);
1022         VERIFY0(lua_gettop(state));
1023
1024         /*
1025          * Load ZFS-specific modules.
1026          */
1027         lua_newtable(state);
1028         VERIFY3U(1, ==, zcp_load_list_lib(state));
1029         lua_setfield(state, -2, "list");
1030         VERIFY3U(1, ==, zcp_load_synctask_lib(state, B_FALSE));
1031         lua_setfield(state, -2, "check");
1032         VERIFY3U(1, ==, zcp_load_synctask_lib(state, B_TRUE));
1033         lua_setfield(state, -2, "sync");
1034         VERIFY3U(1, ==, zcp_load_get_lib(state));
1035         lua_pushcclosure(state, zcp_debug_info.func, 0);
1036         lua_setfield(state, -2, zcp_debug_info.name);
1037         lua_pushcclosure(state, zcp_exists_info.func, 0);
1038         lua_setfield(state, -2, zcp_exists_info.name);
1039         lua_setglobal(state, "zfs");
1040         VERIFY0(lua_gettop(state));
1041
1042         /*
1043          * Push the error-callback that calculates Lua stack traces on
1044          * unexpected failures.
1045          */
1046         lua_pushcfunction(state, zcp_error_handler);
1047         VERIFY3U(1, ==, lua_gettop(state));
1048
1049         /*
1050          * Load the actual script as a function onto the stack as text ("t").
1051          * The only valid error condition is a syntax error in the script.
1052          * ERRMEM should not be possible because our allocator is using
1053          * KM_SLEEP.  ERRGCMM should not be possible because we have not added
1054          * any objects with __gc metamethods to the interpreter that could
1055          * fail.
1056          */
1057         err = luaL_loadbufferx(state, program, strlen(program),
1058             "channel program", "t");
1059         if (err == LUA_ERRSYNTAX) {
1060                 fnvlist_add_string(outnvl, ZCP_RET_ERROR,
1061                     lua_tostring(state, -1));
1062                 lua_close(state);
1063                 return (SET_ERROR(EINVAL));
1064         }
1065         VERIFY0(err);
1066         VERIFY3U(2, ==, lua_gettop(state));
1067
1068         /*
1069          * Convert the input nvlist to a Lua object and put it on top of the
1070          * stack.
1071          */
1072         char errmsg[128];
1073         err = zcp_nvpair_value_to_lua(state, nvarg,
1074             errmsg, sizeof (errmsg));
1075         if (err != 0) {
1076                 fnvlist_add_string(outnvl, ZCP_RET_ERROR, errmsg);
1077                 lua_close(state);
1078                 return (SET_ERROR(EINVAL));
1079         }
1080         VERIFY3U(3, ==, lua_gettop(state));
1081
1082         evalargs.ea_state = state;
1083         evalargs.ea_allocargs = &allocargs;
1084         evalargs.ea_instrlimit = instrlimit;
1085         evalargs.ea_cred = CRED();
1086         evalargs.ea_outnvl = outnvl;
1087         evalargs.ea_result = 0;
1088
1089         VERIFY0(dsl_sync_task(poolname, zcp_eval_check,
1090             zcp_eval_sync, &evalargs, 0, ZFS_SPACE_CHECK_NONE));
1091
1092         lua_close(state);
1093
1094         return (evalargs.ea_result);
1095 }
1096
1097 /*
1098  * Retrieve metadata about the currently running channel program.
1099  */
1100 zcp_run_info_t *
1101 zcp_run_info(lua_State *state)
1102 {
1103         zcp_run_info_t *ri;
1104
1105         lua_getfield(state, LUA_REGISTRYINDEX, ZCP_RUN_INFO_KEY);
1106         ri = lua_touserdata(state, -1);
1107         lua_pop(state, 1);
1108         return (ri);
1109 }
1110
1111 /*
1112  * Argument Parsing
1113  * ================
1114  *
1115  * The Lua language allows methods to be called with any number
1116  * of arguments of any type. When calling back into ZFS we need to sanitize
1117  * arguments from channel programs to make sure unexpected arguments or
1118  * arguments of the wrong type result in clear error messages. To do this
1119  * in a uniform way all callbacks from channel programs should use the
1120  * zcp_parse_args() function to interpret inputs.
1121  *
1122  * Positional vs Keyword Arguments
1123  * ===============================
1124  *
1125  * Every callback function takes a fixed set of required positional arguments
1126  * and optional keyword arguments. For example, the destroy function takes
1127  * a single positional string argument (the name of the dataset to destroy)
1128  * and an optional "defer" keyword boolean argument. When calling lua functions
1129  * with parentheses, only positional arguments can be used:
1130  *
1131  *     zfs.sync.snapshot("rpool@snap")
1132  *
1133  * To use keyword arguments functions should be called with a single argument
1134  * that is a lua table containing mappings of integer -> positional arguments
1135  * and string -> keyword arguments:
1136  *
1137  *     zfs.sync.snapshot({1="rpool@snap", defer=true})
1138  *
1139  * The lua language allows curly braces to be used in place of parenthesis as
1140  * syntactic sugar for this calling convention:
1141  *
1142  *     zfs.sync.snapshot{"rpool@snap", defer=true}
1143  */
1144
1145 /*
1146  * Throw an error and print the given arguments.  If there are too many
1147  * arguments to fit in the output buffer, only the error format string is
1148  * output.
1149  */
1150 static void
1151 zcp_args_error(lua_State *state, const char *fname, const zcp_arg_t *pargs,
1152     const zcp_arg_t *kwargs, const char *fmt, ...)
1153 {
1154         int i;
1155         char errmsg[512];
1156         size_t len = sizeof (errmsg);
1157         size_t msglen = 0;
1158         va_list argp;
1159
1160         va_start(argp, fmt);
1161         VERIFY3U(len, >, vsnprintf(errmsg, len, fmt, argp));
1162         va_end(argp);
1163
1164         /*
1165          * Calculate the total length of the final string, including extra
1166          * formatting characters. If the argument dump would be too large,
1167          * only print the error string.
1168          */
1169         msglen = strlen(errmsg);
1170         msglen += strlen(fname) + 4; /* : + {} + null terminator */
1171         for (i = 0; pargs[i].za_name != NULL; i++) {
1172                 msglen += strlen(pargs[i].za_name);
1173                 msglen += strlen(lua_typename(state, pargs[i].za_lua_type));
1174                 if (pargs[i + 1].za_name != NULL || kwargs[0].za_name != NULL)
1175                         msglen += 5; /* < + ( + )> + , */
1176                 else
1177                         msglen += 4; /* < + ( + )> */
1178         }
1179         for (i = 0; kwargs[i].za_name != NULL; i++) {
1180                 msglen += strlen(kwargs[i].za_name);
1181                 msglen += strlen(lua_typename(state, kwargs[i].za_lua_type));
1182                 if (kwargs[i + 1].za_name != NULL)
1183                         msglen += 4; /* =( + ) + , */
1184                 else
1185                         msglen += 3; /* =( + ) */
1186         }
1187
1188         if (msglen >= len)
1189                 (void) luaL_error(state, errmsg);
1190
1191         VERIFY3U(len, >, strlcat(errmsg, ": ", len));
1192         VERIFY3U(len, >, strlcat(errmsg, fname, len));
1193         VERIFY3U(len, >, strlcat(errmsg, "{", len));
1194         for (i = 0; pargs[i].za_name != NULL; i++) {
1195                 VERIFY3U(len, >, strlcat(errmsg, "<", len));
1196                 VERIFY3U(len, >, strlcat(errmsg, pargs[i].za_name, len));
1197                 VERIFY3U(len, >, strlcat(errmsg, "(", len));
1198                 VERIFY3U(len, >, strlcat(errmsg,
1199                     lua_typename(state, pargs[i].za_lua_type), len));
1200                 VERIFY3U(len, >, strlcat(errmsg, ")>", len));
1201                 if (pargs[i + 1].za_name != NULL || kwargs[0].za_name != NULL) {
1202                         VERIFY3U(len, >, strlcat(errmsg, ", ", len));
1203                 }
1204         }
1205         for (i = 0; kwargs[i].za_name != NULL; i++) {
1206                 VERIFY3U(len, >, strlcat(errmsg, kwargs[i].za_name, len));
1207                 VERIFY3U(len, >, strlcat(errmsg, "=(", len));
1208                 VERIFY3U(len, >, strlcat(errmsg,
1209                     lua_typename(state, kwargs[i].za_lua_type), len));
1210                 VERIFY3U(len, >, strlcat(errmsg, ")", len));
1211                 if (kwargs[i + 1].za_name != NULL) {
1212                         VERIFY3U(len, >, strlcat(errmsg, ", ", len));
1213                 }
1214         }
1215         VERIFY3U(len, >, strlcat(errmsg, "}", len));
1216
1217         (void) luaL_error(state, errmsg);
1218         panic("unreachable code");
1219 }
1220
1221 static void
1222 zcp_parse_table_args(lua_State *state, const char *fname,
1223     const zcp_arg_t *pargs, const zcp_arg_t *kwargs)
1224 {
1225         int i;
1226         int type;
1227
1228         for (i = 0; pargs[i].za_name != NULL; i++) {
1229                 /*
1230                  * Check the table for this positional argument, leaving it
1231                  * on the top of the stack once we finish validating it.
1232                  */
1233                 lua_pushinteger(state, i + 1);
1234                 lua_gettable(state, 1);
1235
1236                 type = lua_type(state, -1);
1237                 if (type == LUA_TNIL) {
1238                         zcp_args_error(state, fname, pargs, kwargs,
1239                             "too few arguments");
1240                         panic("unreachable code");
1241                 } else if (type != pargs[i].za_lua_type) {
1242                         zcp_args_error(state, fname, pargs, kwargs,
1243                             "arg %d wrong type (is '%s', expected '%s')",
1244                             i + 1, lua_typename(state, type),
1245                             lua_typename(state, pargs[i].za_lua_type));
1246                         panic("unreachable code");
1247                 }
1248
1249                 /*
1250                  * Remove the positional argument from the table.
1251                  */
1252                 lua_pushinteger(state, i + 1);
1253                 lua_pushnil(state);
1254                 lua_settable(state, 1);
1255         }
1256
1257         for (i = 0; kwargs[i].za_name != NULL; i++) {
1258                 /*
1259                  * Check the table for this keyword argument, which may be
1260                  * nil if it was omitted. Leave the value on the top of
1261                  * the stack after validating it.
1262                  */
1263                 lua_getfield(state, 1, kwargs[i].za_name);
1264
1265                 type = lua_type(state, -1);
1266                 if (type != LUA_TNIL && type != kwargs[i].za_lua_type) {
1267                         zcp_args_error(state, fname, pargs, kwargs,
1268                             "kwarg '%s' wrong type (is '%s', expected '%s')",
1269                             kwargs[i].za_name, lua_typename(state, type),
1270                             lua_typename(state, kwargs[i].za_lua_type));
1271                         panic("unreachable code");
1272                 }
1273
1274                 /*
1275                  * Remove the keyword argument from the table.
1276                  */
1277                 lua_pushnil(state);
1278                 lua_setfield(state, 1, kwargs[i].za_name);
1279         }
1280
1281         /*
1282          * Any entries remaining in the table are invalid inputs, print
1283          * an error message based on what the entry is.
1284          */
1285         lua_pushnil(state);
1286         if (lua_next(state, 1)) {
1287                 if (lua_isnumber(state, -2) && lua_tointeger(state, -2) > 0) {
1288                         zcp_args_error(state, fname, pargs, kwargs,
1289                             "too many positional arguments");
1290                 } else if (lua_isstring(state, -2)) {
1291                         zcp_args_error(state, fname, pargs, kwargs,
1292                             "invalid kwarg '%s'", lua_tostring(state, -2));
1293                 } else {
1294                         zcp_args_error(state, fname, pargs, kwargs,
1295                             "kwarg keys must be strings");
1296                 }
1297                 panic("unreachable code");
1298         }
1299
1300         lua_remove(state, 1);
1301 }
1302
1303 static void
1304 zcp_parse_pos_args(lua_State *state, const char *fname, const zcp_arg_t *pargs,
1305     const zcp_arg_t *kwargs)
1306 {
1307         int i;
1308         int type;
1309
1310         for (i = 0; pargs[i].za_name != NULL; i++) {
1311                 type = lua_type(state, i + 1);
1312                 if (type == LUA_TNONE) {
1313                         zcp_args_error(state, fname, pargs, kwargs,
1314                             "too few arguments");
1315                         panic("unreachable code");
1316                 } else if (type != pargs[i].za_lua_type) {
1317                         zcp_args_error(state, fname, pargs, kwargs,
1318                             "arg %d wrong type (is '%s', expected '%s')",
1319                             i + 1, lua_typename(state, type),
1320                             lua_typename(state, pargs[i].za_lua_type));
1321                         panic("unreachable code");
1322                 }
1323         }
1324         if (lua_gettop(state) != i) {
1325                 zcp_args_error(state, fname, pargs, kwargs,
1326                     "too many positional arguments");
1327                 panic("unreachable code");
1328         }
1329
1330         for (i = 0; kwargs[i].za_name != NULL; i++) {
1331                 lua_pushnil(state);
1332         }
1333 }
1334
1335 /*
1336  * Checks the current Lua stack against an expected set of positional and
1337  * keyword arguments. If the stack does not match the expected arguments
1338  * aborts the current channel program with a useful error message, otherwise
1339  * it re-arranges the stack so that it contains the positional arguments
1340  * followed by the keyword argument values in declaration order. Any missing
1341  * keyword argument will be represented by a nil value on the stack.
1342  *
1343  * If the stack contains exactly one argument of type LUA_TTABLE the curly
1344  * braces calling convention is assumed, otherwise the stack is parsed for
1345  * positional arguments only.
1346  *
1347  * This function should be used by every function callback. It should be called
1348  * before the callback manipulates the Lua stack as it assumes the stack
1349  * represents the function arguments.
1350  */
1351 void
1352 zcp_parse_args(lua_State *state, const char *fname, const zcp_arg_t *pargs,
1353     const zcp_arg_t *kwargs)
1354 {
1355         if (lua_gettop(state) == 1 && lua_istable(state, 1)) {
1356                 zcp_parse_table_args(state, fname, pargs, kwargs);
1357         } else {
1358                 zcp_parse_pos_args(state, fname, pargs, kwargs);
1359         }
1360 }