1/*
2 * kmod-lsmod - list modules from linux kernel using libkmod.
3 *
4 * Copyright (C) 2011-2013  ProFUSION embedded systems
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program 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
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include <errno.h>
21#include <stddef.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#include <unistd.h>
26
27#include <libkmod/libkmod.h>
28
29#include "kmod.h"
30
31static int do_lsmod(int argc, char *argv[])
32{
33	struct kmod_ctx *ctx;
34	const char *null_config = NULL;
35	struct kmod_list *list, *itr;
36	int err;
37
38	if (argc != 1) {
39		fprintf(stderr, "Usage: %s\n", argv[0]);
40		return EXIT_FAILURE;
41	}
42
43	ctx = kmod_new(NULL, &null_config);
44	if (ctx == NULL) {
45		fputs("Error: kmod_new() failed!\n", stderr);
46		return EXIT_FAILURE;
47	}
48
49	err = kmod_module_new_from_loaded(ctx, &list);
50	if (err < 0) {
51		fprintf(stderr, "Error: could not get list of modules: %s\n",
52			strerror(-err));
53		kmod_unref(ctx);
54		return EXIT_FAILURE;
55	}
56
57	puts("Module                  Size  Used by");
58
59	kmod_list_foreach(itr, list) {
60		struct kmod_module *mod = kmod_module_get_module(itr);
61		const char *name = kmod_module_get_name(mod);
62		int use_count = kmod_module_get_refcnt(mod);
63		long size = kmod_module_get_size(mod);
64		struct kmod_list *holders, *hitr;
65		int first = 1;
66
67		printf("%-19s %8ld  %d", name, size, use_count);
68		holders = kmod_module_get_holders(mod);
69		kmod_list_foreach(hitr, holders) {
70			struct kmod_module *hm = kmod_module_get_module(hitr);
71
72			if (!first) {
73				putchar(',');
74			} else {
75				putchar(' ');
76				first = 0;
77			}
78
79			fputs(kmod_module_get_name(hm), stdout);
80			kmod_module_unref(hm);
81		}
82		putchar('\n');
83		kmod_module_unref_list(holders);
84		kmod_module_unref(mod);
85	}
86	kmod_module_unref_list(list);
87	kmod_unref(ctx);
88
89	return EXIT_SUCCESS;
90}
91
92const struct kmod_cmd kmod_cmd_compat_lsmod = {
93	.name = "lsmod",
94	.cmd = do_lsmod,
95	.help = "compat lsmod command",
96};
97
98const struct kmod_cmd kmod_cmd_list = {
99	.name = "list",
100	.cmd = do_lsmod,
101	.help = "list currently loaded modules",
102};
103