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