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