]> git.ipfire.org Git - thirdparty/kmod.git/blob - libkmod/libkmod-module.c
Lookup aliases in the modules.builtin.modinfo
[thirdparty/kmod.git] / libkmod / libkmod-module.c
1 /*
2 * libkmod - interface to kernel module operations
3 *
4 * Copyright (C) 2011-2013 ProFUSION embedded systems
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <assert.h>
21 #include <ctype.h>
22 #include <dirent.h>
23 #include <errno.h>
24 #include <fnmatch.h>
25 #include <inttypes.h>
26 #include <limits.h>
27 #include <stdarg.h>
28 #include <stddef.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <sys/mman.h>
34 #include <sys/stat.h>
35 #include <sys/syscall.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #ifdef HAVE_LINUX_MODULE_H
39 #include <linux/module.h>
40 #endif
41
42 #include <shared/util.h>
43
44 #include "libkmod.h"
45 #include "libkmod-internal.h"
46
47 /**
48 * SECTION:libkmod-module
49 * @short_description: operate on kernel modules
50 */
51
52 enum kmod_module_builtin {
53 KMOD_MODULE_BUILTIN_UNKNOWN,
54 KMOD_MODULE_BUILTIN_NO,
55 KMOD_MODULE_BUILTIN_YES,
56 };
57
58 /**
59 * kmod_module:
60 *
61 * Opaque object representing a module.
62 */
63 struct kmod_module {
64 struct kmod_ctx *ctx;
65 char *hashkey;
66 char *name;
67 char *path;
68 struct kmod_list *dep;
69 char *options;
70 const char *install_commands; /* owned by kmod_config */
71 const char *remove_commands; /* owned by kmod_config */
72 char *alias; /* only set if this module was created from an alias */
73 struct kmod_file *file;
74 int n_dep;
75 int refcount;
76 struct {
77 bool dep : 1;
78 bool options : 1;
79 bool install_commands : 1;
80 bool remove_commands : 1;
81 } init;
82
83 /*
84 * mark if module is builtin, i.e. it's present on modules.builtin
85 * file. This is set as soon as it is needed or as soon as we know
86 * about it, i.e. the module was created from builtin lookup.
87 */
88 enum kmod_module_builtin builtin;
89
90 /*
91 * private field used by kmod_module_get_probe_list() to detect
92 * dependency loops
93 */
94 bool visited : 1;
95
96 /*
97 * set by kmod_module_get_probe_list: indicates for probe_insert()
98 * whether the module's command and softdep should be ignored
99 */
100 bool ignorecmd : 1;
101
102 /*
103 * set by kmod_module_get_probe_list: indicates whether this is the
104 * module the user asked for or its dependency, or whether this
105 * is a softdep only
106 */
107 bool required : 1;
108 };
109
110 static inline const char *path_join(const char *path, size_t prefixlen,
111 char buf[PATH_MAX])
112 {
113 size_t pathlen;
114
115 if (path[0] == '/')
116 return path;
117
118 pathlen = strlen(path);
119 if (prefixlen + pathlen + 1 >= PATH_MAX)
120 return NULL;
121
122 memcpy(buf + prefixlen, path, pathlen + 1);
123 return buf;
124 }
125
126 static inline bool module_is_inkernel(struct kmod_module *mod)
127 {
128 int state = kmod_module_get_initstate(mod);
129
130 if (state == KMOD_MODULE_LIVE ||
131 state == KMOD_MODULE_BUILTIN)
132 return true;
133
134 return false;
135 }
136
137 int kmod_module_parse_depline(struct kmod_module *mod, char *line)
138 {
139 struct kmod_ctx *ctx = mod->ctx;
140 struct kmod_list *list = NULL;
141 const char *dirname;
142 char buf[PATH_MAX];
143 char *p, *saveptr;
144 int err = 0, n = 0;
145 size_t dirnamelen;
146
147 if (mod->init.dep)
148 return mod->n_dep;
149 assert(mod->dep == NULL);
150 mod->init.dep = true;
151
152 p = strchr(line, ':');
153 if (p == NULL)
154 return 0;
155
156 *p = '\0';
157 dirname = kmod_get_dirname(mod->ctx);
158 dirnamelen = strlen(dirname);
159 if (dirnamelen + 2 >= PATH_MAX)
160 return 0;
161
162 memcpy(buf, dirname, dirnamelen);
163 buf[dirnamelen] = '/';
164 dirnamelen++;
165 buf[dirnamelen] = '\0';
166
167 if (mod->path == NULL) {
168 const char *str = path_join(line, dirnamelen, buf);
169 if (str == NULL)
170 return 0;
171 mod->path = strdup(str);
172 if (mod->path == NULL)
173 return 0;
174 }
175
176 p++;
177 for (p = strtok_r(p, " \t", &saveptr); p != NULL;
178 p = strtok_r(NULL, " \t", &saveptr)) {
179 struct kmod_module *depmod = NULL;
180 const char *path;
181
182 path = path_join(p, dirnamelen, buf);
183 if (path == NULL) {
184 ERR(ctx, "could not join path '%s' and '%s'.\n",
185 dirname, p);
186 goto fail;
187 }
188
189 err = kmod_module_new_from_path(ctx, path, &depmod);
190 if (err < 0) {
191 ERR(ctx, "ctx=%p path=%s error=%s\n",
192 ctx, path, strerror(-err));
193 goto fail;
194 }
195
196 DBG(ctx, "add dep: %s\n", path);
197
198 list = kmod_list_prepend(list, depmod);
199 n++;
200 }
201
202 DBG(ctx, "%d dependencies for %s\n", n, mod->name);
203
204 mod->dep = list;
205 mod->n_dep = n;
206 return n;
207
208 fail:
209 kmod_module_unref_list(list);
210 mod->init.dep = false;
211 return err;
212 }
213
214 void kmod_module_set_visited(struct kmod_module *mod, bool visited)
215 {
216 mod->visited = visited;
217 }
218
219 void kmod_module_set_builtin(struct kmod_module *mod, bool builtin)
220 {
221 mod->builtin =
222 builtin ? KMOD_MODULE_BUILTIN_YES : KMOD_MODULE_BUILTIN_NO;
223 }
224
225 void kmod_module_set_required(struct kmod_module *mod, bool required)
226 {
227 mod->required = required;
228 }
229
230 bool kmod_module_is_builtin(struct kmod_module *mod)
231 {
232 if (mod->builtin == KMOD_MODULE_BUILTIN_UNKNOWN) {
233 kmod_module_set_builtin(mod,
234 kmod_lookup_alias_is_builtin(mod->ctx, mod->name));
235 }
236
237 return mod->builtin == KMOD_MODULE_BUILTIN_YES;
238 }
239 /*
240 * Memory layout with alias:
241 *
242 * struct kmod_module {
243 * hashkey -----.
244 * alias -----. |
245 * name ----. | |
246 * } | | |
247 * name <----------' | |
248 * alias <-----------' |
249 * name\alias <--------'
250 *
251 * Memory layout without alias:
252 *
253 * struct kmod_module {
254 * hashkey ---.
255 * alias -----|----> NULL
256 * name ----. |
257 * } | |
258 * name <----------'-'
259 *
260 * @key is "name\alias" or "name" (in which case alias == NULL)
261 */
262 static int kmod_module_new(struct kmod_ctx *ctx, const char *key,
263 const char *name, size_t namelen,
264 const char *alias, size_t aliaslen,
265 struct kmod_module **mod)
266 {
267 struct kmod_module *m;
268 size_t keylen;
269
270 m = kmod_pool_get_module(ctx, key);
271 if (m != NULL) {
272 *mod = kmod_module_ref(m);
273 return 0;
274 }
275
276 if (alias == NULL)
277 keylen = namelen;
278 else
279 keylen = namelen + aliaslen + 1;
280
281 m = malloc(sizeof(*m) + (alias == NULL ? 1 : 2) * (keylen + 1));
282 if (m == NULL)
283 return -ENOMEM;
284
285 memset(m, 0, sizeof(*m));
286
287 m->ctx = kmod_ref(ctx);
288 m->name = (char *)m + sizeof(*m);
289 memcpy(m->name, key, keylen + 1);
290 if (alias == NULL) {
291 m->hashkey = m->name;
292 m->alias = NULL;
293 } else {
294 m->name[namelen] = '\0';
295 m->alias = m->name + namelen + 1;
296 m->hashkey = m->name + keylen + 1;
297 memcpy(m->hashkey, key, keylen + 1);
298 }
299
300 m->refcount = 1;
301 kmod_pool_add_module(ctx, m, m->hashkey);
302 *mod = m;
303
304 return 0;
305 }
306
307 /**
308 * kmod_module_new_from_name:
309 * @ctx: kmod library context
310 * @name: name of the module
311 * @mod: where to save the created struct kmod_module
312 *
313 * Create a new struct kmod_module using the module name. @name can not be an
314 * alias, file name or anything else; it must be a module name. There's no
315 * check if the module exists in the system.
316 *
317 * This function is also used internally by many others that return a new
318 * struct kmod_module or a new list of modules.
319 *
320 * The initial refcount is 1, and needs to be decremented to release the
321 * resources of the kmod_module. Since libkmod keeps track of all
322 * kmod_modules created, they are all released upon @ctx destruction too. Do
323 * not unref @ctx before all the desired operations with the returned
324 * kmod_module are done.
325 *
326 * Returns: 0 on success or < 0 otherwise. It fails if name is not a valid
327 * module name or if memory allocation failed.
328 */
329 KMOD_EXPORT int kmod_module_new_from_name(struct kmod_ctx *ctx,
330 const char *name,
331 struct kmod_module **mod)
332 {
333 size_t namelen;
334 char name_norm[PATH_MAX];
335
336 if (ctx == NULL || name == NULL || mod == NULL)
337 return -ENOENT;
338
339 modname_normalize(name, name_norm, &namelen);
340
341 return kmod_module_new(ctx, name_norm, name_norm, namelen, NULL, 0, mod);
342 }
343
344 int kmod_module_new_from_alias(struct kmod_ctx *ctx, const char *alias,
345 const char *name, struct kmod_module **mod)
346 {
347 int err;
348 char key[PATH_MAX];
349 size_t namelen = strlen(name);
350 size_t aliaslen = strlen(alias);
351
352 if (namelen + aliaslen + 2 > PATH_MAX)
353 return -ENAMETOOLONG;
354
355 memcpy(key, name, namelen);
356 memcpy(key + namelen + 1, alias, aliaslen + 1);
357 key[namelen] = '\\';
358
359 err = kmod_module_new(ctx, key, name, namelen, alias, aliaslen, mod);
360 if (err < 0)
361 return err;
362
363 return 0;
364 }
365
366 /**
367 * kmod_module_new_from_path:
368 * @ctx: kmod library context
369 * @path: path where to find the given module
370 * @mod: where to save the created struct kmod_module
371 *
372 * Create a new struct kmod_module using the module path. @path must be an
373 * existent file with in the filesystem and must be accessible to libkmod.
374 *
375 * The initial refcount is 1, and needs to be decremented to release the
376 * resources of the kmod_module. Since libkmod keeps track of all
377 * kmod_modules created, they are all released upon @ctx destruction too. Do
378 * not unref @ctx before all the desired operations with the returned
379 * kmod_module are done.
380 *
381 * If @path is relative, it's treated as relative to the current working
382 * directory. Otherwise, give an absolute path.
383 *
384 * Returns: 0 on success or < 0 otherwise. It fails if file does not exist, if
385 * it's not a valid file for a kmod_module or if memory allocation failed.
386 */
387 KMOD_EXPORT int kmod_module_new_from_path(struct kmod_ctx *ctx,
388 const char *path,
389 struct kmod_module **mod)
390 {
391 struct kmod_module *m;
392 int err;
393 struct stat st;
394 char name[PATH_MAX];
395 char *abspath;
396 size_t namelen;
397
398 if (ctx == NULL || path == NULL || mod == NULL)
399 return -ENOENT;
400
401 abspath = path_make_absolute_cwd(path);
402 if (abspath == NULL) {
403 DBG(ctx, "no absolute path for %s\n", path);
404 return -ENOMEM;
405 }
406
407 err = stat(abspath, &st);
408 if (err < 0) {
409 err = -errno;
410 DBG(ctx, "stat %s: %s\n", path, strerror(errno));
411 free(abspath);
412 return err;
413 }
414
415 if (path_to_modname(path, name, &namelen) == NULL) {
416 DBG(ctx, "could not get modname from path %s\n", path);
417 free(abspath);
418 return -ENOENT;
419 }
420
421 m = kmod_pool_get_module(ctx, name);
422 if (m != NULL) {
423 if (m->path == NULL)
424 m->path = abspath;
425 else if (streq(m->path, abspath))
426 free(abspath);
427 else {
428 ERR(ctx, "kmod_module '%s' already exists with different path: new-path='%s' old-path='%s'\n",
429 name, abspath, m->path);
430 free(abspath);
431 return -EEXIST;
432 }
433
434 *mod = kmod_module_ref(m);
435 return 0;
436 }
437
438 err = kmod_module_new(ctx, name, name, namelen, NULL, 0, &m);
439 if (err < 0) {
440 free(abspath);
441 return err;
442 }
443
444 m->path = abspath;
445 *mod = m;
446
447 return 0;
448 }
449
450 /**
451 * kmod_module_unref:
452 * @mod: kmod module
453 *
454 * Drop a reference of the kmod module. If the refcount reaches zero, its
455 * resources are released.
456 *
457 * Returns: NULL if @mod is NULL or if the module was released. Otherwise it
458 * returns the passed @mod with its refcount decremented.
459 */
460 KMOD_EXPORT struct kmod_module *kmod_module_unref(struct kmod_module *mod)
461 {
462 if (mod == NULL)
463 return NULL;
464
465 if (--mod->refcount > 0)
466 return mod;
467
468 DBG(mod->ctx, "kmod_module %p released\n", mod);
469
470 kmod_pool_del_module(mod->ctx, mod, mod->hashkey);
471 kmod_module_unref_list(mod->dep);
472
473 if (mod->file)
474 kmod_file_unref(mod->file);
475
476 kmod_unref(mod->ctx);
477 free(mod->options);
478 free(mod->path);
479 free(mod);
480 return NULL;
481 }
482
483 /**
484 * kmod_module_ref:
485 * @mod: kmod module
486 *
487 * Take a reference of the kmod module, incrementing its refcount.
488 *
489 * Returns: the passed @module with its refcount incremented.
490 */
491 KMOD_EXPORT struct kmod_module *kmod_module_ref(struct kmod_module *mod)
492 {
493 if (mod == NULL)
494 return NULL;
495
496 mod->refcount++;
497
498 return mod;
499 }
500
501 #define CHECK_ERR_AND_FINISH(_err, _label_err, _list, label_finish) \
502 do { \
503 if ((_err) < 0) \
504 goto _label_err; \
505 if (*(_list) != NULL) \
506 goto finish; \
507 } while (0)
508
509 /**
510 * kmod_module_new_from_lookup:
511 * @ctx: kmod library context
512 * @given_alias: alias to look for
513 * @list: an empty list where to save the list of modules matching
514 * @given_alias
515 *
516 * Create a new list of kmod modules using an alias or module name and lookup
517 * libkmod's configuration files and indexes in order to find the module.
518 * Once it's found in one of the places, it stops searching and create the
519 * list of modules that is saved in @list.
520 *
521 * The search order is: 1. aliases in configuration file; 2. module names in
522 * modules.dep index; 3. symbol aliases in modules.symbols index; 4. aliases
523 * in modules.alias index.
524 *
525 * The initial refcount is 1, and needs to be decremented to release the
526 * resources of the kmod_module. The returned @list must be released by
527 * calling kmod_module_unref_list(). Since libkmod keeps track of all
528 * kmod_modules created, they are all released upon @ctx destruction too. Do
529 * not unref @ctx before all the desired operations with the returned list are
530 * completed.
531 *
532 * Returns: 0 on success or < 0 otherwise. It fails if any of the lookup
533 * methods failed, which is basically due to memory allocation fail. If module
534 * is not found, it still returns 0, but @list is an empty list.
535 */
536 KMOD_EXPORT int kmod_module_new_from_lookup(struct kmod_ctx *ctx,
537 const char *given_alias,
538 struct kmod_list **list)
539 {
540 int err;
541 char alias[PATH_MAX];
542
543 if (ctx == NULL || given_alias == NULL)
544 return -ENOENT;
545
546 if (list == NULL || *list != NULL) {
547 ERR(ctx, "An empty list is needed to create lookup\n");
548 return -ENOSYS;
549 }
550
551 if (alias_normalize(given_alias, alias, NULL) < 0) {
552 DBG(ctx, "invalid alias: %s\n", given_alias);
553 return -EINVAL;
554 }
555
556 DBG(ctx, "input alias=%s, normalized=%s\n", given_alias, alias);
557
558 /* Aliases from config file override all the others */
559 err = kmod_lookup_alias_from_config(ctx, alias, list);
560 CHECK_ERR_AND_FINISH(err, fail, list, finish);
561
562 DBG(ctx, "lookup modules.dep %s\n", alias);
563 err = kmod_lookup_alias_from_moddep_file(ctx, alias, list);
564 CHECK_ERR_AND_FINISH(err, fail, list, finish);
565
566 DBG(ctx, "lookup modules.symbols %s\n", alias);
567 err = kmod_lookup_alias_from_symbols_file(ctx, alias, list);
568 CHECK_ERR_AND_FINISH(err, fail, list, finish);
569
570 DBG(ctx, "lookup install and remove commands %s\n", alias);
571 err = kmod_lookup_alias_from_commands(ctx, alias, list);
572 CHECK_ERR_AND_FINISH(err, fail, list, finish);
573
574 DBG(ctx, "lookup modules.aliases %s\n", alias);
575 err = kmod_lookup_alias_from_aliases_file(ctx, alias, list);
576 CHECK_ERR_AND_FINISH(err, fail, list, finish);
577
578 DBG(ctx, "lookup modules.builtin.modinfo %s\n", alias);
579 err = kmod_lookup_alias_from_kernel_builtin_file(ctx, alias, list);
580 CHECK_ERR_AND_FINISH(err, fail, list, finish);
581
582 if (err == 0) {
583 DBG(ctx, "lookup modules.builtin %s\n", alias);
584 err = kmod_lookup_alias_from_builtin_file(ctx, alias, list);
585 CHECK_ERR_AND_FINISH(err, fail, list, finish);
586 }
587
588 finish:
589 DBG(ctx, "lookup %s=%d, list=%p\n", alias, err, *list);
590 return err;
591 fail:
592 DBG(ctx, "Failed to lookup %s\n", alias);
593 kmod_module_unref_list(*list);
594 *list = NULL;
595 return err;
596 }
597 #undef CHECK_ERR_AND_FINISH
598
599 /**
600 * kmod_module_unref_list:
601 * @list: list of kmod modules
602 *
603 * Drop a reference of each kmod module in @list and releases the resources
604 * taken by the list itself.
605 *
606 * Returns: 0
607 */
608 KMOD_EXPORT int kmod_module_unref_list(struct kmod_list *list)
609 {
610 for (; list != NULL; list = kmod_list_remove(list))
611 kmod_module_unref(list->data);
612
613 return 0;
614 }
615
616 /**
617 * kmod_module_get_filtered_blacklist:
618 * @ctx: kmod library context
619 * @input: list of kmod_module to be filtered with blacklist
620 * @output: where to save the new list
621 *
622 * This function should not be used. Use kmod_module_apply_filter instead.
623 *
624 * Given a list @input, this function filter it out with config's blacklist
625 * and save it in @output.
626 *
627 * Returns: 0 on success or < 0 otherwise. @output is saved with the updated
628 * list.
629 */
630 KMOD_EXPORT int kmod_module_get_filtered_blacklist(const struct kmod_ctx *ctx,
631 const struct kmod_list *input,
632 struct kmod_list **output)
633 {
634 return kmod_module_apply_filter(ctx, KMOD_FILTER_BLACKLIST, input, output);
635 }
636
637 static const struct kmod_list *module_get_dependencies_noref(const struct kmod_module *mod)
638 {
639 if (!mod->init.dep) {
640 /* lazy init */
641 char *line = kmod_search_moddep(mod->ctx, mod->name);
642
643 if (line == NULL)
644 return NULL;
645
646 kmod_module_parse_depline((struct kmod_module *)mod, line);
647 free(line);
648
649 if (!mod->init.dep)
650 return NULL;
651 }
652
653 return mod->dep;
654 }
655
656 /**
657 * kmod_module_get_dependencies:
658 * @mod: kmod module
659 *
660 * Search the modules.dep index to find the dependencies of the given @mod.
661 * The result is cached in @mod, so subsequent calls to this function will
662 * return the already searched list of modules.
663 *
664 * Returns: NULL on failure. Otherwise it returns a list of kmod modules
665 * that can be released by calling kmod_module_unref_list().
666 */
667 KMOD_EXPORT struct kmod_list *kmod_module_get_dependencies(const struct kmod_module *mod)
668 {
669 struct kmod_list *l, *l_new, *list_new = NULL;
670
671 if (mod == NULL)
672 return NULL;
673
674 module_get_dependencies_noref(mod);
675
676 kmod_list_foreach(l, mod->dep) {
677 l_new = kmod_list_append(list_new, kmod_module_ref(l->data));
678 if (l_new == NULL) {
679 kmod_module_unref(l->data);
680 goto fail;
681 }
682
683 list_new = l_new;
684 }
685
686 return list_new;
687
688 fail:
689 ERR(mod->ctx, "out of memory\n");
690 kmod_module_unref_list(list_new);
691 return NULL;
692 }
693
694 /**
695 * kmod_module_get_module:
696 * @entry: an entry in a list of kmod modules.
697 *
698 * Get the kmod module of this @entry in the list, increasing its refcount.
699 * After it's used, unref it. Since the refcount is incremented upon return,
700 * you still have to call kmod_module_unref_list() to release the list of kmod
701 * modules.
702 *
703 * Returns: NULL on failure or the kmod_module contained in this list entry
704 * with its refcount incremented.
705 */
706 KMOD_EXPORT struct kmod_module *kmod_module_get_module(const struct kmod_list *entry)
707 {
708 if (entry == NULL)
709 return NULL;
710
711 return kmod_module_ref(entry->data);
712 }
713
714 /**
715 * kmod_module_get_name:
716 * @mod: kmod module
717 *
718 * Get the name of this kmod module. Name is always available, independently
719 * if it was created by kmod_module_new_from_name() or another function and
720 * it's always normalized (dashes are replaced with underscores).
721 *
722 * Returns: the name of this kmod module.
723 */
724 KMOD_EXPORT const char *kmod_module_get_name(const struct kmod_module *mod)
725 {
726 if (mod == NULL)
727 return NULL;
728
729 return mod->name;
730 }
731
732 /**
733 * kmod_module_get_path:
734 * @mod: kmod module
735 *
736 * Get the path of this kmod module. If this kmod module was not created by
737 * path, it can search the modules.dep index in order to find out the module
738 * under context's dirname.
739 *
740 * Returns: the path of this kmod module or NULL if such information is not
741 * available.
742 */
743 KMOD_EXPORT const char *kmod_module_get_path(const struct kmod_module *mod)
744 {
745 char *line;
746
747 if (mod == NULL)
748 return NULL;
749
750 DBG(mod->ctx, "name='%s' path='%s'\n", mod->name, mod->path);
751
752 if (mod->path != NULL)
753 return mod->path;
754 if (mod->init.dep)
755 return NULL;
756
757 /* lazy init */
758 line = kmod_search_moddep(mod->ctx, mod->name);
759 if (line == NULL)
760 return NULL;
761
762 kmod_module_parse_depline((struct kmod_module *) mod, line);
763 free(line);
764
765 return mod->path;
766 }
767
768
769 extern long delete_module(const char *name, unsigned int flags);
770
771 /**
772 * kmod_module_remove_module:
773 * @mod: kmod module
774 * @flags: flags to pass to Linux kernel when removing the module. The only valid flag is
775 * KMOD_REMOVE_FORCE: force remove module regardless if it's still in
776 * use by a kernel subsystem or other process;
777 * KMOD_REMOVE_NOWAIT is always enforced, causing us to pass O_NONBLOCK to
778 * delete_module(2).
779 *
780 * Remove a module from Linux kernel.
781 *
782 * Returns: 0 on success or < 0 on failure.
783 */
784 KMOD_EXPORT int kmod_module_remove_module(struct kmod_module *mod,
785 unsigned int flags)
786 {
787 int err;
788
789 if (mod == NULL)
790 return -ENOENT;
791
792 /* Filter out other flags and force ONONBLOCK */
793 flags &= KMOD_REMOVE_FORCE;
794 flags |= KMOD_REMOVE_NOWAIT;
795
796 err = delete_module(mod->name, flags);
797 if (err != 0) {
798 err = -errno;
799 ERR(mod->ctx, "could not remove '%s': %m\n", mod->name);
800 }
801
802 return err;
803 }
804
805 extern long init_module(const void *mem, unsigned long len, const char *args);
806
807 /**
808 * kmod_module_insert_module:
809 * @mod: kmod module
810 * @flags: flags are not passed to Linux Kernel, but instead they dictate the
811 * behavior of this function, valid flags are
812 * KMOD_INSERT_FORCE_VERMAGIC: ignore kernel version magic;
813 * KMOD_INSERT_FORCE_MODVERSION: ignore symbol version hashes.
814 * @options: module's options to pass to Linux Kernel.
815 *
816 * Insert a module in Linux kernel. It opens the file pointed by @mod,
817 * mmap'ing it and passing to kernel.
818 *
819 * Returns: 0 on success or < 0 on failure. If module is already loaded it
820 * returns -EEXIST.
821 */
822 KMOD_EXPORT int kmod_module_insert_module(struct kmod_module *mod,
823 unsigned int flags,
824 const char *options)
825 {
826 int err;
827 const void *mem;
828 off_t size;
829 struct kmod_elf *elf;
830 const char *path;
831 const char *args = options ? options : "";
832
833 if (mod == NULL)
834 return -ENOENT;
835
836 path = kmod_module_get_path(mod);
837 if (path == NULL) {
838 ERR(mod->ctx, "could not find module by name='%s'\n", mod->name);
839 return -ENOENT;
840 }
841
842 if (!mod->file) {
843 mod->file = kmod_file_open(mod->ctx, path);
844 if (mod->file == NULL) {
845 err = -errno;
846 return err;
847 }
848 }
849
850 if (kmod_file_get_direct(mod->file)) {
851 unsigned int kernel_flags = 0;
852
853 if (flags & KMOD_INSERT_FORCE_VERMAGIC)
854 kernel_flags |= MODULE_INIT_IGNORE_VERMAGIC;
855 if (flags & KMOD_INSERT_FORCE_MODVERSION)
856 kernel_flags |= MODULE_INIT_IGNORE_MODVERSIONS;
857
858 err = finit_module(kmod_file_get_fd(mod->file), args, kernel_flags);
859 if (err == 0 || errno != ENOSYS)
860 goto init_finished;
861 }
862
863 if (flags & (KMOD_INSERT_FORCE_VERMAGIC | KMOD_INSERT_FORCE_MODVERSION)) {
864 elf = kmod_file_get_elf(mod->file);
865 if (elf == NULL) {
866 err = -errno;
867 return err;
868 }
869
870 if (flags & KMOD_INSERT_FORCE_MODVERSION) {
871 err = kmod_elf_strip_section(elf, "__versions");
872 if (err < 0)
873 INFO(mod->ctx, "Failed to strip modversion: %s\n", strerror(-err));
874 }
875
876 if (flags & KMOD_INSERT_FORCE_VERMAGIC) {
877 err = kmod_elf_strip_vermagic(elf);
878 if (err < 0)
879 INFO(mod->ctx, "Failed to strip vermagic: %s\n", strerror(-err));
880 }
881
882 mem = kmod_elf_get_memory(elf);
883 } else {
884 mem = kmod_file_get_contents(mod->file);
885 }
886 size = kmod_file_get_size(mod->file);
887
888 err = init_module(mem, size, args);
889 init_finished:
890 if (err < 0) {
891 err = -errno;
892 INFO(mod->ctx, "Failed to insert module '%s': %m\n", path);
893 }
894 return err;
895 }
896
897 static bool module_is_blacklisted(struct kmod_module *mod)
898 {
899 struct kmod_ctx *ctx = mod->ctx;
900 const struct kmod_config *config = kmod_get_config(ctx);
901 const struct kmod_list *bl = config->blacklists;
902 const struct kmod_list *l;
903
904 kmod_list_foreach(l, bl) {
905 const char *modname = kmod_blacklist_get_modname(l);
906
907 if (streq(modname, mod->name))
908 return true;
909 }
910
911 return false;
912 }
913
914 /**
915 * kmod_module_apply_filter
916 * @ctx: kmod library context
917 * @filter_type: bitmask to filter modules out, valid types are
918 * KMOD_FILTER_BLACKLIST: filter modules in blacklist out;
919 * KMOD_FILTER_BUILTIN: filter builtin modules out.
920 * @input: list of kmod_module to be filtered
921 * @output: where to save the new list
922 *
923 * Given a list @input, this function filter it out by the filter mask
924 * and save it in @output.
925 *
926 * Returns: 0 on success or < 0 otherwise. @output is saved with the updated
927 * list.
928 */
929 KMOD_EXPORT int kmod_module_apply_filter(const struct kmod_ctx *ctx,
930 enum kmod_filter filter_type,
931 const struct kmod_list *input,
932 struct kmod_list **output)
933 {
934 const struct kmod_list *li;
935
936 if (ctx == NULL || output == NULL)
937 return -ENOENT;
938
939 *output = NULL;
940 if (input == NULL)
941 return 0;
942
943 kmod_list_foreach(li, input) {
944 struct kmod_module *mod = li->data;
945 struct kmod_list *node;
946
947 if ((filter_type & KMOD_FILTER_BLACKLIST) &&
948 module_is_blacklisted(mod))
949 continue;
950
951 if ((filter_type & KMOD_FILTER_BUILTIN)
952 && kmod_module_is_builtin(mod))
953 continue;
954
955 node = kmod_list_append(*output, mod);
956 if (node == NULL)
957 goto fail;
958
959 *output = node;
960 kmod_module_ref(mod);
961 }
962
963 return 0;
964
965 fail:
966 kmod_module_unref_list(*output);
967 *output = NULL;
968 return -ENOMEM;
969 }
970
971 static int command_do(struct kmod_module *mod, const char *type,
972 const char *cmd)
973 {
974 const char *modname = kmod_module_get_name(mod);
975 int err;
976
977 DBG(mod->ctx, "%s %s\n", type, cmd);
978
979 setenv("MODPROBE_MODULE", modname, 1);
980 err = system(cmd);
981 unsetenv("MODPROBE_MODULE");
982
983 if (err == -1 || WEXITSTATUS(err)) {
984 ERR(mod->ctx, "Error running %s command for %s\n",
985 type, modname);
986 if (err != -1)
987 err = -WEXITSTATUS(err);
988 }
989
990 return err;
991 }
992
993 struct probe_insert_cb {
994 int (*run_install)(struct kmod_module *m, const char *cmd, void *data);
995 void *data;
996 };
997
998 static int module_do_install_commands(struct kmod_module *mod,
999 const char *options,
1000 struct probe_insert_cb *cb)
1001 {
1002 const char *command = kmod_module_get_install_commands(mod);
1003 char *p;
1004 _cleanup_free_ char *cmd;
1005 int err;
1006 size_t cmdlen, options_len, varlen;
1007
1008 assert(command);
1009
1010 if (options == NULL)
1011 options = "";
1012
1013 options_len = strlen(options);
1014 cmdlen = strlen(command);
1015 varlen = sizeof("$CMDLINE_OPTS") - 1;
1016
1017 cmd = memdup(command, cmdlen + 1);
1018 if (cmd == NULL)
1019 return -ENOMEM;
1020
1021 while ((p = strstr(cmd, "$CMDLINE_OPTS")) != NULL) {
1022 size_t prefixlen = p - cmd;
1023 size_t suffixlen = cmdlen - prefixlen - varlen;
1024 size_t slen = cmdlen - varlen + options_len;
1025 char *suffix = p + varlen;
1026 char *s = malloc(slen + 1);
1027 if (!s)
1028 return -ENOMEM;
1029
1030 memcpy(s, cmd, p - cmd);
1031 memcpy(s + prefixlen, options, options_len);
1032 memcpy(s + prefixlen + options_len, suffix, suffixlen);
1033 s[slen] = '\0';
1034
1035 free(cmd);
1036 cmd = s;
1037 cmdlen = slen;
1038 }
1039
1040 if (cb->run_install != NULL)
1041 err = cb->run_install(mod, cmd, cb->data);
1042 else
1043 err = command_do(mod, "install", cmd);
1044
1045 return err;
1046 }
1047
1048 static char *module_options_concat(const char *opt, const char *xopt)
1049 {
1050 // TODO: we might need to check if xopt overrides options on opt
1051 size_t optlen = opt == NULL ? 0 : strlen(opt);
1052 size_t xoptlen = xopt == NULL ? 0 : strlen(xopt);
1053 char *r;
1054
1055 if (optlen == 0 && xoptlen == 0)
1056 return NULL;
1057
1058 r = malloc(optlen + xoptlen + 2);
1059
1060 if (opt != NULL) {
1061 memcpy(r, opt, optlen);
1062 r[optlen] = ' ';
1063 optlen++;
1064 }
1065
1066 if (xopt != NULL)
1067 memcpy(r + optlen, xopt, xoptlen);
1068
1069 r[optlen + xoptlen] = '\0';
1070
1071 return r;
1072 }
1073
1074 static int __kmod_module_get_probe_list(struct kmod_module *mod,
1075 bool required,
1076 bool ignorecmd,
1077 struct kmod_list **list);
1078
1079 /* re-entrant */
1080 static int __kmod_module_fill_softdep(struct kmod_module *mod,
1081 struct kmod_list **list)
1082 {
1083 struct kmod_list *pre = NULL, *post = NULL, *l;
1084 int err;
1085
1086 err = kmod_module_get_softdeps(mod, &pre, &post);
1087 if (err < 0) {
1088 ERR(mod->ctx, "could not get softdep: %s\n",
1089 strerror(-err));
1090 goto fail;
1091 }
1092
1093 kmod_list_foreach(l, pre) {
1094 struct kmod_module *m = l->data;
1095 err = __kmod_module_get_probe_list(m, false, false, list);
1096 if (err < 0)
1097 goto fail;
1098 }
1099
1100 l = kmod_list_append(*list, kmod_module_ref(mod));
1101 if (l == NULL) {
1102 kmod_module_unref(mod);
1103 err = -ENOMEM;
1104 goto fail;
1105 }
1106 *list = l;
1107 mod->ignorecmd = (pre != NULL || post != NULL);
1108
1109 kmod_list_foreach(l, post) {
1110 struct kmod_module *m = l->data;
1111 err = __kmod_module_get_probe_list(m, false, false, list);
1112 if (err < 0)
1113 goto fail;
1114 }
1115
1116 fail:
1117 kmod_module_unref_list(pre);
1118 kmod_module_unref_list(post);
1119
1120 return err;
1121 }
1122
1123 /* re-entrant */
1124 static int __kmod_module_get_probe_list(struct kmod_module *mod,
1125 bool required,
1126 bool ignorecmd,
1127 struct kmod_list **list)
1128 {
1129 struct kmod_list *dep, *l;
1130 int err = 0;
1131
1132 if (mod->visited) {
1133 DBG(mod->ctx, "Ignore module '%s': already visited\n",
1134 mod->name);
1135 return 0;
1136 }
1137 mod->visited = true;
1138
1139 dep = kmod_module_get_dependencies(mod);
1140 if (required) {
1141 /*
1142 * Called from kmod_module_probe_insert_module(); set the
1143 * ->required flag on mod and all its dependencies before
1144 * they are possibly visited through some softdeps.
1145 */
1146 mod->required = true;
1147 kmod_list_foreach(l, dep) {
1148 struct kmod_module *m = l->data;
1149 m->required = true;
1150 }
1151 }
1152
1153 kmod_list_foreach(l, dep) {
1154 struct kmod_module *m = l->data;
1155 err = __kmod_module_fill_softdep(m, list);
1156 if (err < 0)
1157 goto finish;
1158 }
1159
1160 if (ignorecmd) {
1161 l = kmod_list_append(*list, kmod_module_ref(mod));
1162 if (l == NULL) {
1163 kmod_module_unref(mod);
1164 err = -ENOMEM;
1165 goto finish;
1166 }
1167 *list = l;
1168 mod->ignorecmd = true;
1169 } else
1170 err = __kmod_module_fill_softdep(mod, list);
1171
1172 finish:
1173 kmod_module_unref_list(dep);
1174 return err;
1175 }
1176
1177 static int kmod_module_get_probe_list(struct kmod_module *mod,
1178 bool ignorecmd,
1179 struct kmod_list **list)
1180 {
1181 int err;
1182
1183 assert(mod != NULL);
1184 assert(list != NULL && *list == NULL);
1185
1186 /*
1187 * Make sure we don't get screwed by previous calls to this function
1188 */
1189 kmod_set_modules_visited(mod->ctx, false);
1190 kmod_set_modules_required(mod->ctx, false);
1191
1192 err = __kmod_module_get_probe_list(mod, true, ignorecmd, list);
1193 if (err < 0) {
1194 kmod_module_unref_list(*list);
1195 *list = NULL;
1196 }
1197
1198 return err;
1199 }
1200
1201 /**
1202 * kmod_module_probe_insert_module:
1203 * @mod: kmod module
1204 * @flags: flags are not passed to Linux Kernel, but instead they dictate the
1205 * behavior of this function, valid flags are
1206 * KMOD_PROBE_FORCE_VERMAGIC: ignore kernel version magic;
1207 * KMOD_PROBE_FORCE_MODVERSION: ignore symbol version hashes;
1208 * KMOD_PROBE_IGNORE_COMMAND: whether the probe should ignore install
1209 * commands and softdeps configured in the system;
1210 * KMOD_PROBE_IGNORE_LOADED: do not check whether the module is already
1211 * live in kernel or not;
1212 * KMOD_PROBE_DRY_RUN: dry run, do not insert module, just call the
1213 * associated callback function;
1214 * KMOD_PROBE_FAIL_ON_LOADED: if KMOD_PROBE_IGNORE_LOADED is not specified
1215 * and the module is already live in kernel, the function will fail if this
1216 * flag is specified;
1217 * KMOD_PROBE_APPLY_BLACKLIST_ALL: probe will apply KMOD_FILTER_BLACKLIST
1218 * filter to this module and its dependencies. If any of the dependencies (or
1219 * the module) is blacklisted, the probe will fail, unless the blacklisted
1220 * module is already live in kernel;
1221 * KMOD_PROBE_APPLY_BLACKLIST: probe will fail if the module is blacklisted;
1222 * KMOD_PROBE_APPLY_BLACKLIST_ALIAS_ONLY: probe will fail if the module is an
1223 * alias and is blacklisted.
1224 * @extra_options: module's options to pass to Linux Kernel. It applies only
1225 * to @mod, not to its dependencies.
1226 * @run_install: function to run when @mod is backed by an install command.
1227 * @data: data to give back to @run_install callback
1228 * @print_action: function to call with the action being taken (install or
1229 * insmod). It's useful for tools like modprobe when running with verbose
1230 * output or in dry-run mode.
1231 *
1232 * Insert a module in Linux kernel resolving dependencies, soft dependencies,
1233 * install commands and applying blacklist.
1234 *
1235 * If @run_install is NULL, this function will fork and exec by calling
1236 * system(3). Don't pass a NULL argument in @run_install if your binary is
1237 * setuid/setgid (see warning in system(3)). If you need control over the
1238 * execution of an install command, give a callback function instead.
1239 *
1240 * Returns: 0 on success, > 0 if stopped by a reason given in @flags or < 0 on
1241 * failure.
1242 */
1243 KMOD_EXPORT int kmod_module_probe_insert_module(struct kmod_module *mod,
1244 unsigned int flags, const char *extra_options,
1245 int (*run_install)(struct kmod_module *m,
1246 const char *cmd, void *data),
1247 const void *data,
1248 void (*print_action)(struct kmod_module *m,
1249 bool install,
1250 const char *options))
1251 {
1252 struct kmod_list *list = NULL, *l;
1253 struct probe_insert_cb cb;
1254 int err;
1255
1256 if (mod == NULL)
1257 return -ENOENT;
1258
1259 if (!(flags & KMOD_PROBE_IGNORE_LOADED)
1260 && module_is_inkernel(mod)) {
1261 if (flags & KMOD_PROBE_FAIL_ON_LOADED)
1262 return -EEXIST;
1263 else
1264 return 0;
1265 }
1266
1267 /*
1268 * Ugly assignement + check. We need to check if we were told to check
1269 * blacklist and also return the reason why we failed.
1270 * KMOD_PROBE_APPLY_BLACKLIST_ALIAS_ONLY will take effect only if the
1271 * module is an alias, so we also need to check it
1272 */
1273 if ((mod->alias != NULL && ((err = flags & KMOD_PROBE_APPLY_BLACKLIST_ALIAS_ONLY)))
1274 || (err = flags & KMOD_PROBE_APPLY_BLACKLIST_ALL)
1275 || (err = flags & KMOD_PROBE_APPLY_BLACKLIST)) {
1276 if (module_is_blacklisted(mod))
1277 return err;
1278 }
1279
1280 err = kmod_module_get_probe_list(mod,
1281 !!(flags & KMOD_PROBE_IGNORE_COMMAND), &list);
1282 if (err < 0)
1283 return err;
1284
1285 if (flags & KMOD_PROBE_APPLY_BLACKLIST_ALL) {
1286 struct kmod_list *filtered = NULL;
1287
1288 err = kmod_module_apply_filter(mod->ctx,
1289 KMOD_FILTER_BLACKLIST, list, &filtered);
1290 if (err < 0)
1291 return err;
1292
1293 kmod_module_unref_list(list);
1294 if (filtered == NULL)
1295 return KMOD_PROBE_APPLY_BLACKLIST_ALL;
1296
1297 list = filtered;
1298 }
1299
1300 cb.run_install = run_install;
1301 cb.data = (void *) data;
1302
1303 kmod_list_foreach(l, list) {
1304 struct kmod_module *m = l->data;
1305 const char *moptions = kmod_module_get_options(m);
1306 const char *cmd = kmod_module_get_install_commands(m);
1307 char *options;
1308
1309 if (!(flags & KMOD_PROBE_IGNORE_LOADED)
1310 && module_is_inkernel(m)) {
1311 DBG(mod->ctx, "Ignoring module '%s': already loaded\n",
1312 m->name);
1313 err = -EEXIST;
1314 goto finish_module;
1315 }
1316
1317 options = module_options_concat(moptions,
1318 m == mod ? extra_options : NULL);
1319
1320 if (cmd != NULL && !m->ignorecmd) {
1321 if (print_action != NULL)
1322 print_action(m, true, options ?: "");
1323
1324 if (!(flags & KMOD_PROBE_DRY_RUN))
1325 err = module_do_install_commands(m, options,
1326 &cb);
1327 } else {
1328 if (print_action != NULL)
1329 print_action(m, false, options ?: "");
1330
1331 if (!(flags & KMOD_PROBE_DRY_RUN))
1332 err = kmod_module_insert_module(m, flags,
1333 options);
1334 }
1335
1336 free(options);
1337
1338 finish_module:
1339 /*
1340 * Treat "already loaded" error. If we were told to stop on
1341 * already loaded and the module being loaded is not a softdep
1342 * or dep, bail out. Otherwise, just ignore and continue.
1343 *
1344 * We need to check here because of race conditions. We
1345 * checked first if module was already loaded but it may have
1346 * been loaded between the check and the moment we try to
1347 * insert it.
1348 */
1349 if (err == -EEXIST && m == mod &&
1350 (flags & KMOD_PROBE_FAIL_ON_LOADED))
1351 break;
1352
1353 /*
1354 * Ignore errors from softdeps
1355 */
1356 if (err == -EEXIST || !m->required)
1357 err = 0;
1358
1359 else if (err < 0)
1360 break;
1361 }
1362
1363 kmod_module_unref_list(list);
1364 return err;
1365 }
1366
1367 /**
1368 * kmod_module_get_options:
1369 * @mod: kmod module
1370 *
1371 * Get options of this kmod module. Options come from the configuration file
1372 * and are cached in @mod. The first call to this function will search for
1373 * this module in configuration and subsequent calls return the cached string.
1374 *
1375 * Returns: a string with all the options separated by spaces. This string is
1376 * owned by @mod, do not free it.
1377 */
1378 KMOD_EXPORT const char *kmod_module_get_options(const struct kmod_module *mod)
1379 {
1380 if (mod == NULL)
1381 return NULL;
1382
1383 if (!mod->init.options) {
1384 /* lazy init */
1385 struct kmod_module *m = (struct kmod_module *)mod;
1386 const struct kmod_list *l;
1387 const struct kmod_config *config;
1388 char *opts = NULL;
1389 size_t optslen = 0;
1390
1391 config = kmod_get_config(mod->ctx);
1392
1393 kmod_list_foreach(l, config->options) {
1394 const char *modname = kmod_option_get_modname(l);
1395 const char *str;
1396 size_t len;
1397 void *tmp;
1398
1399 DBG(mod->ctx, "modname=%s mod->name=%s mod->alias=%s\n", modname, mod->name, mod->alias);
1400 if (!(streq(modname, mod->name) || (mod->alias != NULL &&
1401 streq(modname, mod->alias))))
1402 continue;
1403
1404 DBG(mod->ctx, "passed = modname=%s mod->name=%s mod->alias=%s\n", modname, mod->name, mod->alias);
1405 str = kmod_option_get_options(l);
1406 len = strlen(str);
1407 if (len < 1)
1408 continue;
1409
1410 tmp = realloc(opts, optslen + len + 2);
1411 if (tmp == NULL) {
1412 free(opts);
1413 goto failed;
1414 }
1415
1416 opts = tmp;
1417
1418 if (optslen > 0) {
1419 opts[optslen] = ' ';
1420 optslen++;
1421 }
1422
1423 memcpy(opts + optslen, str, len);
1424 optslen += len;
1425 opts[optslen] = '\0';
1426 }
1427
1428 m->init.options = true;
1429 m->options = opts;
1430 }
1431
1432 return mod->options;
1433
1434 failed:
1435 ERR(mod->ctx, "out of memory\n");
1436 return NULL;
1437 }
1438
1439 /**
1440 * kmod_module_get_install_commands:
1441 * @mod: kmod module
1442 *
1443 * Get install commands for this kmod module. Install commands come from the
1444 * configuration file and are cached in @mod. The first call to this function
1445 * will search for this module in configuration and subsequent calls return
1446 * the cached string. The install commands are returned as they were in the
1447 * configuration, concatenated by ';'. No other processing is made in this
1448 * string.
1449 *
1450 * Returns: a string with all install commands separated by semicolons. This
1451 * string is owned by @mod, do not free it.
1452 */
1453 KMOD_EXPORT const char *kmod_module_get_install_commands(const struct kmod_module *mod)
1454 {
1455 if (mod == NULL)
1456 return NULL;
1457
1458 if (!mod->init.install_commands) {
1459 /* lazy init */
1460 struct kmod_module *m = (struct kmod_module *)mod;
1461 const struct kmod_list *l;
1462 const struct kmod_config *config;
1463
1464 config = kmod_get_config(mod->ctx);
1465
1466 kmod_list_foreach(l, config->install_commands) {
1467 const char *modname = kmod_command_get_modname(l);
1468
1469 if (fnmatch(modname, mod->name, 0) != 0)
1470 continue;
1471
1472 m->install_commands = kmod_command_get_command(l);
1473
1474 /*
1475 * find only the first command, as modprobe from
1476 * module-init-tools does
1477 */
1478 break;
1479 }
1480
1481 m->init.install_commands = true;
1482 }
1483
1484 return mod->install_commands;
1485 }
1486
1487 void kmod_module_set_install_commands(struct kmod_module *mod, const char *cmd)
1488 {
1489 mod->init.install_commands = true;
1490 mod->install_commands = cmd;
1491 }
1492
1493 static struct kmod_list *lookup_softdep(struct kmod_ctx *ctx, const char * const * array, unsigned int count)
1494 {
1495 struct kmod_list *ret = NULL;
1496 unsigned i;
1497
1498 for (i = 0; i < count; i++) {
1499 const char *depname = array[i];
1500 struct kmod_list *lst = NULL;
1501 int err;
1502
1503 err = kmod_module_new_from_lookup(ctx, depname, &lst);
1504 if (err < 0) {
1505 ERR(ctx, "failed to lookup soft dependency '%s', continuing anyway.\n", depname);
1506 continue;
1507 } else if (lst != NULL)
1508 ret = kmod_list_append_list(ret, lst);
1509 }
1510 return ret;
1511 }
1512
1513 /**
1514 * kmod_module_get_softdeps:
1515 * @mod: kmod module
1516 * @pre: where to save the list of preceding soft dependencies.
1517 * @post: where to save the list of post soft dependencies.
1518 *
1519 * Get soft dependencies for this kmod module. Soft dependencies come
1520 * from configuration file and are not cached in @mod because it may include
1521 * dependency cycles that would make we leak kmod_module. Any call
1522 * to this function will search for this module in configuration, allocate a
1523 * list and return the result.
1524 *
1525 * Both @pre and @post are newly created list of kmod_module and
1526 * should be unreferenced with kmod_module_unref_list().
1527 *
1528 * Returns: 0 on success or < 0 otherwise.
1529 */
1530 KMOD_EXPORT int kmod_module_get_softdeps(const struct kmod_module *mod,
1531 struct kmod_list **pre,
1532 struct kmod_list **post)
1533 {
1534 const struct kmod_list *l;
1535 const struct kmod_config *config;
1536
1537 if (mod == NULL || pre == NULL || post == NULL)
1538 return -ENOENT;
1539
1540 assert(*pre == NULL);
1541 assert(*post == NULL);
1542
1543 config = kmod_get_config(mod->ctx);
1544
1545 kmod_list_foreach(l, config->softdeps) {
1546 const char *modname = kmod_softdep_get_name(l);
1547 const char * const *array;
1548 unsigned count;
1549
1550 if (fnmatch(modname, mod->name, 0) != 0)
1551 continue;
1552
1553 array = kmod_softdep_get_pre(l, &count);
1554 *pre = lookup_softdep(mod->ctx, array, count);
1555 array = kmod_softdep_get_post(l, &count);
1556 *post = lookup_softdep(mod->ctx, array, count);
1557
1558 /*
1559 * find only the first command, as modprobe from
1560 * module-init-tools does
1561 */
1562 break;
1563 }
1564
1565 return 0;
1566 }
1567
1568 /**
1569 * kmod_module_get_remove_commands:
1570 * @mod: kmod module
1571 *
1572 * Get remove commands for this kmod module. Remove commands come from the
1573 * configuration file and are cached in @mod. The first call to this function
1574 * will search for this module in configuration and subsequent calls return
1575 * the cached string. The remove commands are returned as they were in the
1576 * configuration, concatenated by ';'. No other processing is made in this
1577 * string.
1578 *
1579 * Returns: a string with all remove commands separated by semicolons. This
1580 * string is owned by @mod, do not free it.
1581 */
1582 KMOD_EXPORT const char *kmod_module_get_remove_commands(const struct kmod_module *mod)
1583 {
1584 if (mod == NULL)
1585 return NULL;
1586
1587 if (!mod->init.remove_commands) {
1588 /* lazy init */
1589 struct kmod_module *m = (struct kmod_module *)mod;
1590 const struct kmod_list *l;
1591 const struct kmod_config *config;
1592
1593 config = kmod_get_config(mod->ctx);
1594
1595 kmod_list_foreach(l, config->remove_commands) {
1596 const char *modname = kmod_command_get_modname(l);
1597
1598 if (fnmatch(modname, mod->name, 0) != 0)
1599 continue;
1600
1601 m->remove_commands = kmod_command_get_command(l);
1602
1603 /*
1604 * find only the first command, as modprobe from
1605 * module-init-tools does
1606 */
1607 break;
1608 }
1609
1610 m->init.remove_commands = true;
1611 }
1612
1613 return mod->remove_commands;
1614 }
1615
1616 void kmod_module_set_remove_commands(struct kmod_module *mod, const char *cmd)
1617 {
1618 mod->init.remove_commands = true;
1619 mod->remove_commands = cmd;
1620 }
1621
1622 /**
1623 * SECTION:libkmod-loaded
1624 * @short_description: currently loaded modules
1625 *
1626 * Information about currently loaded modules, as reported by Linux kernel.
1627 * These information are not cached by libkmod and are always read from /sys
1628 * and /proc/modules.
1629 */
1630
1631 /**
1632 * kmod_module_new_from_loaded:
1633 * @ctx: kmod library context
1634 * @list: where to save the list of loaded modules
1635 *
1636 * Create a new list of kmod modules with all modules currently loaded in
1637 * kernel. It uses /proc/modules to get the names of loaded modules and to
1638 * create kmod modules by calling kmod_module_new_from_name() in each of them.
1639 * They are put in @list in no particular order.
1640 *
1641 * The initial refcount is 1, and needs to be decremented to release the
1642 * resources of the kmod_module. The returned @list must be released by
1643 * calling kmod_module_unref_list(). Since libkmod keeps track of all
1644 * kmod_modules created, they are all released upon @ctx destruction too. Do
1645 * not unref @ctx before all the desired operations with the returned list are
1646 * completed.
1647 *
1648 * Returns: 0 on success or < 0 on error.
1649 */
1650 KMOD_EXPORT int kmod_module_new_from_loaded(struct kmod_ctx *ctx,
1651 struct kmod_list **list)
1652 {
1653 struct kmod_list *l = NULL;
1654 FILE *fp;
1655 char line[4096];
1656
1657 if (ctx == NULL || list == NULL)
1658 return -ENOENT;
1659
1660 fp = fopen("/proc/modules", "re");
1661 if (fp == NULL) {
1662 int err = -errno;
1663 ERR(ctx, "could not open /proc/modules: %s\n", strerror(errno));
1664 return err;
1665 }
1666
1667 while (fgets(line, sizeof(line), fp)) {
1668 struct kmod_module *m;
1669 struct kmod_list *node;
1670 int err;
1671 size_t len = strlen(line);
1672 char *saveptr, *name = strtok_r(line, " \t", &saveptr);
1673
1674 err = kmod_module_new_from_name(ctx, name, &m);
1675 if (err < 0) {
1676 ERR(ctx, "could not get module from name '%s': %s\n",
1677 name, strerror(-err));
1678 goto eat_line;
1679 }
1680
1681 node = kmod_list_append(l, m);
1682 if (node)
1683 l = node;
1684 else {
1685 ERR(ctx, "out of memory\n");
1686 kmod_module_unref(m);
1687 }
1688 eat_line:
1689 while (line[len - 1] != '\n' && fgets(line, sizeof(line), fp))
1690 len = strlen(line);
1691 }
1692
1693 fclose(fp);
1694 *list = l;
1695
1696 return 0;
1697 }
1698
1699 /**
1700 * kmod_module_initstate_str:
1701 * @state: the state as returned by kmod_module_get_initstate()
1702 *
1703 * Translate a initstate to a string.
1704 *
1705 * Returns: the string associated to the @state. This string is statically
1706 * allocated, do not free it.
1707 */
1708 KMOD_EXPORT const char *kmod_module_initstate_str(enum kmod_module_initstate state)
1709 {
1710 switch (state) {
1711 case KMOD_MODULE_BUILTIN:
1712 return "builtin";
1713 case KMOD_MODULE_LIVE:
1714 return "live";
1715 case KMOD_MODULE_COMING:
1716 return "coming";
1717 case KMOD_MODULE_GOING:
1718 return "going";
1719 default:
1720 return NULL;
1721 }
1722 }
1723
1724 /**
1725 * kmod_module_get_initstate:
1726 * @mod: kmod module
1727 *
1728 * Get the initstate of this @mod, as returned by Linux Kernel, by reading
1729 * /sys filesystem.
1730 *
1731 * Returns: < 0 on error or module state if module is found in kernel, valid states are
1732 * KMOD_MODULE_BUILTIN: module is builtin;
1733 * KMOD_MODULE_LIVE: module is live in kernel;
1734 * KMOD_MODULE_COMING: module is being loaded;
1735 * KMOD_MODULE_GOING: module is being unloaded.
1736 */
1737 KMOD_EXPORT int kmod_module_get_initstate(const struct kmod_module *mod)
1738 {
1739 char path[PATH_MAX], buf[32];
1740 int fd, err, pathlen;
1741
1742 if (mod == NULL)
1743 return -ENOENT;
1744
1745 /* remove const: this can only change internal state */
1746 if (kmod_module_is_builtin((struct kmod_module *)mod))
1747 return KMOD_MODULE_BUILTIN;
1748
1749 pathlen = snprintf(path, sizeof(path),
1750 "/sys/module/%s/initstate", mod->name);
1751 fd = open(path, O_RDONLY|O_CLOEXEC);
1752 if (fd < 0) {
1753 err = -errno;
1754
1755 DBG(mod->ctx, "could not open '%s': %s\n",
1756 path, strerror(-err));
1757
1758 if (pathlen > (int)sizeof("/initstate") - 1) {
1759 struct stat st;
1760 path[pathlen - (sizeof("/initstate") - 1)] = '\0';
1761 if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
1762 return KMOD_MODULE_COMING;
1763 }
1764
1765 DBG(mod->ctx, "could not open '%s': %s\n",
1766 path, strerror(-err));
1767 return err;
1768 }
1769
1770 err = read_str_safe(fd, buf, sizeof(buf));
1771 close(fd);
1772 if (err < 0) {
1773 ERR(mod->ctx, "could not read from '%s': %s\n",
1774 path, strerror(-err));
1775 return err;
1776 }
1777
1778 if (streq(buf, "live\n"))
1779 return KMOD_MODULE_LIVE;
1780 else if (streq(buf, "coming\n"))
1781 return KMOD_MODULE_COMING;
1782 else if (streq(buf, "going\n"))
1783 return KMOD_MODULE_GOING;
1784
1785 ERR(mod->ctx, "unknown %s: '%s'\n", path, buf);
1786 return -EINVAL;
1787 }
1788
1789 /**
1790 * kmod_module_get_size:
1791 * @mod: kmod module
1792 *
1793 * Get the size of this kmod module as returned by Linux kernel. If supported,
1794 * the size is read from the coresize attribute in /sys/module. For older
1795 * kernels, this falls back on /proc/modules and searches for the specified
1796 * module to get its size.
1797 *
1798 * Returns: the size of this kmod module.
1799 */
1800 KMOD_EXPORT long kmod_module_get_size(const struct kmod_module *mod)
1801 {
1802 FILE *fp;
1803 char line[4096];
1804 int lineno = 0;
1805 long size = -ENOENT;
1806 int dfd, cfd;
1807
1808 if (mod == NULL)
1809 return -ENOENT;
1810
1811 /* try to open the module dir in /sys. If this fails, don't
1812 * bother trying to find the size as we know the module isn't
1813 * loaded.
1814 */
1815 snprintf(line, sizeof(line), "/sys/module/%s", mod->name);
1816 dfd = open(line, O_RDONLY|O_CLOEXEC);
1817 if (dfd < 0)
1818 return -errno;
1819
1820 /* available as of linux 3.3.x */
1821 cfd = openat(dfd, "coresize", O_RDONLY|O_CLOEXEC);
1822 if (cfd >= 0) {
1823 if (read_str_long(cfd, &size, 10) < 0)
1824 ERR(mod->ctx, "failed to read coresize from %s\n", line);
1825 close(cfd);
1826 goto done;
1827 }
1828
1829 /* fall back on parsing /proc/modules */
1830 fp = fopen("/proc/modules", "re");
1831 if (fp == NULL) {
1832 int err = -errno;
1833 ERR(mod->ctx,
1834 "could not open /proc/modules: %s\n", strerror(errno));
1835 close(dfd);
1836 return err;
1837 }
1838
1839 while (fgets(line, sizeof(line), fp)) {
1840 size_t len = strlen(line);
1841 char *saveptr, *endptr, *tok = strtok_r(line, " \t", &saveptr);
1842 long value;
1843
1844 lineno++;
1845 if (tok == NULL || !streq(tok, mod->name))
1846 goto eat_line;
1847
1848 tok = strtok_r(NULL, " \t", &saveptr);
1849 if (tok == NULL) {
1850 ERR(mod->ctx,
1851 "invalid line format at /proc/modules:%d\n", lineno);
1852 break;
1853 }
1854
1855 value = strtol(tok, &endptr, 10);
1856 if (endptr == tok || *endptr != '\0') {
1857 ERR(mod->ctx,
1858 "invalid line format at /proc/modules:%d\n", lineno);
1859 break;
1860 }
1861
1862 size = value;
1863 break;
1864 eat_line:
1865 while (line[len - 1] != '\n' && fgets(line, sizeof(line), fp))
1866 len = strlen(line);
1867 }
1868 fclose(fp);
1869
1870 done:
1871 close(dfd);
1872 return size;
1873 }
1874
1875 /**
1876 * kmod_module_get_refcnt:
1877 * @mod: kmod module
1878 *
1879 * Get the ref count of this @mod, as returned by Linux Kernel, by reading
1880 * /sys filesystem.
1881 *
1882 * Returns: the reference count on success or < 0 on failure.
1883 */
1884 KMOD_EXPORT int kmod_module_get_refcnt(const struct kmod_module *mod)
1885 {
1886 char path[PATH_MAX];
1887 long refcnt;
1888 int fd, err;
1889
1890 if (mod == NULL)
1891 return -ENOENT;
1892
1893 snprintf(path, sizeof(path), "/sys/module/%s/refcnt", mod->name);
1894 fd = open(path, O_RDONLY|O_CLOEXEC);
1895 if (fd < 0) {
1896 err = -errno;
1897 DBG(mod->ctx, "could not open '%s': %s\n",
1898 path, strerror(errno));
1899 return err;
1900 }
1901
1902 err = read_str_long(fd, &refcnt, 10);
1903 close(fd);
1904 if (err < 0) {
1905 ERR(mod->ctx, "could not read integer from '%s': '%s'\n",
1906 path, strerror(-err));
1907 return err;
1908 }
1909
1910 return (int)refcnt;
1911 }
1912
1913 /**
1914 * kmod_module_get_holders:
1915 * @mod: kmod module
1916 *
1917 * Get a list of kmod modules that are holding this @mod, as returned by Linux
1918 * Kernel. After use, free the @list by calling kmod_module_unref_list().
1919 *
1920 * Returns: a new list of kmod modules on success or NULL on failure.
1921 */
1922 KMOD_EXPORT struct kmod_list *kmod_module_get_holders(const struct kmod_module *mod)
1923 {
1924 char dname[PATH_MAX];
1925 struct kmod_list *list = NULL;
1926 struct dirent *dent;
1927 DIR *d;
1928
1929 if (mod == NULL || mod->ctx == NULL)
1930 return NULL;
1931
1932 snprintf(dname, sizeof(dname), "/sys/module/%s/holders", mod->name);
1933
1934 d = opendir(dname);
1935 if (d == NULL) {
1936 ERR(mod->ctx, "could not open '%s': %s\n",
1937 dname, strerror(errno));
1938 return NULL;
1939 }
1940
1941 for (dent = readdir(d); dent != NULL; dent = readdir(d)) {
1942 struct kmod_module *holder;
1943 struct kmod_list *l;
1944 int err;
1945
1946 if (dent->d_name[0] == '.') {
1947 if (dent->d_name[1] == '\0' ||
1948 (dent->d_name[1] == '.' && dent->d_name[2] == '\0'))
1949 continue;
1950 }
1951
1952 err = kmod_module_new_from_name(mod->ctx, dent->d_name,
1953 &holder);
1954 if (err < 0) {
1955 ERR(mod->ctx, "could not create module for '%s': %s\n",
1956 dent->d_name, strerror(-err));
1957 goto fail;
1958 }
1959
1960 l = kmod_list_append(list, holder);
1961 if (l != NULL) {
1962 list = l;
1963 } else {
1964 ERR(mod->ctx, "out of memory\n");
1965 kmod_module_unref(holder);
1966 goto fail;
1967 }
1968 }
1969
1970 closedir(d);
1971 return list;
1972
1973 fail:
1974 closedir(d);
1975 kmod_module_unref_list(list);
1976 return NULL;
1977 }
1978
1979 struct kmod_module_section {
1980 unsigned long address;
1981 char name[];
1982 };
1983
1984 static void kmod_module_section_free(struct kmod_module_section *section)
1985 {
1986 free(section);
1987 }
1988
1989 /**
1990 * kmod_module_get_sections:
1991 * @mod: kmod module
1992 *
1993 * Get a list of kmod sections of this @mod, as returned by Linux Kernel. The
1994 * structure contained in this list is internal to libkmod and their fields
1995 * can be obtained by calling kmod_module_section_get_name() and
1996 * kmod_module_section_get_address().
1997 *
1998 * After use, free the @list by calling kmod_module_section_free_list().
1999 *
2000 * Returns: a new list of kmod module sections on success or NULL on failure.
2001 */
2002 KMOD_EXPORT struct kmod_list *kmod_module_get_sections(const struct kmod_module *mod)
2003 {
2004 char dname[PATH_MAX];
2005 struct kmod_list *list = NULL;
2006 struct dirent *dent;
2007 DIR *d;
2008 int dfd;
2009
2010 if (mod == NULL)
2011 return NULL;
2012
2013 snprintf(dname, sizeof(dname), "/sys/module/%s/sections", mod->name);
2014
2015 d = opendir(dname);
2016 if (d == NULL) {
2017 ERR(mod->ctx, "could not open '%s': %s\n",
2018 dname, strerror(errno));
2019 return NULL;
2020 }
2021
2022 dfd = dirfd(d);
2023
2024 for (dent = readdir(d); dent; dent = readdir(d)) {
2025 struct kmod_module_section *section;
2026 struct kmod_list *l;
2027 unsigned long address;
2028 size_t namesz;
2029 int fd, err;
2030
2031 if (dent->d_name[0] == '.') {
2032 if (dent->d_name[1] == '\0' ||
2033 (dent->d_name[1] == '.' && dent->d_name[2] == '\0'))
2034 continue;
2035 }
2036
2037 fd = openat(dfd, dent->d_name, O_RDONLY|O_CLOEXEC);
2038 if (fd < 0) {
2039 ERR(mod->ctx, "could not open '%s/%s': %m\n",
2040 dname, dent->d_name);
2041 goto fail;
2042 }
2043
2044 err = read_str_ulong(fd, &address, 16);
2045 close(fd);
2046 if (err < 0) {
2047 ERR(mod->ctx, "could not read long from '%s/%s': %m\n",
2048 dname, dent->d_name);
2049 goto fail;
2050 }
2051
2052 namesz = strlen(dent->d_name) + 1;
2053 section = malloc(sizeof(*section) + namesz);
2054
2055 if (section == NULL) {
2056 ERR(mod->ctx, "out of memory\n");
2057 goto fail;
2058 }
2059
2060 section->address = address;
2061 memcpy(section->name, dent->d_name, namesz);
2062
2063 l = kmod_list_append(list, section);
2064 if (l != NULL) {
2065 list = l;
2066 } else {
2067 ERR(mod->ctx, "out of memory\n");
2068 free(section);
2069 goto fail;
2070 }
2071 }
2072
2073 closedir(d);
2074 return list;
2075
2076 fail:
2077 closedir(d);
2078 kmod_module_unref_list(list);
2079 return NULL;
2080 }
2081
2082 /**
2083 * kmod_module_section_get_module_name:
2084 * @entry: a list entry representing a kmod module section
2085 *
2086 * Get the name of a kmod module section.
2087 *
2088 * After use, free the @list by calling kmod_module_section_free_list().
2089 *
2090 * Returns: the name of this kmod module section on success or NULL on
2091 * failure. The string is owned by the section, do not free it.
2092 */
2093 KMOD_EXPORT const char *kmod_module_section_get_name(const struct kmod_list *entry)
2094 {
2095 struct kmod_module_section *section;
2096
2097 if (entry == NULL)
2098 return NULL;
2099
2100 section = entry->data;
2101 return section->name;
2102 }
2103
2104 /**
2105 * kmod_module_section_get_address:
2106 * @entry: a list entry representing a kmod module section
2107 *
2108 * Get the address of a kmod module section.
2109 *
2110 * After use, free the @list by calling kmod_module_section_free_list().
2111 *
2112 * Returns: the address of this kmod module section on success or ULONG_MAX
2113 * on failure.
2114 */
2115 KMOD_EXPORT unsigned long kmod_module_section_get_address(const struct kmod_list *entry)
2116 {
2117 struct kmod_module_section *section;
2118
2119 if (entry == NULL)
2120 return (unsigned long)-1;
2121
2122 section = entry->data;
2123 return section->address;
2124 }
2125
2126 /**
2127 * kmod_module_section_free_list:
2128 * @list: kmod module section list
2129 *
2130 * Release the resources taken by @list
2131 */
2132 KMOD_EXPORT void kmod_module_section_free_list(struct kmod_list *list)
2133 {
2134 while (list) {
2135 kmod_module_section_free(list->data);
2136 list = kmod_list_remove(list);
2137 }
2138 }
2139
2140 static struct kmod_elf *kmod_module_get_elf(const struct kmod_module *mod)
2141 {
2142 if (mod->file == NULL) {
2143 const char *path = kmod_module_get_path(mod);
2144
2145 if (path == NULL) {
2146 errno = ENOENT;
2147 return NULL;
2148 }
2149
2150 ((struct kmod_module *)mod)->file = kmod_file_open(mod->ctx,
2151 path);
2152 if (mod->file == NULL)
2153 return NULL;
2154 }
2155
2156 return kmod_file_get_elf(mod->file);
2157 }
2158
2159 struct kmod_module_info {
2160 char *key;
2161 char value[];
2162 };
2163
2164 static struct kmod_module_info *kmod_module_info_new(const char *key, size_t keylen, const char *value, size_t valuelen)
2165 {
2166 struct kmod_module_info *info;
2167
2168 info = malloc(sizeof(struct kmod_module_info) + keylen + valuelen + 2);
2169 if (info == NULL)
2170 return NULL;
2171
2172 info->key = (char *)info + sizeof(struct kmod_module_info)
2173 + valuelen + 1;
2174 memcpy(info->key, key, keylen);
2175 info->key[keylen] = '\0';
2176 memcpy(info->value, value, valuelen);
2177 info->value[valuelen] = '\0';
2178 return info;
2179 }
2180
2181 static void kmod_module_info_free(struct kmod_module_info *info)
2182 {
2183 free(info);
2184 }
2185
2186 static struct kmod_list *kmod_module_info_append(struct kmod_list **list, const char *key, size_t keylen, const char *value, size_t valuelen)
2187 {
2188 struct kmod_module_info *info;
2189 struct kmod_list *n;
2190
2191 info = kmod_module_info_new(key, keylen, value, valuelen);
2192 if (info == NULL)
2193 return NULL;
2194 n = kmod_list_append(*list, info);
2195 if (n != NULL)
2196 *list = n;
2197 else
2198 kmod_module_info_free(info);
2199 return n;
2200 }
2201
2202 static char *kmod_module_hex_to_str(const char *hex, size_t len)
2203 {
2204 char *str;
2205 int i;
2206 int j;
2207 const size_t line_limit = 20;
2208 size_t str_len;
2209
2210 str_len = len * 3; /* XX: or XX\0 */
2211 str_len += ((str_len + line_limit - 1) / line_limit - 1) * 3; /* \n\t\t */
2212
2213 str = malloc(str_len);
2214 if (str == NULL)
2215 return NULL;
2216
2217 for (i = 0, j = 0; i < (int)len; i++) {
2218 j += sprintf(str + j, "%02X", (unsigned char)hex[i]);
2219 if (i < (int)len - 1) {
2220 str[j++] = ':';
2221
2222 if ((i + 1) % line_limit == 0)
2223 j += sprintf(str + j, "\n\t\t");
2224 }
2225 }
2226 return str;
2227 }
2228
2229 static struct kmod_list *kmod_module_info_append_hex(struct kmod_list **list,
2230 const char *key,
2231 size_t keylen,
2232 const char *value,
2233 size_t valuelen)
2234 {
2235 char *hex;
2236 struct kmod_list *n;
2237
2238 if (valuelen > 0) {
2239 /* Display as 01:12:DE:AD:BE:EF:... */
2240 hex = kmod_module_hex_to_str(value, valuelen);
2241 if (hex == NULL)
2242 goto list_error;
2243 n = kmod_module_info_append(list, key, keylen, hex, strlen(hex));
2244 free(hex);
2245 if (n == NULL)
2246 goto list_error;
2247 } else {
2248 n = kmod_module_info_append(list, key, keylen, NULL, 0);
2249 if (n == NULL)
2250 goto list_error;
2251 }
2252
2253 return n;
2254
2255 list_error:
2256 return NULL;
2257 }
2258
2259 /**
2260 * kmod_module_get_info:
2261 * @mod: kmod module
2262 * @list: where to return list of module information. Use
2263 * kmod_module_info_get_key() and
2264 * kmod_module_info_get_value(). Release this list with
2265 * kmod_module_info_free_list()
2266 *
2267 * Get a list of entries in ELF section ".modinfo", these contain
2268 * alias, license, depends, vermagic and other keys with respective
2269 * values. If the module is signed (CONFIG_MODULE_SIG), information
2270 * about the module signature is included as well: signer,
2271 * sig_key and sig_hashalgo.
2272 *
2273 * After use, free the @list by calling kmod_module_info_free_list().
2274 *
2275 * Returns: 0 on success or < 0 otherwise.
2276 */
2277 KMOD_EXPORT int kmod_module_get_info(const struct kmod_module *mod, struct kmod_list **list)
2278 {
2279 struct kmod_elf *elf;
2280 char **strings;
2281 int i, count, ret = -ENOMEM;
2282 struct kmod_signature_info sig_info = {};
2283
2284 if (mod == NULL || list == NULL)
2285 return -ENOENT;
2286
2287 assert(*list == NULL);
2288
2289 elf = kmod_module_get_elf(mod);
2290 if (elf == NULL)
2291 return -errno;
2292
2293 count = kmod_elf_get_strings(elf, ".modinfo", &strings);
2294 if (count < 0)
2295 return count;
2296
2297 for (i = 0; i < count; i++) {
2298 struct kmod_list *n;
2299 const char *key, *value;
2300 size_t keylen, valuelen;
2301
2302 key = strings[i];
2303 value = strchr(key, '=');
2304 if (value == NULL) {
2305 keylen = strlen(key);
2306 valuelen = 0;
2307 value = key;
2308 } else {
2309 keylen = value - key;
2310 value++;
2311 valuelen = strlen(value);
2312 }
2313
2314 n = kmod_module_info_append(list, key, keylen, value, valuelen);
2315 if (n == NULL)
2316 goto list_error;
2317 }
2318
2319 if (kmod_module_signature_info(mod->file, &sig_info)) {
2320 struct kmod_list *n;
2321
2322 n = kmod_module_info_append(list, "sig_id", strlen("sig_id"),
2323 sig_info.id_type, strlen(sig_info.id_type));
2324 if (n == NULL)
2325 goto list_error;
2326 count++;
2327
2328 n = kmod_module_info_append(list, "signer", strlen("signer"),
2329 sig_info.signer, sig_info.signer_len);
2330 if (n == NULL)
2331 goto list_error;
2332 count++;
2333
2334
2335 n = kmod_module_info_append_hex(list, "sig_key", strlen("sig_key"),
2336 sig_info.key_id,
2337 sig_info.key_id_len);
2338 if (n == NULL)
2339 goto list_error;
2340 count++;
2341
2342 n = kmod_module_info_append(list,
2343 "sig_hashalgo", strlen("sig_hashalgo"),
2344 sig_info.hash_algo, strlen(sig_info.hash_algo));
2345 if (n == NULL)
2346 goto list_error;
2347 count++;
2348
2349 /*
2350 * Omit sig_info.algo for now, as these
2351 * are currently constant.
2352 */
2353 n = kmod_module_info_append_hex(list, "signature",
2354 strlen("signature"),
2355 sig_info.sig,
2356 sig_info.sig_len);
2357
2358 if (n == NULL)
2359 goto list_error;
2360 count++;
2361
2362 }
2363 ret = count;
2364
2365 list_error:
2366 /* aux structures freed in normal case also */
2367 kmod_module_signature_info_free(&sig_info);
2368
2369 if (ret < 0) {
2370 kmod_module_info_free_list(*list);
2371 *list = NULL;
2372 }
2373 free(strings);
2374 return ret;
2375 }
2376
2377 /**
2378 * kmod_module_info_get_key:
2379 * @entry: a list entry representing a kmod module info
2380 *
2381 * Get the key of a kmod module info.
2382 *
2383 * Returns: the key of this kmod module info on success or NULL on
2384 * failure. The string is owned by the info, do not free it.
2385 */
2386 KMOD_EXPORT const char *kmod_module_info_get_key(const struct kmod_list *entry)
2387 {
2388 struct kmod_module_info *info;
2389
2390 if (entry == NULL)
2391 return NULL;
2392
2393 info = entry->data;
2394 return info->key;
2395 }
2396
2397 /**
2398 * kmod_module_info_get_value:
2399 * @entry: a list entry representing a kmod module info
2400 *
2401 * Get the value of a kmod module info.
2402 *
2403 * Returns: the value of this kmod module info on success or NULL on
2404 * failure. The string is owned by the info, do not free it.
2405 */
2406 KMOD_EXPORT const char *kmod_module_info_get_value(const struct kmod_list *entry)
2407 {
2408 struct kmod_module_info *info;
2409
2410 if (entry == NULL)
2411 return NULL;
2412
2413 info = entry->data;
2414 return info->value;
2415 }
2416
2417 /**
2418 * kmod_module_info_free_list:
2419 * @list: kmod module info list
2420 *
2421 * Release the resources taken by @list
2422 */
2423 KMOD_EXPORT void kmod_module_info_free_list(struct kmod_list *list)
2424 {
2425 while (list) {
2426 kmod_module_info_free(list->data);
2427 list = kmod_list_remove(list);
2428 }
2429 }
2430
2431 struct kmod_module_version {
2432 uint64_t crc;
2433 char symbol[];
2434 };
2435
2436 static struct kmod_module_version *kmod_module_versions_new(uint64_t crc, const char *symbol)
2437 {
2438 struct kmod_module_version *mv;
2439 size_t symbollen = strlen(symbol) + 1;
2440
2441 mv = malloc(sizeof(struct kmod_module_version) + symbollen);
2442 if (mv == NULL)
2443 return NULL;
2444
2445 mv->crc = crc;
2446 memcpy(mv->symbol, symbol, symbollen);
2447 return mv;
2448 }
2449
2450 static void kmod_module_version_free(struct kmod_module_version *version)
2451 {
2452 free(version);
2453 }
2454
2455 /**
2456 * kmod_module_get_versions:
2457 * @mod: kmod module
2458 * @list: where to return list of module versions. Use
2459 * kmod_module_version_get_symbol() and
2460 * kmod_module_version_get_crc(). Release this list with
2461 * kmod_module_versions_free_list()
2462 *
2463 * Get a list of entries in ELF section "__versions".
2464 *
2465 * After use, free the @list by calling kmod_module_versions_free_list().
2466 *
2467 * Returns: 0 on success or < 0 otherwise.
2468 */
2469 KMOD_EXPORT int kmod_module_get_versions(const struct kmod_module *mod, struct kmod_list **list)
2470 {
2471 struct kmod_elf *elf;
2472 struct kmod_modversion *versions;
2473 int i, count, ret = 0;
2474
2475 if (mod == NULL || list == NULL)
2476 return -ENOENT;
2477
2478 assert(*list == NULL);
2479
2480 elf = kmod_module_get_elf(mod);
2481 if (elf == NULL)
2482 return -errno;
2483
2484 count = kmod_elf_get_modversions(elf, &versions);
2485 if (count < 0)
2486 return count;
2487
2488 for (i = 0; i < count; i++) {
2489 struct kmod_module_version *mv;
2490 struct kmod_list *n;
2491
2492 mv = kmod_module_versions_new(versions[i].crc, versions[i].symbol);
2493 if (mv == NULL) {
2494 ret = -errno;
2495 kmod_module_versions_free_list(*list);
2496 *list = NULL;
2497 goto list_error;
2498 }
2499
2500 n = kmod_list_append(*list, mv);
2501 if (n != NULL)
2502 *list = n;
2503 else {
2504 kmod_module_version_free(mv);
2505 kmod_module_versions_free_list(*list);
2506 *list = NULL;
2507 ret = -ENOMEM;
2508 goto list_error;
2509 }
2510 }
2511 ret = count;
2512
2513 list_error:
2514 free(versions);
2515 return ret;
2516 }
2517
2518 /**
2519 * kmod_module_version_get_symbol:
2520 * @entry: a list entry representing a kmod module versions
2521 *
2522 * Get the symbol of a kmod module versions.
2523 *
2524 * Returns: the symbol of this kmod module versions on success or NULL
2525 * on failure. The string is owned by the versions, do not free it.
2526 */
2527 KMOD_EXPORT const char *kmod_module_version_get_symbol(const struct kmod_list *entry)
2528 {
2529 struct kmod_module_version *version;
2530
2531 if (entry == NULL || entry->data == NULL)
2532 return NULL;
2533
2534 version = entry->data;
2535 return version->symbol;
2536 }
2537
2538 /**
2539 * kmod_module_version_get_crc:
2540 * @entry: a list entry representing a kmod module version
2541 *
2542 * Get the crc of a kmod module version.
2543 *
2544 * Returns: the crc of this kmod module version if available, otherwise default to 0.
2545 */
2546 KMOD_EXPORT uint64_t kmod_module_version_get_crc(const struct kmod_list *entry)
2547 {
2548 struct kmod_module_version *version;
2549
2550 if (entry == NULL || entry->data == NULL)
2551 return 0;
2552
2553 version = entry->data;
2554 return version->crc;
2555 }
2556
2557 /**
2558 * kmod_module_versions_free_list:
2559 * @list: kmod module versions list
2560 *
2561 * Release the resources taken by @list
2562 */
2563 KMOD_EXPORT void kmod_module_versions_free_list(struct kmod_list *list)
2564 {
2565 while (list) {
2566 kmod_module_version_free(list->data);
2567 list = kmod_list_remove(list);
2568 }
2569 }
2570
2571 struct kmod_module_symbol {
2572 uint64_t crc;
2573 char symbol[];
2574 };
2575
2576 static struct kmod_module_symbol *kmod_module_symbols_new(uint64_t crc, const char *symbol)
2577 {
2578 struct kmod_module_symbol *mv;
2579 size_t symbollen = strlen(symbol) + 1;
2580
2581 mv = malloc(sizeof(struct kmod_module_symbol) + symbollen);
2582 if (mv == NULL)
2583 return NULL;
2584
2585 mv->crc = crc;
2586 memcpy(mv->symbol, symbol, symbollen);
2587 return mv;
2588 }
2589
2590 static void kmod_module_symbol_free(struct kmod_module_symbol *symbol)
2591 {
2592 free(symbol);
2593 }
2594
2595 /**
2596 * kmod_module_get_symbols:
2597 * @mod: kmod module
2598 * @list: where to return list of module symbols. Use
2599 * kmod_module_symbol_get_symbol() and
2600 * kmod_module_symbol_get_crc(). Release this list with
2601 * kmod_module_symbols_free_list()
2602 *
2603 * Get a list of entries in ELF section ".symtab" or "__ksymtab_strings".
2604 *
2605 * After use, free the @list by calling kmod_module_symbols_free_list().
2606 *
2607 * Returns: 0 on success or < 0 otherwise.
2608 */
2609 KMOD_EXPORT int kmod_module_get_symbols(const struct kmod_module *mod, struct kmod_list **list)
2610 {
2611 struct kmod_elf *elf;
2612 struct kmod_modversion *symbols;
2613 int i, count, ret = 0;
2614
2615 if (mod == NULL || list == NULL)
2616 return -ENOENT;
2617
2618 assert(*list == NULL);
2619
2620 elf = kmod_module_get_elf(mod);
2621 if (elf == NULL)
2622 return -errno;
2623
2624 count = kmod_elf_get_symbols(elf, &symbols);
2625 if (count < 0)
2626 return count;
2627
2628 for (i = 0; i < count; i++) {
2629 struct kmod_module_symbol *mv;
2630 struct kmod_list *n;
2631
2632 mv = kmod_module_symbols_new(symbols[i].crc, symbols[i].symbol);
2633 if (mv == NULL) {
2634 ret = -errno;
2635 kmod_module_symbols_free_list(*list);
2636 *list = NULL;
2637 goto list_error;
2638 }
2639
2640 n = kmod_list_append(*list, mv);
2641 if (n != NULL)
2642 *list = n;
2643 else {
2644 kmod_module_symbol_free(mv);
2645 kmod_module_symbols_free_list(*list);
2646 *list = NULL;
2647 ret = -ENOMEM;
2648 goto list_error;
2649 }
2650 }
2651 ret = count;
2652
2653 list_error:
2654 free(symbols);
2655 return ret;
2656 }
2657
2658 /**
2659 * kmod_module_symbol_get_symbol:
2660 * @entry: a list entry representing a kmod module symbols
2661 *
2662 * Get the symbol of a kmod module symbols.
2663 *
2664 * Returns: the symbol of this kmod module symbols on success or NULL
2665 * on failure. The string is owned by the symbols, do not free it.
2666 */
2667 KMOD_EXPORT const char *kmod_module_symbol_get_symbol(const struct kmod_list *entry)
2668 {
2669 struct kmod_module_symbol *symbol;
2670
2671 if (entry == NULL || entry->data == NULL)
2672 return NULL;
2673
2674 symbol = entry->data;
2675 return symbol->symbol;
2676 }
2677
2678 /**
2679 * kmod_module_symbol_get_crc:
2680 * @entry: a list entry representing a kmod module symbol
2681 *
2682 * Get the crc of a kmod module symbol.
2683 *
2684 * Returns: the crc of this kmod module symbol if available, otherwise default to 0.
2685 */
2686 KMOD_EXPORT uint64_t kmod_module_symbol_get_crc(const struct kmod_list *entry)
2687 {
2688 struct kmod_module_symbol *symbol;
2689
2690 if (entry == NULL || entry->data == NULL)
2691 return 0;
2692
2693 symbol = entry->data;
2694 return symbol->crc;
2695 }
2696
2697 /**
2698 * kmod_module_symbols_free_list:
2699 * @list: kmod module symbols list
2700 *
2701 * Release the resources taken by @list
2702 */
2703 KMOD_EXPORT void kmod_module_symbols_free_list(struct kmod_list *list)
2704 {
2705 while (list) {
2706 kmod_module_symbol_free(list->data);
2707 list = kmod_list_remove(list);
2708 }
2709 }
2710
2711 struct kmod_module_dependency_symbol {
2712 uint64_t crc;
2713 uint8_t bind;
2714 char symbol[];
2715 };
2716
2717 static struct kmod_module_dependency_symbol *kmod_module_dependency_symbols_new(uint64_t crc, uint8_t bind, const char *symbol)
2718 {
2719 struct kmod_module_dependency_symbol *mv;
2720 size_t symbollen = strlen(symbol) + 1;
2721
2722 mv = malloc(sizeof(struct kmod_module_dependency_symbol) + symbollen);
2723 if (mv == NULL)
2724 return NULL;
2725
2726 mv->crc = crc;
2727 mv->bind = bind;
2728 memcpy(mv->symbol, symbol, symbollen);
2729 return mv;
2730 }
2731
2732 static void kmod_module_dependency_symbol_free(struct kmod_module_dependency_symbol *dependency_symbol)
2733 {
2734 free(dependency_symbol);
2735 }
2736
2737 /**
2738 * kmod_module_get_dependency_symbols:
2739 * @mod: kmod module
2740 * @list: where to return list of module dependency_symbols. Use
2741 * kmod_module_dependency_symbol_get_symbol() and
2742 * kmod_module_dependency_symbol_get_crc(). Release this list with
2743 * kmod_module_dependency_symbols_free_list()
2744 *
2745 * Get a list of entries in ELF section ".symtab" or "__ksymtab_strings".
2746 *
2747 * After use, free the @list by calling
2748 * kmod_module_dependency_symbols_free_list().
2749 *
2750 * Returns: 0 on success or < 0 otherwise.
2751 */
2752 KMOD_EXPORT int kmod_module_get_dependency_symbols(const struct kmod_module *mod, struct kmod_list **list)
2753 {
2754 struct kmod_elf *elf;
2755 struct kmod_modversion *symbols;
2756 int i, count, ret = 0;
2757
2758 if (mod == NULL || list == NULL)
2759 return -ENOENT;
2760
2761 assert(*list == NULL);
2762
2763 elf = kmod_module_get_elf(mod);
2764 if (elf == NULL)
2765 return -errno;
2766
2767 count = kmod_elf_get_dependency_symbols(elf, &symbols);
2768 if (count < 0)
2769 return count;
2770
2771 for (i = 0; i < count; i++) {
2772 struct kmod_module_dependency_symbol *mv;
2773 struct kmod_list *n;
2774
2775 mv = kmod_module_dependency_symbols_new(symbols[i].crc,
2776 symbols[i].bind,
2777 symbols[i].symbol);
2778 if (mv == NULL) {
2779 ret = -errno;
2780 kmod_module_dependency_symbols_free_list(*list);
2781 *list = NULL;
2782 goto list_error;
2783 }
2784
2785 n = kmod_list_append(*list, mv);
2786 if (n != NULL)
2787 *list = n;
2788 else {
2789 kmod_module_dependency_symbol_free(mv);
2790 kmod_module_dependency_symbols_free_list(*list);
2791 *list = NULL;
2792 ret = -ENOMEM;
2793 goto list_error;
2794 }
2795 }
2796 ret = count;
2797
2798 list_error:
2799 free(symbols);
2800 return ret;
2801 }
2802
2803 /**
2804 * kmod_module_dependency_symbol_get_symbol:
2805 * @entry: a list entry representing a kmod module dependency_symbols
2806 *
2807 * Get the dependency symbol of a kmod module
2808 *
2809 * Returns: the symbol of this kmod module dependency_symbols on success or NULL
2810 * on failure. The string is owned by the dependency_symbols, do not free it.
2811 */
2812 KMOD_EXPORT const char *kmod_module_dependency_symbol_get_symbol(const struct kmod_list *entry)
2813 {
2814 struct kmod_module_dependency_symbol *dependency_symbol;
2815
2816 if (entry == NULL || entry->data == NULL)
2817 return NULL;
2818
2819 dependency_symbol = entry->data;
2820 return dependency_symbol->symbol;
2821 }
2822
2823 /**
2824 * kmod_module_dependency_symbol_get_crc:
2825 * @entry: a list entry representing a kmod module dependency_symbol
2826 *
2827 * Get the crc of a kmod module dependency_symbol.
2828 *
2829 * Returns: the crc of this kmod module dependency_symbol if available, otherwise default to 0.
2830 */
2831 KMOD_EXPORT uint64_t kmod_module_dependency_symbol_get_crc(const struct kmod_list *entry)
2832 {
2833 struct kmod_module_dependency_symbol *dependency_symbol;
2834
2835 if (entry == NULL || entry->data == NULL)
2836 return 0;
2837
2838 dependency_symbol = entry->data;
2839 return dependency_symbol->crc;
2840 }
2841
2842 /**
2843 * kmod_module_dependency_symbol_get_bind:
2844 * @entry: a list entry representing a kmod module dependency_symbol
2845 *
2846 * Get the bind type of a kmod module dependency_symbol.
2847 *
2848 * Returns: the bind of this kmod module dependency_symbol on success
2849 * or < 0 on failure.
2850 */
2851 KMOD_EXPORT int kmod_module_dependency_symbol_get_bind(const struct kmod_list *entry)
2852 {
2853 struct kmod_module_dependency_symbol *dependency_symbol;
2854
2855 if (entry == NULL || entry->data == NULL)
2856 return 0;
2857
2858 dependency_symbol = entry->data;
2859 return dependency_symbol->bind;
2860 }
2861
2862 /**
2863 * kmod_module_dependency_symbols_free_list:
2864 * @list: kmod module dependency_symbols list
2865 *
2866 * Release the resources taken by @list
2867 */
2868 KMOD_EXPORT void kmod_module_dependency_symbols_free_list(struct kmod_list *list)
2869 {
2870 while (list) {
2871 kmod_module_dependency_symbol_free(list->data);
2872 list = kmod_list_remove(list);
2873 }
2874 }
2875
2876 /**
2877 * kmod_module_get_builtin:
2878 * @ctx: kmod library context
2879 * @list: where to save the builtin module list
2880 *
2881 * Returns: 0 on success or < 0 otherwise.
2882 */
2883 int kmod_module_get_builtin(struct kmod_ctx *ctx, struct kmod_list **list)
2884 {
2885 struct kmod_builtin_iter *iter;
2886 int err = 0;
2887
2888 iter = kmod_builtin_iter_new(ctx);
2889 if (!iter)
2890 return -errno;
2891
2892 while (kmod_builtin_iter_next(iter)) {
2893 struct kmod_module *mod = NULL;
2894 char modname[PATH_MAX];
2895
2896 if (!kmod_builtin_iter_get_modname(iter, modname)) {
2897 err = -errno;
2898 goto fail;
2899 }
2900
2901 kmod_module_new_from_name(ctx, modname, &mod);
2902 kmod_module_set_builtin(mod, true);
2903
2904 *list = kmod_list_append(*list, mod);
2905 }
2906
2907 kmod_builtin_iter_free(iter);
2908 return err;
2909 fail:
2910 kmod_builtin_iter_free(iter);
2911 kmod_module_unref_list(*list);
2912 *list = NULL;
2913 return err;
2914 }