]> git.ipfire.org Git - thirdparty/kmod.git/blob - libkmod/libkmod-module.c
a38a3e221ae1800101dbe4b1c3e342320e6fa36f
[thirdparty/kmod.git] / libkmod / libkmod-module.c
1 /*
2 * libkmod - interface to kernel module operations
3 *
4 * Copyright (C) 2011 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, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21 #include <assert.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stddef.h>
25 #include <stdarg.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <inttypes.h>
31 #include <limits.h>
32 #include <dirent.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <sys/mman.h>
36 #include <string.h>
37
38 #include "libkmod.h"
39 #include "libkmod-private.h"
40
41 /**
42 * kmod_module:
43 *
44 * Opaque object representing a module.
45 */
46 struct kmod_module {
47 struct kmod_ctx *ctx;
48 char *name;
49 char *path;
50 struct kmod_list *dep;
51 char *options;
52 char *install_commands;
53 char *remove_commands;
54 char *alias; /* only set if this module was created from an alias */
55 int n_dep;
56 int refcount;
57 struct {
58 bool dep : 1;
59 bool options : 1;
60 bool install_commands : 1;
61 bool remove_commands : 1;
62 } init;
63 };
64
65 inline char *modname_normalize(const char *modname, char buf[NAME_MAX],
66 size_t *len)
67 {
68 size_t s;
69
70 for (s = 0; s < NAME_MAX - 1; s++) {
71 const char c = modname[s];
72 if (c == '-')
73 buf[s] = '_';
74 else if (c == '\0' || c == '.')
75 break;
76 else
77 buf[s] = c;
78 }
79
80 buf[s] = '\0';
81
82 if (len)
83 *len = s;
84
85 return buf;
86 }
87
88 static char *path_to_modname(const char *path, char buf[NAME_MAX], size_t *len)
89 {
90 char *modname;
91
92 modname = basename(path);
93 if (modname == NULL || modname[0] == '\0')
94 return NULL;
95
96 return modname_normalize(modname, buf, len);
97 }
98
99 static inline const char *path_join(const char *path, size_t prefixlen,
100 char buf[PATH_MAX])
101 {
102 size_t pathlen;
103
104 if (path[0] == '/')
105 return path;
106
107 pathlen = strlen(path);
108 if (prefixlen + pathlen + 1 >= PATH_MAX)
109 return NULL;
110
111 memcpy(buf + prefixlen, path, pathlen + 1);
112 return buf;
113 }
114
115 int kmod_module_parse_depline(struct kmod_module *mod, char *line)
116 {
117 struct kmod_ctx *ctx = mod->ctx;
118 struct kmod_list *list = NULL;
119 const char *dirname;
120 char buf[PATH_MAX];
121 char *p, *saveptr;
122 int err = 0, n = 0;
123 size_t dirnamelen;
124
125 if (mod->init.dep)
126 return mod->n_dep;
127 assert(mod->dep == NULL);
128 mod->init.dep = true;
129
130 p = strchr(line, ':');
131 if (p == NULL)
132 return 0;
133
134 *p = '\0';
135 dirname = kmod_get_dirname(mod->ctx);
136 dirnamelen = strlen(dirname);
137 if (dirnamelen + 2 >= PATH_MAX)
138 return 0;
139
140 memcpy(buf, dirname, dirnamelen);
141 buf[dirnamelen] = '/';
142 dirnamelen++;
143 buf[dirnamelen] = '\0';
144
145 if (mod->path == NULL) {
146 const char *str = path_join(line, dirnamelen, buf);
147 if (str == NULL)
148 return 0;
149 mod->path = strdup(str);
150 if (mod->path == NULL)
151 return 0;
152 }
153
154 p++;
155 for (p = strtok_r(p, " \t", &saveptr); p != NULL;
156 p = strtok_r(NULL, " \t", &saveptr)) {
157 struct kmod_module *depmod;
158 const char *path;
159
160 path = path_join(p, dirnamelen, buf);
161 if (path == NULL) {
162 ERR(ctx, "could not join path '%s' and '%s'.\n",
163 dirname, p);
164 goto fail;
165 }
166
167 err = kmod_module_new_from_path(ctx, path, &depmod);
168 if (err < 0) {
169 ERR(ctx, "ctx=%p path=%s error=%s\n",
170 ctx, path, strerror(-err));
171 goto fail;
172 }
173
174 DBG(ctx, "add dep: %s\n", path);
175
176 list = kmod_list_append(list, depmod);
177 n++;
178 }
179
180 DBG(ctx, "%d dependencies for %s\n", n, mod->name);
181
182 mod->dep = list;
183 mod->n_dep = n;
184 return n;
185
186 fail:
187 kmod_module_unref_list(list);
188 mod->init.dep = false;
189 return err;
190 }
191
192 /**
193 * kmod_module_new_from_name:
194 * @ctx: kmod library context
195 * @name: name of the module
196 * @mod: where to save the created struct kmod_module
197 *
198 * Create a new struct kmod_module using the module name. @name can not be an
199 * alias, file name or anything else; it must be a module name. There's no
200 * check if the module does exists in the system.
201 *
202 * This function is also used internally by many others that return a new
203 * struct kmod_module or a new list of modules.
204 *
205 * The initial refcount is 1, and needs to be decremented to release the
206 * resources of the kmod_module. Since libkmod keeps track of all
207 * kmod_modules created, they are all released upon @ctx destruction too. Do
208 * not unref @ctx before all the desired operations with the returned
209 * kmod_module are done.
210 *
211 * Returns: 0 on success or < 0 otherwise. It fails if name is not a valid
212 * module name or if memory allocation failed.
213 */
214 KMOD_EXPORT int kmod_module_new_from_name(struct kmod_ctx *ctx,
215 const char *name,
216 struct kmod_module **mod)
217 {
218 struct kmod_module *m;
219 size_t namelen;
220 char name_norm[NAME_MAX];
221
222 if (ctx == NULL || name == NULL)
223 return -ENOENT;
224
225 alias_normalize(name, name_norm, &namelen);
226
227 m = kmod_pool_get_module(ctx, name_norm);
228 if (m != NULL) {
229 *mod = kmod_module_ref(m);
230 return 0;
231 }
232
233 m = calloc(1, sizeof(*m) + namelen + 1);
234 if (m == NULL) {
235 free(m);
236 return -ENOMEM;
237 }
238
239 m->ctx = kmod_ref(ctx);
240 m->name = (char *)m + sizeof(*m);
241 memcpy(m->name, name_norm, namelen + 1);
242 m->refcount = 1;
243
244 kmod_pool_add_module(ctx, m);
245
246 *mod = m;
247
248 return 0;
249 }
250
251 int kmod_module_new_from_alias(struct kmod_ctx *ctx, const char *alias,
252 const char *name, struct kmod_module **mod)
253 {
254 int err;
255 struct kmod_module *m;
256
257 err = kmod_module_new_from_name(ctx, alias, mod);
258 if (err < 0)
259 return err;
260
261 m = *mod;
262
263 /* if module did not came from pool */
264 if (m->alias == NULL) {
265 m->alias = m->name;
266 m->name = strdup(name);
267 if (m->name == NULL)
268 goto fail_oom;
269 }
270
271 return 0;
272
273 fail_oom:
274 ERR(ctx, "out of memory\n");
275 kmod_module_unref(m);
276 *mod = NULL;
277 return err;
278 }
279
280 /**
281 * kmod_module_new_from_path:
282 * @ctx: kmod library context
283 * @path: path where to find the given module
284 * @mod: where to save the created struct kmod_module
285 *
286 * Create a new struct kmod_module using the module path. @path must be an
287 * existent file with in the filesystem and must be accessible to libkmod.
288 *
289 * The initial refcount is 1, and needs to be decremented to release the
290 * resources of the kmod_module. Since libkmod keeps track of all
291 * kmod_modules created, they are all released upon @ctx destruction too. Do
292 * not unref @ctx before all the desired operations with the returned
293 * kmod_module are done.
294 *
295 * If @path is relative, it's treated as relative to the current working
296 * directory. Otherwise, give an absolute path.
297 *
298 * Returns: 0 on success or < 0 otherwise. It fails if file does not exist, if
299 * it's not a valid file for a kmod_module or if memory allocation failed.
300 */
301 KMOD_EXPORT int kmod_module_new_from_path(struct kmod_ctx *ctx,
302 const char *path,
303 struct kmod_module **mod)
304 {
305 struct kmod_module *m;
306 int err;
307 struct stat st;
308 char name[NAME_MAX];
309 char *abspath;
310 size_t namelen;
311
312 if (ctx == NULL || path == NULL)
313 return -ENOENT;
314
315 abspath = path_make_absolute_cwd(path);
316 if (abspath == NULL)
317 return -ENOMEM;
318
319 err = stat(abspath, &st);
320 if (err < 0) {
321 free(abspath);
322 return -errno;
323 }
324
325 if (path_to_modname(path, name, &namelen) == NULL) {
326 free(abspath);
327 return -ENOENT;
328 }
329
330 m = kmod_pool_get_module(ctx, name);
331 if (m != NULL) {
332 if (m->path == NULL)
333 m->path = abspath;
334 else if (streq(m->path, abspath))
335 free(abspath);
336 else {
337 ERR(ctx, "kmod_module '%s' already exists with different path\n",
338 name);
339 free(abspath);
340 return -EEXIST;
341 }
342
343 *mod = kmod_module_ref(m);
344 return 0;
345 }
346
347 m = calloc(1, sizeof(*m) + namelen + 1);
348 if (m == NULL)
349 return -errno;
350
351 m->ctx = kmod_ref(ctx);
352 m->name = (char *)m + sizeof(*m);
353 memcpy(m->name, name, namelen);
354 m->path = abspath;
355 m->refcount = 1;
356
357 kmod_pool_add_module(ctx, m);
358
359 *mod = m;
360
361 return 0;
362 }
363
364 /**
365 * kmod_module_unref:
366 * @mod: kmod module
367 *
368 * Drop a reference of the kmod module. If the refcount reaches zero, its
369 * resources are released.
370 *
371 * Returns: NULL if @mod is NULL or if the module was released. Otherwise it
372 * returns the passed @mod with its refcount decremented.
373 */
374 KMOD_EXPORT struct kmod_module *kmod_module_unref(struct kmod_module *mod)
375 {
376 if (mod == NULL)
377 return NULL;
378
379 if (--mod->refcount > 0)
380 return mod;
381
382 DBG(mod->ctx, "kmod_module %p released\n", mod);
383
384 kmod_module_unref_list(mod->dep);
385 kmod_unref(mod->ctx);
386 free(mod->options);
387 free(mod->install_commands);
388 free(mod->remove_commands);
389 free(mod->path);
390 if (mod->alias != NULL)
391 free(mod->name);
392 free(mod);
393 return NULL;
394 }
395
396 /**
397 * kmod_module_ref:
398 * @mod: kmod module
399 *
400 * Take a reference of the kmod module, incrementing its refcount.
401 *
402 * Returns: the passed @module with its refcount incremented.
403 */
404 KMOD_EXPORT struct kmod_module *kmod_module_ref(struct kmod_module *mod)
405 {
406 if (mod == NULL)
407 return NULL;
408
409 mod->refcount++;
410
411 return mod;
412 }
413
414 #define CHECK_ERR_AND_FINISH(_err, _label_err, _list, label_finish) \
415 do { \
416 if ((_err) < 0) \
417 goto _label_err; \
418 if (*(_list) != NULL) \
419 goto finish; \
420 } while (0)
421
422 /**
423 * kmod_module_new_from_lookup:
424 * @ctx: kmod library context
425 * @given_alias: alias to look for
426 * @list: an empty list where to save the list of modules matching
427 * @given_alias
428 *
429 * Create a new list of kmod modules using an alias or module name and lookup
430 * libkmod's configuration files and indexes in order to find the module.
431 * Once it's found in one of the places, it stops searching and create the
432 * list of modules that is saved in @list.
433 *
434 * The search order is: 1. aliases in configuration file; 2. module names in
435 * modules.dep index; 3. symbol aliases in modules.symbols index; 4. aliases
436 * in modules.alias index.
437 *
438 * The initial refcount is 1, and needs to be decremented to release the
439 * resources of the kmod_module. The returned @list must be released by
440 * calling kmod_module_unref_list(). Since libkmod keeps track of all
441 * kmod_modules created, they are all released upon @ctx destruction too. Do
442 * not unref @ctx before all the desired operations with the returned list are
443 * completed.
444 *
445 * Returns: 0 on success or < 0 otherwise. It fails if any of the lookup
446 * methods failed, which is basically due to memory allocation fail. If module
447 * is not found, it still returns 0, but @list is an empty list.
448 */
449 KMOD_EXPORT int kmod_module_new_from_lookup(struct kmod_ctx *ctx,
450 const char *given_alias,
451 struct kmod_list **list)
452 {
453 int err;
454 char alias[NAME_MAX];
455
456 if (ctx == NULL || given_alias == NULL)
457 return -ENOENT;
458
459 if (list == NULL || *list != NULL) {
460 ERR(ctx, "An empty list is needed to create lookup\n");
461 return -ENOSYS;
462 }
463
464 if (alias_normalize(given_alias, alias, NULL) < 0)
465 return -EINVAL;
466
467 /* Aliases from config file override all the others */
468 err = kmod_lookup_alias_from_config(ctx, alias, list);
469 CHECK_ERR_AND_FINISH(err, fail, list, finish);
470
471 err = kmod_lookup_alias_from_moddep_file(ctx, alias, list);
472 CHECK_ERR_AND_FINISH(err, fail, list, finish);
473
474 err = kmod_lookup_alias_from_symbols_file(ctx, alias, list);
475 CHECK_ERR_AND_FINISH(err, fail, list, finish);
476
477 // TODO: add lookup for install commands here.
478
479 err = kmod_lookup_alias_from_aliases_file(ctx, alias, list);
480 CHECK_ERR_AND_FINISH(err, fail, list, finish);
481
482 finish:
483
484 return err;
485 fail:
486 kmod_module_unref_list(*list);
487 *list = NULL;
488 return err;
489 }
490 #undef CHECK_ERR_AND_FINISH
491
492 /**
493 * kmod_module_unref:
494 * @list: list of kmod modules
495 *
496 * Drop a reference of each kmod module in @list and releases the resources
497 * taken by the list itself.
498 *
499 * Returns: NULL if @mod is NULL or if the module was released. Otherwise it
500 * returns the passed @mod with its refcount decremented.
501 */
502 KMOD_EXPORT int kmod_module_unref_list(struct kmod_list *list)
503 {
504 for (; list != NULL; list = kmod_list_remove(list))
505 kmod_module_unref(list->data);
506
507 return 0;
508 }
509
510 /**
511 * kmod_module_unref:
512 * @mod: kmod module
513 *
514 * Search the modules.dep index to find the dependencies of the given @mod.
515 * The result is cached in @mod, so subsequent calls to this function will
516 * return the already searched list of modules.
517 *
518 * Returns: NULL on failure or if there are any dependencies. Otherwise it
519 * returns a list of kmod modules that can be released by calling
520 * kmod_module_unref_list().
521 */
522 KMOD_EXPORT struct kmod_list *kmod_module_get_dependencies(const struct kmod_module *mod)
523 {
524 struct kmod_list *l, *l_new, *list_new = NULL;
525
526 if (mod == NULL)
527 return NULL;
528
529 if (!mod->init.dep) {
530 /* lazy init */
531 char *line = kmod_search_moddep(mod->ctx, mod->name);
532
533 if (line == NULL)
534 return NULL;
535
536 kmod_module_parse_depline((struct kmod_module *)mod, line);
537 free(line);
538
539 if (!mod->init.dep)
540 return NULL;
541 }
542
543 kmod_list_foreach(l, mod->dep) {
544 l_new = kmod_list_append(list_new, kmod_module_ref(l->data));
545 if (l_new == NULL) {
546 kmod_module_unref(l->data);
547 goto fail;
548 }
549
550 list_new = l_new;
551 }
552
553 return list_new;
554
555 fail:
556 ERR(mod->ctx, "out of memory\n");
557 kmod_module_unref_list(list_new);
558 return NULL;
559 }
560
561 /**
562 * kmod_module_get_module:
563 * @entry: an entry in a list of kmod modules.
564 *
565 * Get the kmod module of this @entry in the list, increasing its refcount.
566 * After it's used, unref it. Since the refcount is incremented upon return,
567 * you still have to call kmod_module_unref_list() to release the list of kmod
568 * modules.
569 *
570 * Returns: NULL on failure or the kmod_module contained in this list entry
571 * with its refcount incremented.
572 */
573 KMOD_EXPORT struct kmod_module *kmod_module_get_module(const struct kmod_list *entry)
574 {
575 if (entry == NULL)
576 return NULL;
577
578 return kmod_module_ref(entry->data);
579 }
580
581 /**
582 * kmod_module_get_size:
583 * @mod: kmod module
584 *
585 * Get the size of this kmod module as returned by Linux kernel. It reads the
586 * file /proc/modules to search for this module and get its size.
587 *
588 * Returns: the size of this kmod module.
589 */
590 KMOD_EXPORT long kmod_module_get_size(const struct kmod_module *mod)
591 {
592 // FIXME TODO: this should be available from /sys/module/foo
593 FILE *fp;
594 char line[4096];
595 int lineno = 0;
596 long size = -ENOENT;
597
598 if (mod == NULL)
599 return -ENOENT;
600
601 fp = fopen("/proc/modules", "r");
602 if (fp == NULL) {
603 int err = -errno;
604 ERR(mod->ctx,
605 "could not open /proc/modules: %s\n", strerror(errno));
606 return err;
607 }
608
609 while (fgets(line, sizeof(line), fp)) {
610 char *saveptr, *endptr, *tok = strtok_r(line, " \t", &saveptr);
611 long value;
612
613 lineno++;
614 if (tok == NULL || !streq(tok, mod->name))
615 continue;
616
617 tok = strtok_r(NULL, " \t", &saveptr);
618 if (tok == NULL) {
619 ERR(mod->ctx,
620 "invalid line format at /proc/modules:%d\n", lineno);
621 break;
622 }
623
624 value = strtol(tok, &endptr, 10);
625 if (endptr == tok || *endptr != '\0') {
626 ERR(mod->ctx,
627 "invalid line format at /proc/modules:%d\n", lineno);
628 break;
629 }
630
631 size = value;
632 break;
633 }
634 fclose(fp);
635 return size;
636 }
637
638 /**
639 * kmod_module_get_name:
640 * @mod: kmod module
641 *
642 * Get the name of this kmod module. Name is always available, independently
643 * if it was created by kmod_module_new_from_name() or another function and
644 * it's always normalized (dashes are replaced with underscores).
645 *
646 * Returns: the name of this kmod module.
647 */
648 KMOD_EXPORT const char *kmod_module_get_name(const struct kmod_module *mod)
649 {
650 return mod->name;
651 }
652
653 /**
654 * kmod_module_get_path:
655 * @mod: kmod module
656 *
657 * Get the path of this kmod module. If this kmod module was not created by
658 * path, it can search the modules.dep index in order to find out the module
659 * under context's dirname (see kmod_get_dirname()).
660 *
661 * Returns: the path of this kmod module or NULL if such information is not
662 * available.
663 */
664 KMOD_EXPORT const char *kmod_module_get_path(const struct kmod_module *mod)
665 {
666 char *line;
667
668 DBG(mod->ctx, "name='%s' path='%s'\n", mod->name, mod->path);
669
670 if (mod->path != NULL)
671 return mod->path;
672 if (mod->init.dep)
673 return NULL;
674
675 /* lazy init */
676 line = kmod_search_moddep(mod->ctx, mod->name);
677 if (line == NULL)
678 return NULL;
679
680 kmod_module_parse_depline((struct kmod_module *) mod, line);
681 free(line);
682
683 return mod->path;
684 }
685
686
687 extern long delete_module(const char *name, unsigned int flags);
688
689 /**
690 * kmod_module_remove_module:
691 * @mod: kmod module
692 * @flags: flags to pass to Linux kernel when removing the module
693 *
694 * Remove a module from Linux kernel.
695 *
696 * Returns: 0 on success or < 0 on failure.
697 */
698 KMOD_EXPORT int kmod_module_remove_module(struct kmod_module *mod,
699 unsigned int flags)
700 {
701 int err;
702
703 if (mod == NULL)
704 return -ENOENT;
705
706 /* Filter out other flags */
707 flags &= (KMOD_REMOVE_FORCE | KMOD_REMOVE_NOWAIT);
708
709 err = delete_module(mod->name, flags);
710 if (err != 0) {
711 ERR(mod->ctx, "Removing '%s': %s\n", mod->name,
712 strerror(-err));
713 return err;
714 }
715
716 return 0;
717 }
718
719 extern long init_module(void *mem, unsigned long len, const char *args);
720
721 /**
722 * kmod_module_insert_module:
723 * @mod: kmod module
724 * @flags: flags are not passed to Linux Kernel, but instead it dictates the
725 * behavior of this function. They are not implemented yet.
726 * @options: module's options to pass to Linux Kernel.
727 *
728 * Insert a module in Linux kernel. It opens the file pointed by @mod,
729 * mmap'ing it and passing to kernel.
730 *
731 * Returns: 0 on success or < 0 on failure.
732 */
733 KMOD_EXPORT int kmod_module_insert_module(struct kmod_module *mod,
734 unsigned int flags,
735 const char *options)
736 {
737 int err;
738 void *mmaped_file;
739 struct stat st;
740 int fd;
741 const char *args = options ? options : "";
742
743 if (mod == NULL)
744 return -ENOENT;
745
746 if (mod->path == NULL) {
747 ERR(mod->ctx, "Not supported to load a module by name yet\n");
748 return -ENOSYS;
749 }
750
751 if (flags != 0)
752 INFO(mod->ctx, "Flags are not implemented yet\n");
753
754 if ((fd = open(mod->path, O_RDONLY)) < 0) {
755 err = -errno;
756 return err;
757 }
758
759 fstat(fd, &st);
760
761 if ((mmaped_file = mmap(0, st.st_size, PROT_READ,
762 MAP_PRIVATE, fd, 0)) == MAP_FAILED) {
763 close(fd);
764 return -errno;
765 }
766
767 err = init_module(mmaped_file, st.st_size, args);
768 if (err < 0)
769 ERR(mod->ctx, "Failed to insert module '%s'\n", mod->path);
770
771 munmap(mmaped_file, st.st_size);
772 close(fd);
773
774 return err;
775 }
776
777 /**
778 * kmod_module_get_options:
779 * @mod: kmod module
780 *
781 * Get options of this kmod module. Options come from the configuration file
782 * and are cached in @mod. The first call to this function will search for
783 * this module in configuration and subsequent calls return the cached string.
784 *
785 * Returns: a string with all the options separated by spaces. This string is
786 * owned by @mod, do not free it.
787 */
788 KMOD_EXPORT const char *kmod_module_get_options(const struct kmod_module *mod)
789 {
790 if (mod == NULL)
791 return NULL;
792
793 if (!mod->init.options) {
794 /* lazy init */
795 struct kmod_module *m = (struct kmod_module *)mod;
796 const struct kmod_list *l, *ctx_options;
797 char *opts = NULL;
798 size_t optslen = 0;
799
800 ctx_options = kmod_get_options(mod->ctx);
801
802 kmod_list_foreach(l, ctx_options) {
803 const char *modname = kmod_option_get_modname(l);
804 const char *str;
805 size_t len;
806 void *tmp;
807
808 DBG(mod->ctx, "modname=%s mod->name=%s mod->alias=%s\n", modname, mod->name, mod->alias);
809 if (!(streq(modname, mod->name) || (mod->alias != NULL &&
810 streq(modname, mod->alias))))
811 continue;
812
813 DBG(mod->ctx, "passed = modname=%s mod->name=%s mod->alias=%s\n", modname, mod->name, mod->alias);
814 str = kmod_option_get_options(l);
815 len = strlen(str);
816 if (len < 1)
817 continue;
818
819 tmp = realloc(opts, optslen + len + 2);
820 if (tmp == NULL) {
821 free(opts);
822 goto failed;
823 }
824
825 opts = tmp;
826
827 if (optslen > 0) {
828 opts[optslen] = ' ';
829 optslen++;
830 }
831
832 memcpy(opts + optslen, str, len);
833 optslen += len;
834 opts[optslen] = '\0';
835 }
836
837 m->init.options = true;
838 m->options = opts;
839 }
840
841 return mod->options;
842
843 failed:
844 ERR(mod->ctx, "out of memory\n");
845 return NULL;
846 }
847
848 /**
849 * kmod_module_get_install_commands:
850 * @mod: kmod module
851 *
852 * Get install commands for this kmod module. Install commands come from the
853 * configuration file and are cached in @mod. The first call to this function
854 * will search for this module in configuration and subsequent calls return
855 * the cached string. The install commands are returned as they were in the
856 * configuration, concatenated by ';'. No other processing is made in this
857 * string.
858 *
859 * Returns: a string with all install commands separated by semicolons. This
860 * string is owned by @mod, do not free it.
861 */
862 KMOD_EXPORT const char *kmod_module_get_install_commands(const struct kmod_module *mod)
863 {
864 if (mod == NULL)
865 return NULL;
866
867 if (!mod->init.install_commands) {
868 /* lazy init */
869 struct kmod_module *m = (struct kmod_module *)mod;
870 const struct kmod_list *l, *ctx_install_commands;
871 char *cmds = NULL;
872 size_t cmdslen = 0;
873
874 ctx_install_commands = kmod_get_install_commands(mod->ctx);
875
876 kmod_list_foreach(l, ctx_install_commands) {
877 const char *modname = kmod_command_get_modname(l);
878 const char *str;
879 size_t len;
880 void *tmp;
881
882 if (strcmp(modname, mod->name) != 0)
883 continue;
884
885 str = kmod_command_get_command(l);
886 len = strlen(str);
887 if (len < 1)
888 continue;
889
890 tmp = realloc(cmds, cmdslen + len + 2);
891 if (tmp == NULL) {
892 free(cmds);
893 goto failed;
894 }
895
896 cmds = tmp;
897
898 if (cmdslen > 0) {
899 cmds[cmdslen] = ';';
900 cmdslen++;
901 }
902
903 memcpy(cmds + cmdslen, str, len);
904 cmdslen += len;
905 cmds[cmdslen] = '\0';
906 }
907
908 m->init.install_commands = true;
909 m->install_commands = cmds;
910 }
911
912 return mod->install_commands;
913
914 failed:
915 ERR(mod->ctx, "out of memory\n");
916 return NULL;
917 }
918
919 /**
920 * kmod_module_get_remove_commands:
921 * @mod: kmod module
922 *
923 * Get remove commands for this kmod module. Remove commands come from the
924 * configuration file and are cached in @mod. The first call to this function
925 * will search for this module in configuration and subsequent calls return
926 * the cached string. The remove commands are returned as they were in the
927 * configuration, concatenated by ';'. No other processing is made in this
928 * string.
929 *
930 * Returns: a string with all remove commands separated by semicolons. This
931 * string is owned by @mod, do not free it.
932 */
933 KMOD_EXPORT const char *kmod_module_get_remove_commands(const struct kmod_module *mod)
934 {
935 if (mod == NULL)
936 return NULL;
937
938 if (!mod->init.remove_commands) {
939 /* lazy init */
940 struct kmod_module *m = (struct kmod_module *)mod;
941 const struct kmod_list *l, *ctx_remove_commands;
942 char *cmds = NULL;
943 size_t cmdslen = 0;
944
945 ctx_remove_commands = kmod_get_remove_commands(mod->ctx);
946
947 kmod_list_foreach(l, ctx_remove_commands) {
948 const char *modname = kmod_command_get_modname(l);
949 const char *str;
950 size_t len;
951 void *tmp;
952
953 if (strcmp(modname, mod->name) != 0)
954 continue;
955
956 str = kmod_command_get_command(l);
957 len = strlen(str);
958 if (len < 1)
959 continue;
960
961 tmp = realloc(cmds, cmdslen + len + 2);
962 if (tmp == NULL) {
963 free(cmds);
964 goto failed;
965 }
966
967 cmds = tmp;
968
969 if (cmdslen > 0) {
970 cmds[cmdslen] = ';';
971 cmdslen++;
972 }
973
974 memcpy(cmds + cmdslen, str, len);
975 cmdslen += len;
976 cmds[cmdslen] = '\0';
977 }
978
979 m->init.remove_commands = true;
980 m->remove_commands = cmds;
981 }
982
983 return mod->remove_commands;
984
985 failed:
986 ERR(mod->ctx, "out of memory\n");
987 return NULL;
988 }
989
990 /**
991 * SECTION:libkmod-loaded
992 * @short_description: currently loaded modules
993 *
994 * Information about currently loaded modules, as reported by Linux kernel.
995 * These information are not cached by libkmod and are always read from /sys
996 * and /proc/modules.
997 */
998
999 /**
1000 * kmod_module_new_from_loaded:
1001 * @ctx: kmod library context
1002 * @list: where to save the list of loaded modules
1003 *
1004 * Create a new list of kmod modules with all modules currently loaded in
1005 * kernel. It uses /proc/modules to get the names of loaded modules and to
1006 * create kmod modules by calling kmod_module_new_from_name() in each of them.
1007 * They are put are put in @list in no particular order.
1008 *
1009 * The initial refcount is 1, and needs to be decremented to release the
1010 * resources of the kmod_module. The returned @list must be released by
1011 * calling kmod_module_unref_list(). Since libkmod keeps track of all
1012 * kmod_modules created, they are all released upon @ctx destruction too. Do
1013 * not unref @ctx before all the desired operations with the returned list are
1014 * completed.
1015 *
1016 * Returns: 0 on success or < 0 on error.
1017 */
1018 KMOD_EXPORT int kmod_module_new_from_loaded(struct kmod_ctx *ctx,
1019 struct kmod_list **list)
1020 {
1021 struct kmod_list *l = NULL;
1022 FILE *fp;
1023 char line[4096];
1024
1025 if (ctx == NULL || list == NULL)
1026 return -ENOENT;
1027
1028 fp = fopen("/proc/modules", "r");
1029 if (fp == NULL) {
1030 int err = -errno;
1031 ERR(ctx, "could not open /proc/modules: %s\n", strerror(errno));
1032 return err;
1033 }
1034
1035 while (fgets(line, sizeof(line), fp)) {
1036 struct kmod_module *m;
1037 struct kmod_list *node;
1038 int err;
1039 char *saveptr, *name = strtok_r(line, " \t", &saveptr);
1040
1041 err = kmod_module_new_from_name(ctx, name, &m);
1042 if (err < 0) {
1043 ERR(ctx, "could not get module from name '%s': %s\n",
1044 name, strerror(-err));
1045 continue;
1046 }
1047
1048 node = kmod_list_append(l, m);
1049 if (node)
1050 l = node;
1051 else {
1052 ERR(ctx, "out of memory\n");
1053 kmod_module_unref(m);
1054 }
1055 }
1056
1057 fclose(fp);
1058 *list = l;
1059
1060 return 0;
1061 }
1062
1063 /**
1064 * kmod_module_initstate_str:
1065 * @state: the state as returned by kmod_module_get_initstate()
1066 *
1067 * Translate a initstate to a string.
1068 *
1069 * Returns: the string associated to the @state. This string is statically
1070 * allocated, do not free it.
1071 */
1072 KMOD_EXPORT const char *kmod_module_initstate_str(enum kmod_module_initstate state)
1073 {
1074 switch (state) {
1075 case KMOD_MODULE_BUILTIN:
1076 return "builtin";
1077 case KMOD_MODULE_LIVE:
1078 return "live";
1079 case KMOD_MODULE_COMING:
1080 return "coming";
1081 case KMOD_MODULE_GOING:
1082 return "going";
1083 default:
1084 return NULL;
1085 }
1086 }
1087
1088 /**
1089 * kmod_module_get_initstate:
1090 * @mod: kmod module
1091 *
1092 * Get the initstate of this @mod, as returned by Linux Kernel, by reading
1093 * /sys filesystem.
1094 *
1095 * Returns: < 0 on error or enum kmod_initstate if module is found in kernel.
1096 */
1097 KMOD_EXPORT int kmod_module_get_initstate(const struct kmod_module *mod)
1098 {
1099 char path[PATH_MAX], buf[32];
1100 int fd, err, pathlen;
1101
1102 pathlen = snprintf(path, sizeof(path),
1103 "/sys/module/%s/initstate", mod->name);
1104 fd = open(path, O_RDONLY);
1105 if (fd < 0) {
1106 err = -errno;
1107
1108 if (pathlen > (int)sizeof("/initstate") - 1) {
1109 struct stat st;
1110 path[pathlen - (sizeof("/initstate") - 1)] = '\0';
1111 if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
1112 return KMOD_MODULE_BUILTIN;
1113 }
1114
1115 DBG(mod->ctx, "could not open '%s': %s\n",
1116 path, strerror(-err));
1117 return err;
1118 }
1119
1120 err = read_str_safe(fd, buf, sizeof(buf));
1121 close(fd);
1122 if (err < 0) {
1123 ERR(mod->ctx, "could not read from '%s': %s\n",
1124 path, strerror(-err));
1125 return err;
1126 }
1127
1128 if (streq(buf, "live\n"))
1129 return KMOD_MODULE_LIVE;
1130 else if (streq(buf, "coming\n"))
1131 return KMOD_MODULE_COMING;
1132 else if (streq(buf, "going\n"))
1133 return KMOD_MODULE_GOING;
1134
1135 ERR(mod->ctx, "unknown %s: '%s'\n", path, buf);
1136 return -EINVAL;
1137 }
1138
1139 /**
1140 * kmod_module_get_refcnt:
1141 * @mod: kmod module
1142 *
1143 * Get the ref count of this @mod, as returned by Linux Kernel, by reading
1144 * /sys filesystem.
1145 *
1146 * Returns: 0 on success or < 0 on failure.
1147 */
1148 KMOD_EXPORT int kmod_module_get_refcnt(const struct kmod_module *mod)
1149 {
1150 char path[PATH_MAX];
1151 long refcnt;
1152 int fd, err;
1153
1154 snprintf(path, sizeof(path), "/sys/module/%s/refcnt", mod->name);
1155 fd = open(path, O_RDONLY);
1156 if (fd < 0) {
1157 err = -errno;
1158 ERR(mod->ctx, "could not open '%s': %s\n",
1159 path, strerror(errno));
1160 return err;
1161 }
1162
1163 err = read_str_long(fd, &refcnt, 10);
1164 close(fd);
1165 if (err < 0) {
1166 ERR(mod->ctx, "could not read integer from '%s': '%s'\n",
1167 path, strerror(-err));
1168 return err;
1169 }
1170
1171 return (int)refcnt;
1172 }
1173
1174 /**
1175 * kmod_module_get_holders:
1176 * @mod: kmod module
1177 *
1178 * Get a list of kmod modules that are holding this @mod, as returned by Linux
1179 * Kernel. After use, free the @list by calling kmod_module_unref_list().
1180 *
1181 * Returns: a new list of kmod modules on success or NULL on failure.
1182 */
1183 KMOD_EXPORT struct kmod_list *kmod_module_get_holders(const struct kmod_module *mod)
1184 {
1185 char dname[PATH_MAX];
1186 struct kmod_list *list = NULL;
1187 DIR *d;
1188
1189 if (mod == NULL)
1190 return NULL;
1191 snprintf(dname, sizeof(dname), "/sys/module/%s/holders", mod->name);
1192
1193 d = opendir(dname);
1194 if (d == NULL) {
1195 ERR(mod->ctx, "could not open '%s': %s\n",
1196 dname, strerror(errno));
1197 return NULL;
1198 }
1199
1200 for (;;) {
1201 struct dirent de, *entp;
1202 struct kmod_module *holder;
1203 struct kmod_list *l;
1204 int err;
1205
1206 err = readdir_r(d, &de, &entp);
1207 if (err != 0) {
1208 ERR(mod->ctx, "could not iterate for module '%s': %s\n",
1209 mod->name, strerror(-err));
1210 goto fail;
1211 }
1212
1213 if (entp == NULL)
1214 break;
1215
1216 if (de.d_name[0] == '.') {
1217 if (de.d_name[1] == '\0' ||
1218 (de.d_name[1] == '.' && de.d_name[2] == '\0'))
1219 continue;
1220 }
1221
1222 err = kmod_module_new_from_name(mod->ctx, de.d_name, &holder);
1223 if (err < 0) {
1224 ERR(mod->ctx, "could not create module for '%s': %s\n",
1225 de.d_name, strerror(-err));
1226 goto fail;
1227 }
1228
1229 l = kmod_list_append(list, holder);
1230 if (l != NULL) {
1231 list = l;
1232 } else {
1233 ERR(mod->ctx, "out of memory\n");
1234 kmod_module_unref(holder);
1235 goto fail;
1236 }
1237 }
1238
1239 closedir(d);
1240 return list;
1241
1242 fail:
1243 closedir(d);
1244 kmod_module_unref_list(list);
1245 return NULL;
1246 }
1247
1248 struct kmod_module_section {
1249 unsigned long address;
1250 char name[];
1251 };
1252
1253 static void kmod_module_section_free(struct kmod_module_section *section)
1254 {
1255 free(section);
1256 }
1257
1258 /**
1259 * kmod_module_get_sections:
1260 * @mod: kmod module
1261 *
1262 * Get a list of kmod sections of this @mod, as returned by Linux Kernel. The
1263 * structure contained in this list is internal to libkmod and their fields
1264 * can be obtained by calling kmod_module_section_get_name() and
1265 * kmod_module_section_get_address().
1266 *
1267 * After use, free the @list by calling kmod_module_section_free_list().
1268 *
1269 * Returns: a new list of kmod module sections on success or NULL on failure.
1270 */
1271 KMOD_EXPORT struct kmod_list *kmod_module_get_sections(const struct kmod_module *mod)
1272 {
1273 char dname[PATH_MAX];
1274 struct kmod_list *list = NULL;
1275 DIR *d;
1276 int dfd;
1277
1278 if (mod == NULL)
1279 return NULL;
1280
1281 snprintf(dname, sizeof(dname), "/sys/module/%s/sections", mod->name);
1282
1283 d = opendir(dname);
1284 if (d == NULL) {
1285 ERR(mod->ctx, "could not open '%s': %s\n",
1286 dname, strerror(errno));
1287 return NULL;
1288 }
1289
1290 dfd = dirfd(d);
1291
1292 for (;;) {
1293 struct dirent de, *entp;
1294 struct kmod_module_section *section;
1295 struct kmod_list *l;
1296 unsigned long address;
1297 size_t namesz;
1298 int fd, err;
1299
1300 err = readdir_r(d, &de, &entp);
1301 if (err != 0) {
1302 ERR(mod->ctx, "could not iterate for module '%s': %s\n",
1303 mod->name, strerror(-err));
1304 goto fail;
1305 }
1306
1307 if (de.d_name[0] == '.') {
1308 if (de.d_name[1] == '\0' ||
1309 (de.d_name[1] == '.' && de.d_name[2] == '\0'))
1310 continue;
1311 }
1312
1313 fd = openat(dfd, de.d_name, O_RDONLY);
1314 if (fd < 0) {
1315 ERR(mod->ctx, "could not open '%s/%s': %m\n",
1316 dname, de.d_name);
1317 goto fail;
1318 }
1319
1320 err = read_str_ulong(fd, &address, 16);
1321 close(fd);
1322 if (err < 0) {
1323 ERR(mod->ctx, "could not read long from '%s/%s': %m\n",
1324 dname, de.d_name);
1325 goto fail;
1326 }
1327
1328 namesz = strlen(de.d_name) + 1;
1329 section = malloc(sizeof(*section) + namesz);
1330
1331 if (section == NULL) {
1332 ERR(mod->ctx, "out of memory\n");
1333 goto fail;
1334 }
1335
1336 section->address = address;
1337 memcpy(section->name, de.d_name, namesz);
1338
1339 l = kmod_list_append(list, section);
1340 if (l != NULL) {
1341 list = l;
1342 } else {
1343 ERR(mod->ctx, "out of memory\n");
1344 free(section);
1345 goto fail;
1346 }
1347 }
1348
1349 closedir(d);
1350 return list;
1351
1352 fail:
1353 closedir(d);
1354 kmod_module_unref_list(list);
1355 return NULL;
1356 }
1357
1358 /**
1359 * kmod_module_section_get_module_name:
1360 * @entry: a list entry representing a kmod module section
1361 *
1362 * Get the name of a kmod module section.
1363 *
1364 * After use, free the @list by calling kmod_module_section_free_list().
1365 *
1366 * Returns: the name of this kmod module section on success or NULL on
1367 * failure. The string is owned by the section, do not free it.
1368 */
1369 KMOD_EXPORT const char *kmod_module_section_get_name(const struct kmod_list *entry)
1370 {
1371 struct kmod_module_section *section;
1372
1373 if (entry == NULL)
1374 return NULL;
1375
1376 section = entry->data;
1377 return section->name;
1378 }
1379
1380 /**
1381 * kmod_module_section_get_address:
1382 * @entry: a list entry representing a kmod module section
1383 *
1384 * Get the address of a kmod module section.
1385 *
1386 * After use, free the @list by calling kmod_module_section_free_list().
1387 *
1388 * Returns: the address of this kmod module section on success or ULONG_MAX
1389 * on failure.
1390 */
1391 KMOD_EXPORT unsigned long kmod_module_section_get_address(const struct kmod_list *entry)
1392 {
1393 struct kmod_module_section *section;
1394
1395 if (entry == NULL)
1396 return (unsigned long)-1;
1397
1398 section = entry->data;
1399 return section->address;
1400 }
1401
1402 /**
1403 * kmod_module_section_free_list:
1404 * @list: kmod module section list
1405 *
1406 * Release the resources taken by @list
1407 */
1408 KMOD_EXPORT void kmod_module_section_free_list(struct kmod_list *list)
1409 {
1410 while (list) {
1411 kmod_module_section_free(list->data);
1412 list = kmod_list_remove(list);
1413 }
1414 }