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