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