From 18da3ffcd7f3c8a0c5f790c801b5813503c2273d Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Fri, 19 Apr 2024 19:03:56 +0200 Subject: Adding upstream version 31+20240202. Signed-off-by: Daniel Baumann --- tools/.gitignore | 15 + tools/COPYING | 339 ++++++ tools/Makefile | 13 + tools/depmod.c | 3153 ++++++++++++++++++++++++++++++++++++++++++++++++++ tools/insert.c | 128 ++ tools/insmod.c | 166 +++ tools/kmod.c | 179 +++ tools/kmod.h | 42 + tools/kmod.pc.in | 10 + tools/log.c | 149 +++ tools/log.h | 37 + tools/lsmod.c | 102 ++ tools/modinfo.c | 500 ++++++++ tools/modprobe.c | 1054 +++++++++++++++++ tools/remove.c | 153 +++ tools/rmmod.c | 203 ++++ tools/static-nodes.c | 277 +++++ 17 files changed, 6520 insertions(+) create mode 100644 tools/.gitignore create mode 100644 tools/COPYING create mode 100644 tools/Makefile create mode 100644 tools/depmod.c create mode 100644 tools/insert.c create mode 100644 tools/insmod.c create mode 100644 tools/kmod.c create mode 100644 tools/kmod.h create mode 100644 tools/kmod.pc.in create mode 100644 tools/log.c create mode 100644 tools/log.h create mode 100644 tools/lsmod.c create mode 100644 tools/modinfo.c create mode 100644 tools/modprobe.c create mode 100644 tools/remove.c create mode 100644 tools/rmmod.c create mode 100644 tools/static-nodes.c (limited to 'tools') diff --git a/tools/.gitignore b/tools/.gitignore new file mode 100644 index 0000000..3e34160 --- /dev/null +++ b/tools/.gitignore @@ -0,0 +1,15 @@ +/.dirstamp +/depmod +/insmod +/kmod +/kmod-depmod +/kmod-insmod +/kmod-lsmod +/kmod-modinfo +/kmod-modprobe +/kmod-rmmod +/lsmod +/modinfo +/modprobe +/rmmod +/test diff --git a/tools/COPYING b/tools/COPYING new file mode 100644 index 0000000..d511905 --- /dev/null +++ b/tools/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/tools/Makefile b/tools/Makefile new file mode 100644 index 0000000..223bec2 --- /dev/null +++ b/tools/Makefile @@ -0,0 +1,13 @@ +# Copyright 2010 Lennart Poettering +# +# This file has been copied from systemd. It is a dirty trick to simplify +# compilation when CWD is not the root of the source tree. This file is not +# intended to be distributed. So, don't touch it, even better ignore it! + +all: + $(MAKE) -C .. + +clean: + $(MAKE) -C .. clean + +.PHONY: all clean diff --git a/tools/depmod.c b/tools/depmod.c new file mode 100644 index 0000000..43fc354 --- /dev/null +++ b/tools/depmod.c @@ -0,0 +1,3153 @@ +/* + * kmod-depmod - calculate modules.dep using libkmod. + * + * Copyright (C) 2011-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#undef ERR +#undef DBG + +#include "kmod.h" + +#define DEFAULT_VERBOSE LOG_WARNING +static int verbose = DEFAULT_VERBOSE; + +static const char CFG_BUILTIN_KEY[] = "built-in"; +static const char CFG_EXTERNAL_KEY[] = "external"; +static const char *const default_cfg_paths[] = { + SYSCONFDIR "/depmod.d", + "/run/depmod.d", + "/usr/local/lib/depmod.d", + DISTCONFDIR "/depmod.d", + "/lib/depmod.d", + NULL +}; + +static const char cmdopts_s[] = "aAb:o:C:E:F:euqrvnP:wmVh"; +static const struct option cmdopts[] = { + { "all", no_argument, 0, 'a' }, + { "quick", no_argument, 0, 'A' }, + { "basedir", required_argument, 0, 'b' }, + { "outdir", required_argument, 0, 'o' }, + { "config", required_argument, 0, 'C' }, + { "symvers", required_argument, 0, 'E' }, + { "filesyms", required_argument, 0, 'F' }, + { "errsyms", no_argument, 0, 'e' }, + { "unresolved-error", no_argument, 0, 'u' }, /* deprecated */ + { "quiet", no_argument, 0, 'q' }, /* deprecated */ + { "root", no_argument, 0, 'r' }, /* deprecated */ + { "verbose", no_argument, 0, 'v' }, + { "show", no_argument, 0, 'n' }, + { "dry-run", no_argument, 0, 'n' }, + { "symbol-prefix", required_argument, 0, 'P' }, + { "warn", no_argument, 0, 'w' }, + { "map", no_argument, 0, 'm' }, /* deprecated */ + { "version", no_argument, 0, 'V' }, + { "help", no_argument, 0, 'h' }, + { } +}; + +static void help(void) +{ + printf("Usage:\n" + "\t%s -[aA] [options] [forced_version]\n" + "\n" + "If no arguments (except options) are given, \"depmod -a\" is assumed\n" + "\n" + "depmod will output a dependency list suitable for the modprobe utility.\n" + "\n" + "Options:\n" + "\t-a, --all Probe all modules\n" + "\t-A, --quick Only does the work if there's a new module\n" + "\t-e, --errsyms Report not supplied symbols\n" + "\t-n, --show Write the dependency file on stdout only\n" + "\t-P, --symbol-prefix Architecture symbol prefix\n" + "\t-C, --config=PATH Read configuration from PATH\n" + "\t-v, --verbose Enable verbose mode\n" + "\t-w, --warn Warn on duplicates\n" + "\t-V, --version show version\n" + "\t-h, --help show this help\n" + "\n" + "The following options are useful for people managing distributions:\n" + "\t-b, --basedir=DIR Use an image of a module tree.\n" + "\t-o, --outdir=DIR Output directory for generated files.\n" + "\t-F, --filesyms=FILE Use the file instead of the\n" + "\t current kernel symbols.\n" + "\t-E, --symvers=FILE Use Module.symvers file to check\n" + "\t symbol versions.\n", + program_invocation_short_name); +} + +_printf_format_(1, 2) +static inline void _show(const char *fmt, ...) +{ + va_list args; + + if (verbose <= DEFAULT_VERBOSE) + return; + + va_start(args, fmt); + vfprintf(stdout, fmt, args); + fflush(stdout); + va_end(args); +} +#define SHOW(...) _show(__VA_ARGS__) + + +/* binary index write *************************************************/ +#include +/* BEGIN: code from module-init-tools/index.c just modified to compile here. + * + * Original copyright: + * index.c: module index file shared functions for modprobe and depmod + * Copyright (C) 2008 Alan Jenkins . + * + * These programs are free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with these programs. If not, see . + */ + +/* see documentation in libkmod/libkmod-index.c */ + +#define INDEX_MAGIC 0xB007F457 +#define INDEX_VERSION_MAJOR 0x0002 +#define INDEX_VERSION_MINOR 0x0001 +#define INDEX_VERSION ((INDEX_VERSION_MAJOR<<16)|INDEX_VERSION_MINOR) +#define INDEX_CHILDMAX 128 + +struct index_value { + struct index_value *next; + unsigned int priority; + char value[0]; +}; + +/* In-memory index (depmod only) */ +struct index_node { + char *prefix; /* path compression */ + struct index_value *values; + unsigned char first; /* range of child nodes */ + unsigned char last; + struct index_node *children[INDEX_CHILDMAX]; /* indexed by character */ +}; + + +/* Format of node offsets within index file */ +enum node_offset { + INDEX_NODE_FLAGS = 0xF0000000, /* Flags in high nibble */ + INDEX_NODE_PREFIX = 0x80000000, + INDEX_NODE_VALUES = 0x40000000, + INDEX_NODE_CHILDS = 0x20000000, + + INDEX_NODE_MASK = 0x0FFFFFFF, /* Offset value */ +}; + +static struct index_node *index_create(void) +{ + struct index_node *node; + + node = NOFAIL(calloc(1, sizeof(struct index_node))); + node->prefix = NOFAIL(strdup("")); + node->first = INDEX_CHILDMAX; + + return node; +} + +static void index_values_free(struct index_value *values) +{ + while (values) { + struct index_value *value = values; + + values = value->next; + free(value); + } +} + +static void index_destroy(struct index_node *node) +{ + int c; + + for (c = node->first; c <= node->last; c++) { + struct index_node *child = node->children[c]; + + if (child) + index_destroy(child); + } + index_values_free(node->values); + free(node->prefix); + free(node); +} + +static void index__checkstring(const char *str) +{ + int i; + + for (i = 0; str[i]; i++) { + int ch = str[i]; + + if (ch >= INDEX_CHILDMAX) + CRIT("Module index: bad character '%c'=0x%x - only 7-bit ASCII is supported:" + "\n%s\n", (char) ch, (int) ch, str); + } +} + +static int index_add_value(struct index_value **values, + const char *value, unsigned int priority) +{ + struct index_value *v; + int duplicate = 0; + int len; + + /* report the presence of duplicate values */ + for (v = *values; v; v = v->next) { + if (streq(v->value, value)) + duplicate = 1; + } + + /* find position to insert value */ + while (*values && (*values)->priority < priority) + values = &(*values)->next; + + len = strlen(value); + v = NOFAIL(calloc(1, sizeof(struct index_value) + len + 1)); + v->next = *values; + v->priority = priority; + memcpy(v->value, value, len + 1); + *values = v; + + return duplicate; +} + +static int index_insert(struct index_node *node, const char *key, + const char *value, unsigned int priority) +{ + int i = 0; /* index within str */ + int ch; + + index__checkstring(key); + index__checkstring(value); + + while(1) { + int j; /* index within node->prefix */ + + /* Ensure node->prefix is a prefix of &str[i]. + If it is not already, then we must split node. */ + for (j = 0; node->prefix[j]; j++) { + ch = node->prefix[j]; + + if (ch != key[i+j]) { + char *prefix = node->prefix; + struct index_node *n; + + /* New child is copy of node with prefix[j+1..N] */ + n = NOFAIL(calloc(1, sizeof(struct index_node))); + memcpy(n, node, sizeof(struct index_node)); + n->prefix = NOFAIL(strdup(&prefix[j+1])); + + /* Parent has prefix[0..j], child at prefix[j] */ + memset(node, 0, sizeof(struct index_node)); + prefix[j] = '\0'; + node->prefix = prefix; + node->first = ch; + node->last = ch; + node->children[ch] = n; + + break; + } + } + /* j is now length of node->prefix */ + i += j; + + ch = key[i]; + if(ch == '\0') + return index_add_value(&node->values, value, priority); + + if (!node->children[ch]) { + struct index_node *child; + + if (ch < node->first) + node->first = ch; + if (ch > node->last) + node->last = ch; + node->children[ch] = NOFAIL(calloc(1, sizeof(struct index_node))); + + child = node->children[ch]; + child->prefix = NOFAIL(strdup(&key[i+1])); + child->first = INDEX_CHILDMAX; + index_add_value(&child->values, value, priority); + + return 0; + } + + /* Descend into child node and continue */ + node = node->children[ch]; + i++; + } +} + +static int index__haschildren(const struct index_node *node) +{ + return node->first < INDEX_CHILDMAX; +} + +/* Recursive post-order traversal + + Pre-order would make for better read-side buffering / readahead / caching. + (post-order means you go backwards in the file as you descend the tree). + However, index reading is already fast enough. + Pre-order is simpler for writing, and depmod is already slow. + */ +static uint32_t index_write__node(const struct index_node *node, FILE *out) +{ + uint32_t *child_offs = NULL; + int child_count = 0; + long offset; + + if (!node) + return 0; + + /* Write children and save their offsets */ + if (index__haschildren(node)) { + const struct index_node *child; + int i; + + child_count = node->last - node->first + 1; + child_offs = NOFAIL(malloc(child_count * sizeof(uint32_t))); + + for (i = 0; i < child_count; i++) { + child = node->children[node->first + i]; + child_offs[i] = htonl(index_write__node(child, out)); + } + } + + /* Now write this node */ + offset = ftell(out); + + if (node->prefix[0]) { + fputs(node->prefix, out); + fputc('\0', out); + offset |= INDEX_NODE_PREFIX; + } + + if (child_count) { + fputc(node->first, out); + fputc(node->last, out); + fwrite(child_offs, sizeof(uint32_t), child_count, out); + offset |= INDEX_NODE_CHILDS; + } + + free(child_offs); + + if (node->values) { + const struct index_value *v; + unsigned int value_count; + uint32_t u; + + value_count = 0; + for (v = node->values; v != NULL; v = v->next) + value_count++; + u = htonl(value_count); + fwrite(&u, sizeof(u), 1, out); + + for (v = node->values; v != NULL; v = v->next) { + u = htonl(v->priority); + fwrite(&u, sizeof(u), 1, out); + fputs(v->value, out); + fputc('\0', out); + } + offset |= INDEX_NODE_VALUES; + } + + return offset; +} + +static void index_write(const struct index_node *node, FILE *out) +{ + long initial_offset, final_offset; + uint32_t u; + + u = htonl(INDEX_MAGIC); + fwrite(&u, sizeof(u), 1, out); + u = htonl(INDEX_VERSION); + fwrite(&u, sizeof(u), 1, out); + + /* Second word is reserved for the offset of the root node */ + initial_offset = ftell(out); + assert(initial_offset >= 0); + u = 0; + fwrite(&u, sizeof(uint32_t), 1, out); + + /* Dump trie */ + u = htonl(index_write__node(node, out)); + + /* Update first word */ + final_offset = ftell(out); + assert(final_offset >= 0); + (void)fseek(out, initial_offset, SEEK_SET); + fwrite(&u, sizeof(uint32_t), 1, out); + (void)fseek(out, final_offset, SEEK_SET); +} + +/* END: code from module-init-tools/index.c just modified to compile here. + */ + +/* configuration parsing **********************************************/ +struct cfg_override { + struct cfg_override *next; + size_t len; + char path[]; +}; + +enum search_type { + SEARCH_PATH, + SEARCH_BUILTIN, + SEARCH_EXTERNAL +}; + +struct cfg_search { + struct cfg_search *next; + enum search_type type; + size_t len; + char path[]; +}; + +struct cfg_external { + struct cfg_external *next; + size_t len; + char path[]; +}; + +struct cfg_exclude { + struct cfg_exclude *next; + char exclude_dir[]; +}; + +struct cfg { + const char *kversion; + char dirname[PATH_MAX]; + size_t dirnamelen; + char outdirname[PATH_MAX]; + size_t outdirnamelen; + char sym_prefix; + uint8_t check_symvers; + uint8_t print_unknown; + uint8_t warn_dups; + struct cfg_override *overrides; + struct cfg_search *searches; + struct cfg_external *externals; + struct cfg_exclude *excludes; +}; + +static enum search_type cfg_define_search_type(const char *path) +{ + if (streq(path, CFG_BUILTIN_KEY)) + return SEARCH_BUILTIN; + if (streq(path, CFG_EXTERNAL_KEY)) + return SEARCH_EXTERNAL; + return SEARCH_PATH; +} + +static int cfg_search_add(struct cfg *cfg, const char *path) +{ + struct cfg_search *s; + size_t len; + enum search_type type; + + type = cfg_define_search_type(path); + + if (type != SEARCH_PATH) + len = 0; + else + len = strlen(path) + 1; + + s = malloc(sizeof(struct cfg_search) + len); + if (s == NULL) { + ERR("search add: out of memory\n"); + return -ENOMEM; + } + s->type = type; + if (type != SEARCH_PATH) + s->len = 0; + else { + s->len = len - 1; + memcpy(s->path, path, len); + } + + DBG("search add: %s, search type=%hhu\n", path, type); + + s->next = cfg->searches; + cfg->searches = s; + return 0; +} + +static void cfg_search_free(struct cfg_search *s) +{ + free(s); +} + +static int cfg_override_add(struct cfg *cfg, const char *modname, const char *subdir) +{ + struct cfg_override *o; + size_t modnamelen = strlen(modname); + size_t subdirlen = strlen(subdir); + size_t i; + + o = malloc(sizeof(struct cfg_override) + subdirlen + 1 + + modnamelen + 1); + if (o == NULL) { + ERR("override add: out of memory\n"); + return -ENOMEM; + } + memcpy(o->path, subdir, subdirlen); + i = subdirlen; + o->path[i] = '/'; + i++; + + memcpy(o->path + i, modname, modnamelen); + i += modnamelen; + o->path[i] = '\0'; /* no extension, so we can match .ko/.ko.gz */ + + o->len = i; + + DBG("override add: %s\n", o->path); + + o->next = cfg->overrides; + cfg->overrides = o; + return 0; +} + +static void cfg_override_free(struct cfg_override *o) +{ + free(o); +} + +static int cfg_external_add(struct cfg *cfg, const char *path) +{ + struct cfg_external *ext; + size_t len = strlen(path); + + ext = malloc(sizeof(struct cfg_external) + len + 1); + if (ext == NULL) { + ERR("external add: out of memory\n"); + return -ENOMEM; + } + + strcpy(ext->path, path); + ext->len = len; + + DBG("external add: %s\n", ext->path); + + ext->next = cfg->externals; + cfg->externals = ext; + return 0; +} + +static void cfg_external_free(struct cfg_external *ext) +{ + free(ext); +} + +static int cfg_exclude_add(struct cfg *cfg, const char *path) +{ + struct cfg_exclude *exc; + size_t len = strlen(path); + + exc = malloc(sizeof(struct cfg_exclude) + len + 1); + if (exc == NULL) { + ERR("exclude add: out of memory\n"); + return -ENOMEM; + } + memcpy(exc->exclude_dir, path, len + 1); + + DBG("exclude add: %s\n", path); + + exc->next = cfg->excludes; + cfg->excludes = exc; + return 0; +} + +static void cfg_exclude_free(struct cfg_exclude *exc) +{ + free(exc); +} + +static int cfg_kernel_matches(const struct cfg *cfg, const char *pattern) +{ + regex_t re; + int status; + + /* old style */ + if (streq(pattern, "*")) + return 1; + + if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) + return 0; + + status = regexec(&re, cfg->kversion, 0, NULL, 0); + regfree(&re); + + return status == 0; +} + +static int cfg_file_parse(struct cfg *cfg, const char *filename) +{ + char *line; + FILE *fp; + unsigned int linenum = 0; + int err; + + fp = fopen(filename, "r"); + if (fp == NULL) { + err = -errno; + ERR("file parse %s: %m\n", filename); + return err; + } + + while ((line = freadline_wrapped(fp, &linenum)) != NULL) { + char *cmd, *saveptr; + + if (line[0] == '\0' || line[0] == '#') + goto done_next; + + cmd = strtok_r(line, "\t ", &saveptr); + if (cmd == NULL) + goto done_next; + + if (streq(cmd, "search")) { + const char *sp; + while ((sp = strtok_r(NULL, "\t ", &saveptr)) != NULL) { + cfg_search_add(cfg, sp); + } + } else if (streq(cmd, "override")) { + const char *modname = strtok_r(NULL, "\t ", &saveptr); + const char *version = strtok_r(NULL, "\t ", &saveptr); + const char *subdir = strtok_r(NULL, "\t ", &saveptr); + + if (modname == NULL || version == NULL || + subdir == NULL) + goto syntax_error; + + if (!cfg_kernel_matches(cfg, version)) { + INF("%s:%u: override kernel did not match %s\n", + filename, linenum, version); + goto done_next; + } + + cfg_override_add(cfg, modname, subdir); + } else if (streq(cmd, "external")) { + const char *version = strtok_r(NULL, "\t ", &saveptr); + const char *dir = strtok_r(NULL, "\t ", &saveptr); + + if (version == NULL || dir == NULL) + goto syntax_error; + + if (!cfg_kernel_matches(cfg, version)) { + INF("%s:%u: external directory did not match %s\n", + filename, linenum, version); + goto done_next; + } + + cfg_external_add(cfg, dir); + } else if (streq(cmd, "exclude")) { + const char *sp; + while ((sp = strtok_r(NULL, "\t ", &saveptr)) != NULL) { + cfg_exclude_add(cfg, sp); + } + } else if (streq(cmd, "include") + || streq(cmd, "make_map_files")) { + INF("%s:%u: command %s not implemented yet\n", + filename, linenum, cmd); + } else { +syntax_error: + ERR("%s:%u: ignoring bad line starting with '%s'\n", + filename, linenum, cmd); + } + +done_next: + free(line); + } + + fclose(fp); + + return 0; +} + +static int cfg_files_filter_out(DIR *d, const char *dir, const char *name) +{ + size_t len = strlen(name); + struct stat st; + + if (name[0] == '.') + return 1; + + if (len < 6 || !streq(name + len - 5, ".conf")) { + INF("All cfg files need .conf: %s/%s\n", dir, name); + return 1; + } + + fstatat(dirfd(d), name, &st, 0); + if (S_ISDIR(st.st_mode)) { + ERR("Directories inside directories are not supported: %s/%s\n", + dir, name); + return 1; + } + + return 0; +} + +struct cfg_file { + size_t dirlen; + size_t namelen; + const char *name; + char path[]; +}; + +static void cfg_file_free(struct cfg_file *f) +{ + free(f); +} + +static int cfg_files_insert_sorted(struct cfg_file ***p_files, size_t *p_n_files, + const char *dir, const char *name) +{ + struct cfg_file **files, *f; + size_t i, n_files, namelen, dirlen; + void *tmp; + + dirlen = strlen(dir); + if (name != NULL) + namelen = strlen(name); + else { + name = basename(dir); + namelen = strlen(name); + dirlen -= namelen + 1; + } + + n_files = *p_n_files; + files = *p_files; + for (i = 0; i < n_files; i++) { + int cmp = strcmp(name, files[i]->name); + if (cmp == 0) { + DBG("Ignoring duplicate config file: %.*s/%s\n", + (int)dirlen, dir, name); + return -EEXIST; + } else if (cmp < 0) + break; + } + + f = malloc(sizeof(struct cfg_file) + dirlen + namelen + 2); + if (f == NULL) { + ERR("files insert sorted: out of memory\n"); + return -ENOMEM; + } + + tmp = realloc(files, sizeof(struct cfg_file *) * (n_files + 1)); + if (tmp == NULL) { + ERR("files insert sorted: out of memory\n"); + free(f); + return -ENOMEM; + } + *p_files = files = tmp; + + if (i < n_files) { + memmove(files + i + 1, files + i, + sizeof(struct cfg_file *) * (n_files - i)); + } + files[i] = f; + + f->dirlen = dirlen; + f->namelen = namelen; + f->name = f->path + dirlen + 1; + memcpy(f->path, dir, dirlen); + f->path[dirlen] = '/'; + memcpy(f->path + dirlen + 1, name, namelen); + f->path[dirlen + 1 + namelen] = '\0'; + + *p_n_files = n_files + 1; + return 0; +} + +/* + * Insert configuration files ignoring duplicates + */ +static int cfg_files_list(struct cfg_file ***p_files, size_t *p_n_files, + const char *path) +{ + struct dirent *dent; + DIR *d; + int err = 0; + struct stat st; + + if (stat(path, &st) != 0) { + err = -errno; + DBG("could not stat '%s': %m\n", path); + return err; + } + + if (!S_ISDIR(st.st_mode)) { + cfg_files_insert_sorted(p_files, p_n_files, path, NULL); + return 0; + } + + d = opendir(path); + if (d == NULL) { + ERR("files list %s: %m\n", path); + return -EINVAL; + } + + for (dent = readdir(d); dent != NULL; dent = readdir(d)) { + if (cfg_files_filter_out(d, path, dent->d_name)) + continue; + + cfg_files_insert_sorted(p_files, p_n_files, path, dent->d_name); + } + + closedir(d); + DBG("parsed configuration files from %s\n", path); + return err; +} + +static int cfg_load(struct cfg *cfg, const char * const *cfg_paths) +{ + size_t i, n_files = 0; + struct cfg_file **files = NULL; + + if (cfg_paths == NULL) + cfg_paths = default_cfg_paths; + + for (i = 0; cfg_paths[i] != NULL; i++) + cfg_files_list(&files, &n_files, cfg_paths[i]); + + for (i = 0; i < n_files; i++) { + struct cfg_file *f = files[i]; + cfg_file_parse(cfg, f->path); + cfg_file_free(f); + } + free(files); + + /* For backward compatibility add "updates" to the head of the search + * list here. But only if there was no "search" option specified. + */ + if (cfg->searches == NULL) + cfg_search_add(cfg, "updates"); + + return 0; +} + +static void cfg_free(struct cfg *cfg) +{ + while (cfg->overrides) { + struct cfg_override *tmp = cfg->overrides; + cfg->overrides = cfg->overrides->next; + cfg_override_free(tmp); + } + + while (cfg->searches) { + struct cfg_search *tmp = cfg->searches; + cfg->searches = cfg->searches->next; + cfg_search_free(tmp); + } + + while (cfg->externals) { + struct cfg_external *tmp = cfg->externals; + cfg->externals = cfg->externals->next; + cfg_external_free(tmp); + } + + while (cfg->excludes) { + struct cfg_exclude *tmp = cfg->excludes; + cfg->excludes = cfg->excludes->next; + cfg_exclude_free(tmp); + } +} + + +/* depmod calculations ***********************************************/ +struct vertex; +struct mod { + struct kmod_module *kmod; + char *path; + const char *relpath; /* path relative to '$ROOT$MODULE_DIRECTORY/$VER/' */ + char *uncrelpath; /* same as relpath but ending in .ko */ + struct kmod_list *info_list; + struct kmod_list *dep_sym_list; + struct array deps; /* struct symbol */ + size_t baselen; /* points to start of basename/filename */ + size_t modnamesz; + int sort_idx; /* sort index using modules.order */ + int dep_sort_idx; /* topological sort index */ + uint16_t idx; /* index in depmod->modules.array */ + uint16_t users; /* how many modules depend on this one */ + bool visited; /* helper field to report cycles */ + struct vertex *vertex; /* helper field to report cycles */ + char modname[]; +}; + +struct symbol { + struct mod *owner; + uint64_t crc; + char name[]; +}; + +struct depmod { + const struct cfg *cfg; + struct kmod_ctx *ctx; + struct array modules; + struct hash *modules_by_uncrelpath; + struct hash *modules_by_name; + struct hash *symbols; +}; + +static void mod_free(struct mod *mod) +{ + DBG("free %p kmod=%p, path=%s\n", mod, mod->kmod, mod->path); + array_free_array(&mod->deps); + kmod_module_unref(mod->kmod); + kmod_module_info_free_list(mod->info_list); + kmod_module_dependency_symbols_free_list(mod->dep_sym_list); + free(mod->uncrelpath); + free(mod->path); + free(mod); +} + +static int mod_add_dependency(struct mod *mod, struct symbol *sym) +{ + int err; + + DBG("%s depends on %s %s\n", mod->path, sym->name, + sym->owner != NULL ? sym->owner->path : "(unknown)"); + + if (sym->owner == NULL) + return 0; + + err = array_append_unique(&mod->deps, sym->owner); + if (err == -EEXIST) + return 0; + if (err < 0) + return err; + + sym->owner->users++; + SHOW("%s needs \"%s\": %s\n", mod->path, sym->name, sym->owner->path); + return 0; +} + +static void symbol_free(struct symbol *sym) +{ + DBG("free %p sym=%s, owner=%p %s\n", sym, sym->name, sym->owner, + sym->owner != NULL ? sym->owner->path : ""); + free(sym); +} + +static int depmod_init(struct depmod *depmod, struct cfg *cfg, + struct kmod_ctx *ctx) +{ + int err = 0; + + depmod->cfg = cfg; + depmod->ctx = ctx; + + array_init(&depmod->modules, 128); + + depmod->modules_by_uncrelpath = hash_new(512, NULL); + if (depmod->modules_by_uncrelpath == NULL) { + err = -errno; + goto modules_by_uncrelpath_failed; + } + + depmod->modules_by_name = hash_new(512, NULL); + if (depmod->modules_by_name == NULL) { + err = -errno; + goto modules_by_name_failed; + } + + depmod->symbols = hash_new(2048, (void (*)(void *))symbol_free); + if (depmod->symbols == NULL) { + err = -errno; + goto symbols_failed; + } + + return 0; + +symbols_failed: + hash_free(depmod->modules_by_name); +modules_by_name_failed: + hash_free(depmod->modules_by_uncrelpath); +modules_by_uncrelpath_failed: + return err; +} + +static void depmod_shutdown(struct depmod *depmod) +{ + size_t i; + + hash_free(depmod->symbols); + + hash_free(depmod->modules_by_uncrelpath); + + hash_free(depmod->modules_by_name); + + for (i = 0; i < depmod->modules.count; i++) + mod_free(depmod->modules.array[i]); + array_free_array(&depmod->modules); + + kmod_unref(depmod->ctx); +} + +static int depmod_module_add(struct depmod *depmod, struct kmod_module *kmod) +{ + const struct cfg *cfg = depmod->cfg; + const char *modname, *lastslash; + size_t modnamesz; + struct mod *mod; + int err; + + modname = kmod_module_get_name(kmod); + modnamesz = strlen(modname) + 1; + + mod = calloc(1, sizeof(struct mod) + modnamesz); + if (mod == NULL) + return -ENOMEM; + mod->kmod = kmod; + mod->sort_idx = depmod->modules.count + 1; + mod->dep_sort_idx = INT32_MAX; + memcpy(mod->modname, modname, modnamesz); + mod->modnamesz = modnamesz; + + array_init(&mod->deps, 4); + + mod->path = strdup(kmod_module_get_path(kmod)); + lastslash = strrchr(mod->path, '/'); + mod->baselen = lastslash - mod->path; + if (strncmp(mod->path, cfg->dirname, cfg->dirnamelen) == 0 && + mod->path[cfg->dirnamelen] == '/') + mod->relpath = mod->path + cfg->dirnamelen + 1; + else + mod->relpath = NULL; + + err = hash_add_unique(depmod->modules_by_name, mod->modname, mod); + if (err < 0) { + ERR("hash_add_unique %s: %s\n", mod->modname, strerror(-err)); + goto fail; + } + + if (mod->relpath != NULL) { + size_t uncrelpathlen = lastslash - mod->relpath + modnamesz + + strlen(KMOD_EXTENSION_UNCOMPRESSED); + mod->uncrelpath = memdup(mod->relpath, uncrelpathlen + 1); + mod->uncrelpath[uncrelpathlen] = '\0'; + err = hash_add_unique(depmod->modules_by_uncrelpath, + mod->uncrelpath, mod); + if (err < 0) { + ERR("hash_add_unique %s: %s\n", + mod->uncrelpath, strerror(-err)); + hash_del(depmod->modules_by_name, mod->modname); + goto fail; + } + } + + DBG("add %p kmod=%p, path=%s\n", mod, kmod, mod->path); + + return 0; + +fail: + free(mod->uncrelpath); + free(mod); + return err; +} + +static int depmod_module_del(struct depmod *depmod, struct mod *mod) +{ + DBG("del %p kmod=%p, path=%s\n", mod, mod->kmod, mod->path); + + if (mod->uncrelpath != NULL) + hash_del(depmod->modules_by_uncrelpath, mod->uncrelpath); + + hash_del(depmod->modules_by_name, mod->modname); + + mod_free(mod); + return 0; +} + +static const char *search_to_string(const struct cfg_search *s) +{ + switch(s->type) { + case SEARCH_EXTERNAL: + return "external"; + case SEARCH_BUILTIN: + return "built-in"; + default: + return s->path; + } +} + +static bool depmod_is_path_starts_with(const char *path, + size_t pathlen, + const char *prefix, + size_t prefix_len) +{ + if (pathlen <= prefix_len) + return false; + if (path[prefix_len] != '/') + return false; + if (memcmp(path, prefix, prefix_len) != 0) + return false; + + return true; +} + +/* returns if existing module @mod is higher priority than newpath. + * note this is the inverse of module-init-tools is_higher_priority() + */ +static int depmod_module_is_higher_priority(const struct depmod *depmod, const struct mod *mod, size_t baselen, size_t namelen, size_t modnamelen, const char *newpath) +{ + const struct cfg *cfg = depmod->cfg; + const struct cfg_override *ov; + const struct cfg_search *se; + const struct cfg_external *ext; + + /* baselen includes the last '/' and mod->baselen doesn't. So it's + * actually correct to use modnamelen in the first and modnamesz in + * the latter */ + size_t newlen = baselen + modnamelen; + size_t oldlen = mod->baselen + mod->modnamesz; + const char *oldpath = mod->path; + int i, bprio = -1, oldprio = -1, newprio = -1; + size_t relnewlen = 0; + size_t reloldlen = 0; + const char *relnewpath = NULL; + const char *reloldpath = NULL; + + DBG("comparing priorities of %s and %s\n", + oldpath, newpath); + + if (strncmp(newpath, cfg->dirname, cfg->dirnamelen) == 0) { + relnewpath = newpath + cfg->dirnamelen + 1; + relnewlen = newlen - (cfg->dirnamelen + 1); + } + if (strncmp(oldpath, cfg->dirname, cfg->dirnamelen) == 0) { + reloldpath = oldpath + cfg->dirnamelen + 1; + reloldlen = oldlen - (cfg->dirnamelen + 1); + } + + for (ov = cfg->overrides; ov != NULL; ov = ov->next) { + DBG("override %s\n", ov->path); + if (relnewlen == ov->len && + memcmp(ov->path, relnewpath, relnewlen) == 0) + return 0; + if (reloldlen == ov->len && + memcmp(ov->path, reloldpath, reloldlen) == 0) + return 1; + } + + for (i = 0, se = cfg->searches; se != NULL; se = se->next, i++) { + DBG("search %s\n", search_to_string(se)); + if (se->type == SEARCH_BUILTIN) + bprio = i; + else if (se->type == SEARCH_EXTERNAL) { + for (ext = cfg->externals; ext != NULL; ext = ext->next, i++) { + if (depmod_is_path_starts_with(newpath, + newlen, + ext->path, + ext->len)) + newprio = i; + if (depmod_is_path_starts_with(oldpath, + oldlen, + ext->path, + ext->len)) + oldprio = i; + } + } else if (relnewlen > se->len && relnewpath[se->len] == '/' && + memcmp(se->path, relnewpath, se->len) == 0) + newprio = i; + else if (reloldlen > se->len && reloldpath[se->len] == '/' && + memcmp(se->path, reloldpath, se->len) == 0) + oldprio = i; + } + + if (newprio < 0) + newprio = bprio; + if (oldprio < 0) + oldprio = bprio; + + DBG("priorities: built-in: %d, old: %d, new: %d\n", + bprio, oldprio, newprio); + + return newprio <= oldprio; +} + +static int depmod_modules_search_file(struct depmod *depmod, size_t baselen, size_t namelen, const char *path) +{ + struct kmod_module *kmod; + struct mod *mod; + const char *relpath; + char modname[PATH_MAX]; + size_t modnamelen; + int err; + + if (!path_ends_with_kmod_ext(path + baselen, namelen)) + return 0; + + if (path_to_modname(path, modname, &modnamelen) == NULL) { + ERR("could not get modname from path %s\n", path); + return -EINVAL; + } + + relpath = path + depmod->cfg->dirnamelen + 1; + DBG("try %s (%s)\n", relpath, modname); + + mod = hash_find(depmod->modules_by_name, modname); + if (mod == NULL) + goto add; + + if (depmod_module_is_higher_priority(depmod, mod, baselen, + namelen, modnamelen, path)) { + DBG("Ignored lower priority: %s, higher: %s\n", + path, mod->path); + return 0; + } + + DBG("Replace lower priority %s with new module %s\n", + mod->relpath, relpath); + err = depmod_module_del(depmod, mod); + if (err < 0) { + ERR("could not del module %s: %s\n", mod->path, strerror(-err)); + return err; + } + +add: + err = kmod_module_new_from_path(depmod->ctx, path, &kmod); + if (err < 0) { + ERR("could not create module %s: %s\n", path, strerror(-err)); + return err; + } + + err = depmod_module_add(depmod, kmod); + if (err < 0) { + ERR("could not add module %s: %s\n", + path, strerror(-err)); + kmod_module_unref(kmod); + return err; + } + return 0; +} + +static bool should_exclude_dir(const struct cfg *cfg, const char *name) +{ + struct cfg_exclude *exc; + + if (name[0] == '.' && (name[1] == '\0' || + (name[1] == '.' && name[2] == '\0'))) + return true; + + if (streq(name, "build") || streq(name, "source")) + return true; + + for (exc = cfg->excludes; exc != NULL; exc = exc->next) { + if (streq(name, exc->exclude_dir)) + return true; + } + + return false; +} + +static int depmod_modules_search_dir(struct depmod *depmod, DIR *d, size_t baselen, struct scratchbuf *s_path) +{ + struct dirent *de; + int err = 0, dfd = dirfd(d); + char *path; + + while ((de = readdir(d)) != NULL) { + const char *name = de->d_name; + size_t namelen; + uint8_t is_dir; + + if (should_exclude_dir(depmod->cfg, name)) + continue; + + namelen = strlen(name); + if (scratchbuf_alloc(s_path, baselen + namelen + 2) < 0) { + err = -ENOMEM; + ERR("No memory\n"); + continue; + } + + path = scratchbuf_str(s_path); + memcpy(path + baselen, name, namelen + 1); + + if (de->d_type == DT_REG) + is_dir = 0; + else if (de->d_type == DT_DIR) + is_dir = 1; + else { + struct stat st; + if (fstatat(dfd, name, &st, 0) < 0) { + ERR("fstatat(%d, %s): %m\n", dfd, name); + continue; + } else if (S_ISREG(st.st_mode)) + is_dir = 0; + else if (S_ISDIR(st.st_mode)) + is_dir = 1; + else { + ERR("unsupported file type %s: %o\n", + path, st.st_mode & S_IFMT); + continue; + } + } + + if (is_dir) { + int fd; + DIR *subdir; + fd = openat(dfd, name, O_RDONLY); + if (fd < 0) { + ERR("openat(%d, %s, O_RDONLY): %m\n", + dfd, name); + continue; + } + subdir = fdopendir(fd); + if (subdir == NULL) { + ERR("fdopendir(%d): %m\n", fd); + close(fd); + continue; + } + path[baselen + namelen] = '/'; + path[baselen + namelen + 1] = '\0'; + err = depmod_modules_search_dir(depmod, subdir, + baselen + namelen + 1, + s_path); + closedir(subdir); + } else { + err = depmod_modules_search_file(depmod, baselen, + namelen, path); + } + + if (err < 0) { + path[baselen + namelen] = '\0'; + ERR("failed %s: %s\n", path, strerror(-err)); + err = 0; /* ignore errors */ + } + } + return err; +} + +static int depmod_modules_search_path(struct depmod *depmod, + const char *path) +{ + char buf[256]; + _cleanup_(scratchbuf_release) struct scratchbuf s_path_buf = + SCRATCHBUF_INITIALIZER(buf); + char *path_buf; + DIR *d; + size_t baselen; + int err; + + d = opendir(path); + if (d == NULL) { + err = -errno; + ERR("could not open directory %s: %m\n", path); + return err; + } + + baselen = strlen(path); + + if (scratchbuf_alloc(&s_path_buf, baselen + 2) < 0) { + err = -ENOMEM; + goto out; + } + path_buf = scratchbuf_str(&s_path_buf); + + memcpy(path_buf, path, baselen); + path_buf[baselen] = '/'; + baselen++; + path_buf[baselen] = '\0'; + + err = depmod_modules_search_dir(depmod, d, baselen, &s_path_buf); +out: + closedir(d); + return err; +} + +static int depmod_modules_search(struct depmod *depmod) +{ + int err; + struct cfg_external *ext; + + err = depmod_modules_search_path(depmod, depmod->cfg->dirname); + if (err < 0) + return err; + + for (ext = depmod->cfg->externals; ext != NULL; ext = ext->next) { + err = depmod_modules_search_path(depmod, ext->path); + if (err < 0 && err == -ENOENT) + /* ignore external dir absense */ + continue; + } + + return 0; +} + +static int mod_cmp(const void *pa, const void *pb) { + const struct mod *a = *(const struct mod **)pa; + const struct mod *b = *(const struct mod **)pb; + return a->sort_idx - b->sort_idx; +} + +static int depmod_modules_build_array(struct depmod *depmod) +{ + struct hash_iter module_iter; + const void *v; + int err; + + hash_iter_init(depmod->modules_by_name, &module_iter); + while (hash_iter_next(&module_iter, NULL, &v)) { + struct mod *mod = (struct mod *) v; + mod->idx = depmod->modules.count; + err = array_append(&depmod->modules, mod); + if (err < 0) + return err; + } + + return 0; +} + +static FILE *dfdopen(const char *dname, const char *filename, int flags, + const char *mode) +{ + int fd, dfd; + FILE *ret; + + dfd = open(dname, O_RDONLY); + if (dfd < 0) { + WRN("could not open directory %s: %m\n", dname); + return NULL; + } + + fd = openat(dfd, filename, flags); + if (fd < 0) { + WRN("could not open %s at %s: %m\n", filename, dname); + ret = NULL; + } else { + ret = fdopen(fd, mode); + if (!ret) { + WRN("could not associate stream with %s: %m\n", filename); + close(fd); + } + } + close(dfd); + return ret; +} + + + +static void depmod_modules_sort(struct depmod *depmod) +{ + char line[PATH_MAX]; + const char *order_file = "modules.order"; + FILE *fp; + unsigned idx = 0, total = 0; + + fp = dfdopen(depmod->cfg->dirname, order_file, O_RDONLY, "r"); + if (fp == NULL) + return; + + while (fgets(line, sizeof(line), fp) != NULL) { + size_t len = strlen(line); + idx++; + if (len == 0) + continue; + if (line[len - 1] != '\n') { + ERR("%s/%s:%u corrupted line misses '\\n'\n", + depmod->cfg->dirname, order_file, idx); + goto corrupted; + } + } + total = idx + 1; + idx = 0; + fseek(fp, 0, SEEK_SET); + while (fgets(line, sizeof(line), fp) != NULL) { + size_t len = strlen(line); + struct mod *mod; + + idx++; + if (len == 0) + continue; + line[len - 1] = '\0'; + + mod = hash_find(depmod->modules_by_uncrelpath, line); + if (mod == NULL) + continue; + mod->sort_idx = idx - total; + } + + array_sort(&depmod->modules, mod_cmp); + for (idx = 0; idx < depmod->modules.count; idx++) { + struct mod *m = depmod->modules.array[idx]; + m->idx = idx; + } + +corrupted: + fclose(fp); +} + +static int depmod_symbol_add(struct depmod *depmod, const char *name, + bool prefix_skipped, uint64_t crc, + const struct mod *owner) +{ + size_t namelen; + int err; + struct symbol *sym; + + if (!prefix_skipped && (name[0] == depmod->cfg->sym_prefix)) + name++; + + namelen = strlen(name) + 1; + sym = malloc(sizeof(struct symbol) + namelen); + if (sym == NULL) + return -ENOMEM; + + sym->owner = (struct mod *)owner; + sym->crc = crc; + memcpy(sym->name, name, namelen); + + err = hash_add(depmod->symbols, sym->name, sym); + if (err < 0) { + free(sym); + return err; + } + + DBG("add %p sym=%s, owner=%p %s\n", sym, sym->name, owner, + owner != NULL ? owner->path : ""); + + return 0; +} + +static struct symbol *depmod_symbol_find(const struct depmod *depmod, + const char *name) +{ + if (name[0] == '.') /* PPC64 needs this: .foo == foo */ + name++; + if (name[0] == depmod->cfg->sym_prefix) + name++; + return hash_find(depmod->symbols, name); +} + +static int depmod_load_modules(struct depmod *depmod) +{ + struct mod **itr, **itr_end; + + DBG("load symbols (%zd modules)\n", depmod->modules.count); + + itr = (struct mod **)depmod->modules.array; + itr_end = itr + depmod->modules.count; + for (; itr < itr_end; itr++) { + struct mod *mod = *itr; + struct kmod_list *l, *list = NULL; + int err = kmod_module_get_symbols(mod->kmod, &list); + if (err < 0) { + if (err == -ENODATA) + DBG("ignoring %s: no symbols\n", mod->path); + else + ERR("failed to load symbols from %s: %s\n", + mod->path, strerror(-err)); + goto load_info; + } + kmod_list_foreach(l, list) { + const char *name = kmod_module_symbol_get_symbol(l); + uint64_t crc = kmod_module_symbol_get_crc(l); + depmod_symbol_add(depmod, name, false, crc, mod); + } + kmod_module_symbols_free_list(list); + +load_info: + kmod_module_get_info(mod->kmod, &mod->info_list); + kmod_module_get_dependency_symbols(mod->kmod, + &mod->dep_sym_list); + kmod_module_unref(mod->kmod); + mod->kmod = NULL; + } + + DBG("loaded symbols (%zd modules, %u symbols)\n", + depmod->modules.count, hash_get_count(depmod->symbols)); + + return 0; +} + +static int depmod_load_module_dependencies(struct depmod *depmod, struct mod *mod) +{ + const struct cfg *cfg = depmod->cfg; + struct kmod_list *l; + + DBG("do dependencies of %s\n", mod->path); + kmod_list_foreach(l, mod->dep_sym_list) { + const char *name = kmod_module_dependency_symbol_get_symbol(l); + uint64_t crc = kmod_module_dependency_symbol_get_crc(l); + int bindtype = kmod_module_dependency_symbol_get_bind(l); + struct symbol *sym = depmod_symbol_find(depmod, name); + uint8_t is_weak = bindtype == KMOD_SYMBOL_WEAK; + + if (sym == NULL) { + DBG("%s needs (%c) unknown symbol %s\n", + mod->path, bindtype, name); + if (cfg->print_unknown && !is_weak) + WRN("%s needs unknown symbol %s\n", + mod->path, name); + continue; + } + + if (cfg->check_symvers && sym->crc != crc && !is_weak) { + DBG("symbol %s (%#"PRIx64") module %s (%#"PRIx64")\n", + sym->name, sym->crc, mod->path, crc); + if (cfg->print_unknown) + WRN("%s disagrees about version of symbol %s\n", + mod->path, name); + } + + mod_add_dependency(mod, sym); + } + + return 0; +} + +static int depmod_load_dependencies(struct depmod *depmod) +{ + struct mod **itr, **itr_end; + + DBG("load dependencies (%zd modules, %u symbols)\n", + depmod->modules.count, hash_get_count(depmod->symbols)); + + itr = (struct mod **)depmod->modules.array; + itr_end = itr + depmod->modules.count; + for (; itr < itr_end; itr++) { + struct mod *mod = *itr; + + if (mod->dep_sym_list == NULL) { + DBG("ignoring %s: no dependency symbols\n", mod->path); + continue; + } + + depmod_load_module_dependencies(depmod, mod); + } + + DBG("loaded dependencies (%zd modules, %u symbols)\n", + depmod->modules.count, hash_get_count(depmod->symbols)); + + return 0; +} + +static int dep_cmp(const void *pa, const void *pb) +{ + const struct mod *a = *(const struct mod **)pa; + const struct mod *b = *(const struct mod **)pb; + return a->dep_sort_idx - b->dep_sort_idx; +} + +static void depmod_sort_dependencies(struct depmod *depmod) +{ + struct mod **itr, **itr_end; + itr = (struct mod **)depmod->modules.array; + itr_end = itr + depmod->modules.count; + for (; itr < itr_end; itr++) { + struct mod *m = *itr; + if (m->deps.count > 1) + array_sort(&m->deps, dep_cmp); + } +} + +struct vertex { + struct vertex *parent; + struct mod *mod; +}; + +static struct vertex *vertex_new(struct mod *mod, struct vertex *parent) +{ + struct vertex *v; + + v = malloc(sizeof(*v)); + if (v == NULL) + return NULL; + + v->parent = parent; + v->mod = mod; + return v; +} + +static void depmod_list_remove_data(struct kmod_list **list, void *data) +{ + struct kmod_list *l; + + l = kmod_list_remove_data(*list, data); + *list = l; +} + +static int depmod_report_one_cycle(struct depmod *depmod, + struct vertex *vertex, + struct kmod_list **roots, + struct hash *loop_set) +{ + const char sep[] = " -> "; + size_t sz; + char *buf; + struct array reverse; + int i; + int n; + struct vertex *v; + int rc; + + array_init(&reverse, 3); + + sz = 0; + for (v = vertex->parent, n = 0; + v != NULL; + v = v->parent, n++) { + + sz += v->mod->modnamesz - 1; + array_append(&reverse, v); + rc = hash_add(loop_set, v->mod->modname, NULL); + if (rc != 0) + return rc; + /* the hash will be freed where created */ + } + sz += vertex->mod->modnamesz - 1; + + buf = malloc(sz + n * strlen(sep) + 1); + + sz = 0; + for (i = reverse.count - 1; i >= 0; i--) { + size_t len; + + v = reverse.array[i]; + + len = v->mod->modnamesz - 1; + memcpy(buf + sz, v->mod->modname, len); + sz += len; + strcpy(buf + sz, sep); + sz += strlen(sep); + + depmod_list_remove_data(roots, v->mod); + } + strcpy(buf + sz, vertex->mod->modname); + ERR("Cycle detected: %s\n", buf); + + free(buf); + array_free_array(&reverse); + + return 0; +} + +static int depmod_report_cycles_from_root(struct depmod *depmod, + struct mod *root_mod, + struct kmod_list **roots, + void **stack, + size_t stack_size, + struct hash *loop_set) +{ + struct kmod_list *free_list = NULL; /* struct vertex */ + struct kmod_list *l; + struct vertex *root; + struct vertex *vertex; + struct vertex *v; + struct mod *m; + struct mod **itr, **itr_end; + size_t is; + int ret = -ENOMEM; + + root = vertex_new(root_mod, NULL); + if (root == NULL) { + ERR("No memory to report cycles\n"); + goto out; + } + + l = kmod_list_append(free_list, root); + if (l == NULL) { + ERR("No memory to report cycles\n"); + goto out; + } + free_list = l; + + is = 0; + stack[is++] = (void *)root; + + while (is > 0) { + vertex = stack[--is]; + m = vertex->mod; + /* + * because of the topological sort we can start only + * from part of a loop or from a branch after a loop + */ + if (m->visited && m == root->mod) { + int rc; + rc = depmod_report_one_cycle(depmod, vertex, + roots, loop_set); + if (rc != 0) { + ret = rc; + goto out; + } + continue; + } + + m->visited = true; + if (m->deps.count == 0) { + /* + * boundary condition: if there is more than one + * single node branch (not a loop), it is + * recognized as a loop by the code above: + * m->visited because more then one, + * m == root->mod since it is a single node. + * So, prevent deeping into the branch second + * time. + */ + depmod_list_remove_data(roots, m); + + continue; + } + + itr = (struct mod **) m->deps.array; + itr_end = itr + m->deps.count; + for (; itr < itr_end; itr++) { + struct mod *dep = *itr; + v = vertex_new(dep, vertex); + if (v == NULL) { + ERR("No memory to report cycles\n"); + goto out; + } + assert(is < stack_size); + stack[is++] = v; + + l = kmod_list_append(free_list, v); + if (l == NULL) { + ERR("No memory to report cycles\n"); + goto out; + } + free_list = l; + + } + } + ret = 0; + +out: + while (free_list) { + v = free_list->data; + l = kmod_list_remove(free_list); + free_list = l; + free(v); + } + + return ret; +} + +static void depmod_report_cycles(struct depmod *depmod, uint16_t n_mods, + uint16_t *users) +{ + int num_cyclic = 0; + struct kmod_list *roots = NULL; /* struct mod */ + struct kmod_list *l; + size_t n_r; /* local n_roots */ + int i; + int err; + _cleanup_free_ void **stack = NULL; + struct mod *m; + struct mod *root; + struct hash *loop_set; + + for (i = 0, n_r = 0; i < n_mods; i++) { + if (users[i] <= 0) + continue; + m = depmod->modules.array[i]; + l = kmod_list_append(roots, m); + if (l == NULL) { + ERR("No memory to report cycles\n"); + goto out_list; + } + roots = l; + n_r++; + } + + stack = malloc(n_r * sizeof(void *)); + if (stack == NULL) { + ERR("No memory to report cycles\n"); + goto out_list; + } + + loop_set = hash_new(16, NULL); + if (loop_set == NULL) { + ERR("No memory to report cycles\n"); + goto out_list; + } + + while (roots != NULL) { + root = roots->data; + l = kmod_list_remove(roots); + roots = l; + err = depmod_report_cycles_from_root(depmod, + root, + &roots, + stack, n_r, loop_set); + if (err < 0) + goto out_hash; + } + + num_cyclic = hash_get_count(loop_set); + ERR("Found %d modules in dependency cycles!\n", num_cyclic); + +out_hash: + hash_free(loop_set); +out_list: + while (roots != NULL) { + /* no need to free data, come from outside */ + roots = kmod_list_remove(roots); + } +} + +static int depmod_calculate_dependencies(struct depmod *depmod) +{ + const struct mod **itrm; + uint16_t *users, *roots, *sorted; + uint16_t i, n_roots = 0, n_sorted = 0, n_mods = depmod->modules.count; + int ret = 0; + + users = malloc(sizeof(uint16_t) * n_mods * 3); + if (users == NULL) + return -ENOMEM; + roots = users + n_mods; + sorted = roots + n_mods; + + DBG("calculate dependencies and ordering (%hu modules)\n", n_mods); + + assert(depmod->modules.count < UINT16_MAX); + + /* populate modules users (how many modules uses it) */ + itrm = (const struct mod **)depmod->modules.array; + for (i = 0; i < n_mods; i++, itrm++) { + const struct mod *m = *itrm; + users[i] = m->users; + if (users[i] == 0) { + roots[n_roots] = i; + n_roots++; + } + } + + /* topological sort (outputs modules without users first) */ + while (n_roots > 0) { + const struct mod **itr_dst, **itr_dst_end; + struct mod *src; + uint16_t src_idx = roots[--n_roots]; + + src = depmod->modules.array[src_idx]; + src->dep_sort_idx = n_sorted; + sorted[n_sorted] = src_idx; + n_sorted++; + + itr_dst = (const struct mod **)src->deps.array; + itr_dst_end = itr_dst + src->deps.count; + for (; itr_dst < itr_dst_end; itr_dst++) { + const struct mod *dst = *itr_dst; + uint16_t dst_idx = dst->idx; + assert(users[dst_idx] > 0); + users[dst_idx]--; + if (users[dst_idx] == 0) { + roots[n_roots] = dst_idx; + n_roots++; + } + } + } + + if (n_sorted < n_mods) { + depmod_report_cycles(depmod, n_mods, users); + ret = -EINVAL; + goto exit; + } + + depmod_sort_dependencies(depmod); + + DBG("calculated dependencies and ordering (%hu modules)\n", n_mods); + +exit: + free(users); + return ret; +} + +static int depmod_load(struct depmod *depmod) +{ + int err; + + err = depmod_load_modules(depmod); + if (err < 0) + return err; + + err = depmod_load_dependencies(depmod); + if (err < 0) + return err; + + err = depmod_calculate_dependencies(depmod); + if (err < 0) + return err; + + return 0; +} + +static size_t mod_count_all_dependencies(const struct mod *mod) +{ + size_t i, count = 0; + for (i = 0; i < mod->deps.count; i++) { + const struct mod *d = mod->deps.array[i]; + count += 1 + mod_count_all_dependencies(d); + } + return count; +} + +static int mod_fill_all_unique_dependencies(const struct mod *mod, const struct mod **deps, size_t n_deps, size_t *last) +{ + size_t i; + int err = 0; + for (i = 0; i < mod->deps.count; i++) { + const struct mod *d = mod->deps.array[i]; + size_t j; + uint8_t exists = 0; + + for (j = 0; j < *last; j++) { + if (deps[j] == d) { + exists = 1; + break; + } + } + + if (exists) + continue; + + if (*last >= n_deps) + return -ENOSPC; + deps[*last] = d; + (*last)++; + err = mod_fill_all_unique_dependencies(d, deps, n_deps, last); + if (err < 0) + break; + } + return err; +} + +static const struct mod **mod_get_all_sorted_dependencies(const struct mod *mod, size_t *n_deps) +{ + const struct mod **deps; + size_t last = 0; + + *n_deps = mod_count_all_dependencies(mod); + if (*n_deps == 0) + return NULL; + + deps = malloc(sizeof(struct mod *) * (*n_deps)); + if (deps == NULL) + return NULL; + + if (mod_fill_all_unique_dependencies(mod, deps, *n_deps, &last) < 0) { + free(deps); + return NULL; + } + + qsort(deps, last, sizeof(struct mod *), dep_cmp); + *n_deps = last; + return deps; +} + +static inline const char *mod_get_compressed_path(const struct mod *mod) +{ + if (mod->relpath != NULL) + return mod->relpath; + return mod->path; +} + +static int output_deps(struct depmod *depmod, FILE *out) +{ + size_t i; + + for (i = 0; i < depmod->modules.count; i++) { + const struct mod **deps, *mod = depmod->modules.array[i]; + const char *p = mod_get_compressed_path(mod); + size_t j, n_deps; + + fprintf(out, "%s:", p); + + if (mod->deps.count == 0) + goto end; + + deps = mod_get_all_sorted_dependencies(mod, &n_deps); + if (deps == NULL) { + ERR("could not get all sorted dependencies of %s\n", p); + goto end; + } + + for (j = 0; j < n_deps; j++) { + const struct mod *d = deps[j]; + fprintf(out, " %s", mod_get_compressed_path(d)); + } + free(deps); + end: + putc('\n', out); + } + + return 0; +} + +static int output_deps_bin(struct depmod *depmod, FILE *out) +{ + struct index_node *idx; + size_t i; + + if (out == stdout) + return 0; + + idx = index_create(); + if (idx == NULL) + return -ENOMEM; + + for (i = 0; i < depmod->modules.count; i++) { + const struct mod **deps, *mod = depmod->modules.array[i]; + const char *p = mod_get_compressed_path(mod); + char *line; + size_t j, n_deps, linepos, linelen, slen; + int duplicate; + + deps = mod_get_all_sorted_dependencies(mod, &n_deps); + if (deps == NULL && n_deps > 0) { + ERR("could not get all sorted dependencies of %s\n", p); + continue; + } + + linelen = strlen(p) + 1; + for (j = 0; j < n_deps; j++) { + const struct mod *d = deps[j]; + linelen += 1 + strlen(mod_get_compressed_path(d)); + } + + line = malloc(linelen + 1); + if (line == NULL) { + free(deps); + ERR("modules.deps.bin: out of memory\n"); + continue; + } + + linepos = 0; + slen = strlen(p); + memcpy(line + linepos, p, slen); + linepos += slen; + line[linepos] = ':'; + linepos++; + + for (j = 0; j < n_deps; j++) { + const struct mod *d = deps[j]; + const char *dp; + + line[linepos] = ' '; + linepos++; + + dp = mod_get_compressed_path(d); + slen = strlen(dp); + memcpy(line + linepos, dp, slen); + linepos += slen; + } + line[linepos] = '\0'; + + duplicate = index_insert(idx, mod->modname, line, mod->idx); + if (duplicate && depmod->cfg->warn_dups) + WRN("duplicate module deps:\n%s\n", line); + free(line); + free(deps); + } + + index_write(idx, out); + index_destroy(idx); + + return 0; +} + +static int output_aliases(struct depmod *depmod, FILE *out) +{ + size_t i; + + fputs("# Aliases extracted from modules themselves.\n", out); + + for (i = 0; i < depmod->modules.count; i++) { + const struct mod *mod = depmod->modules.array[i]; + struct kmod_list *l; + + kmod_list_foreach(l, mod->info_list) { + const char *key = kmod_module_info_get_key(l); + const char *value = kmod_module_info_get_value(l); + + if (!streq(key, "alias")) + continue; + + fprintf(out, "alias %s %s\n", value, mod->modname); + } + } + + return 0; +} + +static int output_aliases_bin(struct depmod *depmod, FILE *out) +{ + struct index_node *idx; + size_t i; + + if (out == stdout) + return 0; + + idx = index_create(); + if (idx == NULL) + return -ENOMEM; + + for (i = 0; i < depmod->modules.count; i++) { + const struct mod *mod = depmod->modules.array[i]; + struct kmod_list *l; + + kmod_list_foreach(l, mod->info_list) { + const char *key = kmod_module_info_get_key(l); + const char *value = kmod_module_info_get_value(l); + char buf[PATH_MAX]; + const char *alias; + int duplicate; + + if (!streq(key, "alias")) + continue; + + if (alias_normalize(value, buf, NULL) < 0) { + WRN("Unmatched bracket in %s\n", value); + continue; + } + alias = buf; + + duplicate = index_insert(idx, alias, mod->modname, + mod->idx); + if (duplicate && depmod->cfg->warn_dups) + WRN("duplicate module alias:\n%s %s\n", + alias, mod->modname); + } + } + + index_write(idx, out); + index_destroy(idx); + + return 0; +} + +static int output_softdeps(struct depmod *depmod, FILE *out) +{ + size_t i; + + fputs("# Soft dependencies extracted from modules themselves.\n", out); + + for (i = 0; i < depmod->modules.count; i++) { + const struct mod *mod = depmod->modules.array[i]; + struct kmod_list *l; + + kmod_list_foreach(l, mod->info_list) { + const char *key = kmod_module_info_get_key(l); + const char *value = kmod_module_info_get_value(l); + + if (!streq(key, "softdep")) + continue; + + fprintf(out, "softdep %s %s\n", mod->modname, value); + } + } + + return 0; +} + +static int output_symbols(struct depmod *depmod, FILE *out) +{ + struct hash_iter iter; + const void *v; + + fputs("# Aliases for symbols, used by symbol_request().\n", out); + + hash_iter_init(depmod->symbols, &iter); + + while (hash_iter_next(&iter, NULL, &v)) { + const struct symbol *sym = v; + if (sym->owner == NULL) + continue; + + fprintf(out, "alias symbol:%s %s\n", + sym->name, sym->owner->modname); + } + + return 0; +} + +static int output_symbols_bin(struct depmod *depmod, FILE *out) +{ + struct index_node *idx; + char alias[1024]; + _cleanup_(scratchbuf_release) struct scratchbuf salias = + SCRATCHBUF_INITIALIZER(alias); + size_t baselen = sizeof("symbol:") - 1; + struct hash_iter iter; + const void *v; + int ret = 0; + + if (out == stdout) + return 0; + + idx = index_create(); + if (idx == NULL) + return -ENOMEM; + + memcpy(alias, "symbol:", baselen); + + hash_iter_init(depmod->symbols, &iter); + + while (hash_iter_next(&iter, NULL, &v)) { + int duplicate; + const struct symbol *sym = v; + size_t len; + + if (sym->owner == NULL) + continue; + + len = strlen(sym->name); + + if (scratchbuf_alloc(&salias, baselen + len + 1) < 0) { + ret = -ENOMEM; + goto err_scratchbuf; + } + memcpy(scratchbuf_str(&salias) + baselen, sym->name, len + 1); + duplicate = index_insert(idx, alias, sym->owner->modname, + sym->owner->idx); + + if (duplicate && depmod->cfg->warn_dups) + WRN("duplicate module syms:\n%s %s\n", + alias, sym->owner->modname); + } + + index_write(idx, out); + +err_scratchbuf: + index_destroy(idx); + + if (ret < 0) + ERR("output symbols: %s\n", strerror(-ret)); + + return ret; +} + +static int output_builtin_bin(struct depmod *depmod, FILE *out) +{ + FILE *in; + struct index_node *idx; + char line[PATH_MAX], modname[PATH_MAX]; + + if (out == stdout) + return 0; + + in = dfdopen(depmod->cfg->dirname, "modules.builtin", O_RDONLY, "r"); + if (in == NULL) + return 0; + + idx = index_create(); + if (idx == NULL) { + fclose(in); + return -ENOMEM; + } + + while (fgets(line, sizeof(line), in) != NULL) { + if (!isalpha(line[0])) { + ERR("Invalid modules.builtin line: %s\n", line); + continue; + } + + path_to_modname(line, modname, NULL); + index_insert(idx, modname, "", 0); + } + + index_write(idx, out); + index_destroy(idx); + fclose(in); + + return 0; +} + +static int flush_stream(FILE *in, int endchar) +{ + size_t i = 0; + int c; + + for (c = fgetc(in); + c != EOF && c != endchar && c != '\0'; + c = fgetc(in)) + ; + + return c == endchar ? i : 0; +} + +static int flush_stream_to(FILE *in, int endchar, char *dst, size_t dst_sz) +{ + size_t i = 0; + int c; + + for (c = fgetc(in); + c != EOF && c != endchar && c != '\0' && i < dst_sz; + c = fgetc(in)) + dst[i++] = c; + + if (i == dst_sz) { + WRN("Could not flush stream: %d. Partial content: %.*s\n", + ENOSPC, (int) dst_sz, dst); + i--; + } + + return c == endchar ? i : 0; +} + +static int output_builtin_alias_bin(struct depmod *depmod, FILE *out) +{ + FILE *in; + struct index_node *idx; + int ret; + + if (out == stdout) + return 0; + + in = dfdopen(depmod->cfg->dirname, "modules.builtin.modinfo", O_RDONLY, "r"); + if (in == NULL) + return 0; + + idx = index_create(); + if (idx == NULL) { + fclose(in); + return -ENOMEM; + } + + /* format: modname.key=value\0 */ + while (!feof(in) && !ferror(in)) { + char alias[PATH_MAX]; + char modname[PATH_MAX]; + char value[PATH_MAX]; + size_t len; + + len = flush_stream_to(in, '.', modname, sizeof(modname)); + modname[len] = '\0'; + if (!len) + continue; + + len = flush_stream_to(in, '=', value, sizeof(value)); + value[len] = '\0'; + if (!streq(value, "alias")) { + flush_stream(in, '\0'); + continue; + } + + len = flush_stream_to(in, '\0', value, sizeof(value)); + value[len] = '\0'; + if (!len) + continue; + + alias[0] = '\0'; + if (alias_normalize(value, alias, NULL) < 0) { + WRN("Unmatched bracket in %s\n", value); + continue; + } + + index_insert(idx, alias, modname, 0); + } + + if (ferror(in)) { + ret = -EINVAL; + } else { + index_write(idx, out); + ret = 0; + } + + index_destroy(idx); + fclose(in); + + return ret; +} + +static int output_devname(struct depmod *depmod, FILE *out) +{ + size_t i; + bool empty = true; + + for (i = 0; i < depmod->modules.count; i++) { + const struct mod *mod = depmod->modules.array[i]; + struct kmod_list *l; + const char *devname = NULL; + char type = '\0'; + unsigned int major = 0, minor = 0; + + kmod_list_foreach(l, mod->info_list) { + const char *key = kmod_module_info_get_key(l); + const char *value = kmod_module_info_get_value(l); + unsigned int maj, min; + + if (!streq(key, "alias")) + continue; + + if (strstartswith(value, "devname:")) + devname = value + sizeof("devname:") - 1; + else if (sscanf(value, "char-major-%u-%u", + &maj, &min) == 2) { + type = 'c'; + major = maj; + minor = min; + } else if (sscanf(value, "block-major-%u-%u", + &maj, &min) == 2) { + type = 'b'; + major = maj; + minor = min; + } + + if (type != '\0' && devname != NULL) + break; + } + + if (devname != NULL) { + if (type != '\0') { + if (empty) { + fputs("# Device nodes to trigger on-demand module loading.\n", + out); + empty = false; + } + fprintf(out, "%s %s %c%u:%u\n", mod->modname, + devname, type, major, minor); + } else + ERR("Module '%s' has devname (%s) but " + "lacks major and minor information. " + "Ignoring.\n", mod->modname, devname); + } + } + + return 0; +} + +static int depmod_output(struct depmod *depmod, FILE *out) +{ + static const struct depfile { + const char *name; + int (*cb)(struct depmod *depmod, FILE *out); + } *itr, depfiles[] = { + { "modules.dep", output_deps }, + { "modules.dep.bin", output_deps_bin }, + { "modules.alias", output_aliases }, + { "modules.alias.bin", output_aliases_bin }, + { "modules.softdep", output_softdeps }, + { "modules.symbols", output_symbols }, + { "modules.symbols.bin", output_symbols_bin }, + { "modules.builtin.bin", output_builtin_bin }, + { "modules.builtin.alias.bin", output_builtin_alias_bin }, + { "modules.devname", output_devname }, + { } + }; + const char *dname = depmod->cfg->outdirname; + int dfd, err = 0; + struct timeval tv; + + gettimeofday(&tv, NULL); + + if (out != NULL) + dfd = -1; + else { + err = mkdir_p(dname, strlen(dname), 0755); + if (err < 0) { + CRIT("could not create directory %s: %m\n", dname); + return err; + } + dfd = open(dname, O_RDONLY); + if (dfd < 0) { + err = -errno; + CRIT("could not open directory %s: %m\n", dname); + return err; + } + } + + for (itr = depfiles; itr->name != NULL; itr++) { + FILE *fp = out; + char tmp[NAME_MAX] = ""; + int r, ferr; + + if (fp == NULL) { + int flags = O_CREAT | O_EXCL | O_WRONLY; + int mode = 0644; + int fd; + + snprintf(tmp, sizeof(tmp), "%s.%i.%li.%li", itr->name, getpid(), + tv.tv_usec, tv.tv_sec); + fd = openat(dfd, tmp, flags, mode); + if (fd < 0) { + ERR("openat(%s, %s, %o, %o): %m\n", + dname, tmp, flags, mode); + continue; + } + fp = fdopen(fd, "wb"); + if (fp == NULL) { + ERR("fdopen(%d=%s/%s): %m\n", fd, dname, tmp); + close(fd); + continue; + } + } + + r = itr->cb(depmod, fp); + if (fp == out) + continue; + + ferr = ferror(fp) | fclose(fp); + + if (r < 0) { + if (unlinkat(dfd, tmp, 0) != 0) + ERR("unlinkat(%s, %s): %m\n", dname, tmp); + + ERR("Could not write index '%s': %s\n", itr->name, + strerror(-r)); + err = -errno; + break; + } + + if (renameat(dfd, tmp, dfd, itr->name) != 0) { + err = -errno; + CRIT("renameat(%s, %s, %s, %s): %m\n", + dname, tmp, dname, itr->name); + break; + } + + if (ferr) { + err = -ENOSPC; + ERR("Could not create index '%s'. Output is truncated: %s\n", + itr->name, strerror(-err)); + break; + } + } + + if (dfd >= 0) + close(dfd); + + return err; +} + +static void depmod_add_fake_syms(struct depmod *depmod) +{ + /* __this_module is magic inserted by kernel loader. */ + depmod_symbol_add(depmod, "__this_module", true, 0, NULL); + /* On S390, this is faked up too */ + depmod_symbol_add(depmod, "_GLOBAL_OFFSET_TABLE_", true, 0, NULL); + /* On PowerPC64 ABIv2, .TOC. is more or less _GLOBAL_OFFSET_TABLE_ */ + if (!depmod_symbol_find(depmod, "TOC.")) + depmod_symbol_add(depmod, "TOC.", true, 0, NULL); +} + +static int depmod_load_symvers(struct depmod *depmod, const char *filename) +{ + char line[10240]; + FILE *fp; + unsigned int linenum = 0; + + fp = fopen(filename, "r"); + if (fp == NULL) { + int err = -errno; + DBG("load symvers: %s: %m\n", filename); + return err; + } + DBG("load symvers: %s\n", filename); + + /* eg. "0xb352177e\tfind_first_bit\tvmlinux\tEXPORT_SYMBOL" */ + while (fgets(line, sizeof(line), fp) != NULL) { + const char *ver, *sym, *where; + char *verend; + uint64_t crc; + + linenum++; + + ver = strtok(line, " \t"); + sym = strtok(NULL, " \t"); + where = strtok(NULL, " \t"); + if (!ver || !sym || !where) + continue; + + if (!streq(where, "vmlinux")) + continue; + + crc = strtoull(ver, &verend, 16); + if (verend[0] != '\0') { + ERR("%s:%u Invalid symbol version %s: %m\n", + filename, linenum, ver); + continue; + } + + depmod_symbol_add(depmod, sym, false, crc, NULL); + } + depmod_add_fake_syms(depmod); + + DBG("loaded symvers: %s\n", filename); + + fclose(fp); + return 0; +} + +static int depmod_load_system_map(struct depmod *depmod, const char *filename) +{ + const char ksymstr[] = "__ksymtab_"; + const size_t ksymstr_len = sizeof(ksymstr) - 1; + char line[10240]; + FILE *fp; + unsigned int linenum = 0; + + fp = fopen(filename, "r"); + if (fp == NULL) { + int err = -errno; + DBG("load System.map: %s: %m\n", filename); + return err; + } + DBG("load System.map: %s\n", filename); + + /* eg. c0294200 R __ksymtab_devfs_alloc_devnum */ + while (fgets(line, sizeof(line), fp) != NULL) { + char *p, *end; + + linenum++; + + p = strchr(line, ' '); + if (p == NULL) + goto invalid_syntax; + p++; + p = strchr(p, ' '); + if (p == NULL) + goto invalid_syntax; + p++; + + /* skip prefix */ + if (p[0] == depmod->cfg->sym_prefix) + p++; + + /* Covers gpl-only and normal symbols. */ + if (strncmp(p, ksymstr, ksymstr_len) != 0) + continue; + + end = strchr(p, '\n'); + if (end != NULL) + *end = '\0'; + + depmod_symbol_add(depmod, p + ksymstr_len, true, 0, NULL); + continue; + + invalid_syntax: + ERR("%s:%u: invalid line: %s\n", filename, linenum, line); + } + depmod_add_fake_syms(depmod); + + DBG("loaded System.map: %s\n", filename); + + fclose(fp); + return 0; +} + + +static int depfile_up_to_date_dir(DIR *d, time_t mtime, size_t baselen, char *path) +{ + struct dirent *de; + int err = 1, dfd = dirfd(d); + + while ((de = readdir(d)) != NULL) { + const char *name = de->d_name; + size_t namelen; + struct stat st; + + if (name[0] == '.' && (name[1] == '\0' || + (name[1] == '.' && name[2] == '\0'))) + continue; + if (streq(name, "build") || streq(name, "source")) + continue; + namelen = strlen(name); + if (baselen + namelen + 2 >= PATH_MAX) { + path[baselen] = '\0'; + ERR("path is too long %s%s\n", path, name); + continue; + } + + if (fstatat(dfd, name, &st, 0) < 0) { + ERR("fstatat(%d, %s): %m\n", dfd, name); + continue; + } + + if (S_ISDIR(st.st_mode)) { + int fd; + DIR *subdir; + memcpy(path + baselen, name, namelen + 1); + if (baselen + namelen + 2 + NAME_MAX >= PATH_MAX) { + ERR("directory path is too long %s\n", path); + continue; + } + fd = openat(dfd, name, O_RDONLY); + if (fd < 0) { + ERR("openat(%d, %s, O_RDONLY): %m\n", + dfd, name); + continue; + } + subdir = fdopendir(fd); + if (subdir == NULL) { + ERR("fdopendir(%d): %m\n", fd); + close(fd); + continue; + } + path[baselen + namelen] = '/'; + path[baselen + namelen + 1] = '\0'; + err = depfile_up_to_date_dir(subdir, mtime, + baselen + namelen + 1, + path); + closedir(subdir); + } else if (S_ISREG(st.st_mode)) { + if (!path_ends_with_kmod_ext(name, namelen)) + continue; + + memcpy(path + baselen, name, namelen + 1); + err = st.st_mtime <= mtime; + if (err == 0) { + DBG("%s %"PRIu64" is newer than %"PRIu64"\n", + path, (uint64_t)st.st_mtime, + (uint64_t)mtime); + } + } else { + ERR("unsupported file type %s: %o\n", + path, st.st_mode & S_IFMT); + continue; + } + + if (err == 0) + break; /* outdated! */ + else if (err < 0) { + path[baselen + namelen] = '\0'; + ERR("failed %s: %s\n", path, strerror(-err)); + err = 1; /* ignore errors */ + } + } + + return err; +} + +/* uptodate: 1, outdated: 0, errors < 0 */ +static int depfile_up_to_date(const char *dirname) +{ + char path[PATH_MAX]; + DIR *d = opendir(dirname); + struct stat st; + size_t baselen; + int err; + if (d == NULL) { + err = -errno; + ERR("could not open directory %s: %m\n", dirname); + return err; + } + + if (fstatat(dirfd(d), "modules.dep", &st, 0) != 0) { + err = -errno; + ERR("could not fstatat(%s, modules.dep): %m\n", dirname); + closedir(d); + return err; + } + + baselen = strlen(dirname); + memcpy(path, dirname, baselen); + path[baselen] = '/'; + baselen++; + path[baselen] = '\0'; + + err = depfile_up_to_date_dir(d, st.st_mtime, baselen, path); + closedir(d); + return err; +} + +static int is_version_number(const char *version) +{ + unsigned int d1, d2; + return (sscanf(version, "%u.%u", &d1, &d2) == 2); +} + +static int do_depmod(int argc, char *argv[]) +{ + FILE *out = NULL; + int err = 0, all = 0, maybe_all = 0, n_config_paths = 0; + _cleanup_free_ char *root = NULL; + _cleanup_free_ char *out_root = NULL; + _cleanup_free_ const char **config_paths = NULL; + const char *system_map = NULL; + const char *module_symvers = NULL; + const char *null_kmod_config = NULL; + struct utsname un; + struct kmod_ctx *ctx = NULL; + struct cfg cfg; + struct depmod depmod; + + memset(&cfg, 0, sizeof(cfg)); + memset(&depmod, 0, sizeof(depmod)); + + for (;;) { + int c, idx = 0; + c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx); + if (c == -1) + break; + switch (c) { + case 'a': + all = 1; + break; + case 'A': + maybe_all = 1; + break; + case 'b': + if (root) + free(root); + root = path_make_absolute_cwd(optarg); + break; + case 'o': + if (out_root) + free(out_root); + out_root = path_make_absolute_cwd(optarg); + break; + case 'C': { + size_t bytes = sizeof(char *) * (n_config_paths + 2); + void *tmp = realloc(config_paths, bytes); + if (!tmp) { + fputs("Error: out-of-memory\n", stderr); + goto cmdline_failed; + } + config_paths = tmp; + config_paths[n_config_paths] = optarg; + n_config_paths++; + config_paths[n_config_paths] = NULL; + break; + } + case 'E': + module_symvers = optarg; + cfg.check_symvers = 1; + break; + case 'F': + system_map = optarg; + break; + case 'e': + cfg.print_unknown = 1; + break; + case 'v': + verbose++; + break; + case 'n': + out = stdout; + break; + case 'P': + if (optarg[1] != '\0') { + CRIT("-P only takes a single char\n"); + goto cmdline_failed; + } + cfg.sym_prefix = optarg[0]; + break; + case 'w': + cfg.warn_dups = 1; + break; + case 'u': + case 'q': + case 'r': + case 'm': + if (idx > 0) + WRN("Ignored deprecated option --%s\n", + cmdopts[idx].name); + else + WRN("Ignored deprecated option -%c\n", c); + + break; + case 'h': + help(); + return EXIT_SUCCESS; + case 'V': + puts(PACKAGE " version " VERSION); + puts(KMOD_FEATURES); + return EXIT_SUCCESS; + case '?': + goto cmdline_failed; + default: + ERR("unexpected getopt_long() value '%c'.\n", c); + goto cmdline_failed; + } + } + + if (optind < argc) { + if (!is_version_number(argv[optind])) { + ERR("Bad version passed %s\n", argv[optind]); + goto cmdline_failed; + } + cfg.kversion = argv[optind]; + optind++; + } else { + if (uname(&un) < 0) { + CRIT("uname() failed: %s\n", strerror(errno)); + goto cmdline_failed; + } + cfg.kversion = un.release; + } + + cfg.dirnamelen = snprintf(cfg.dirname, PATH_MAX, + "%s" MODULE_DIRECTORY "/%s", + root ?: "", cfg.kversion); + + cfg.outdirnamelen = snprintf(cfg.outdirname, PATH_MAX, + "%s" MODULE_DIRECTORY "/%s", + out_root ?: (root ?: ""), cfg.kversion); + + if (optind == argc) + all = 1; + + if (maybe_all) { + if (out == stdout) + goto done; + /* ignore up-to-date errors (< 0) */ + if (depfile_up_to_date(cfg.dirname) == 1) + goto done; + all = 1; + } + + ctx = kmod_new(cfg.dirname, &null_kmod_config); + if (ctx == NULL) { + CRIT("kmod_new(\"%s\", {NULL}) failed: %m\n", cfg.dirname); + goto cmdline_failed; + } + + log_setup_kmod_log(ctx, verbose); + + err = depmod_init(&depmod, &cfg, ctx); + if (err < 0) { + CRIT("depmod_init: %s\n", strerror(-err)); + goto depmod_init_failed; + } + ctx = NULL; /* owned by depmod */ + + if (module_symvers != NULL) { + err = depmod_load_symvers(&depmod, module_symvers); + if (err < 0) { + CRIT("could not load %s: %s\n", module_symvers, + strerror(-err)); + goto cmdline_failed; + } + } else if (system_map != NULL) { + err = depmod_load_system_map(&depmod, system_map); + if (err < 0) { + CRIT("could not load %s: %s\n", system_map, + strerror(-err)); + goto cmdline_failed; + } + } else if (cfg.print_unknown) { + WRN("-e needs -E or -F\n"); + cfg.print_unknown = 0; + } + + if (all) { + err = cfg_load(&cfg, config_paths); + if (err < 0) { + CRIT("could not load configuration files\n"); + goto cmdline_modules_failed; + } + err = depmod_modules_search(&depmod); + if (err < 0) { + CRIT("could not search modules: %s\n", strerror(-err)); + goto cmdline_modules_failed; + } + } else { + int i; + + for (i = optind; i < argc; i++) { + const char *path = argv[i]; + struct kmod_module *mod; + + if (path[0] != '/') { + CRIT("%s: not absolute path.\n", path); + goto cmdline_modules_failed; + } + + err = kmod_module_new_from_path(depmod.ctx, path, &mod); + if (err < 0) { + CRIT("could not create module %s: %s\n", + path, strerror(-err)); + goto cmdline_modules_failed; + } + + err = depmod_module_add(&depmod, mod); + if (err < 0) { + CRIT("could not add module %s: %s\n", + path, strerror(-err)); + kmod_module_unref(mod); + goto cmdline_modules_failed; + } + } + } + + err = depmod_modules_build_array(&depmod); + if (err < 0) { + CRIT("could not build module array: %s\n", + strerror(-err)); + goto cmdline_modules_failed; + } + + depmod_modules_sort(&depmod); + err = depmod_load(&depmod); + if (err < 0) + goto cmdline_modules_failed; + + err = depmod_output(&depmod, out); + +done: + depmod_shutdown(&depmod); + cfg_free(&cfg); + return err >= 0 ? EXIT_SUCCESS : EXIT_FAILURE; + +cmdline_modules_failed: + depmod_shutdown(&depmod); +depmod_init_failed: + if (ctx != NULL) + kmod_unref(ctx); +cmdline_failed: + cfg_free(&cfg); + return EXIT_FAILURE; +} + +const struct kmod_cmd kmod_cmd_compat_depmod = { + .name = "depmod", + .cmd = do_depmod, + .help = "compat depmod command", +}; diff --git a/tools/insert.c b/tools/insert.c new file mode 100644 index 0000000..0ebcef9 --- /dev/null +++ b/tools/insert.c @@ -0,0 +1,128 @@ +/* + * kmod-insert - insert a module into the kernel. + * + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * Copyright (C) 2011-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include + +#include + +#include "kmod.h" + +static const char cmdopts_s[] = "h"; +static const struct option cmdopts[] = { + {"help", no_argument, 0, 'h'}, + { } +}; + +static void help(void) +{ + printf("Usage:\n" + "\t%s insert [options] module\n" + "Options:\n" + "\t-h, --help show this help\n", + program_invocation_short_name); +} + +static const char *mod_strerror(int err) +{ + switch (err) { + case KMOD_PROBE_APPLY_BLACKLIST: + return "Module is blacklisted"; + case -EEXIST: + return "Module already in kernel"; + case -ENOENT: + return "Unknown symbol in module or unknown parameter (see dmesg)"; + default: + return strerror(-err); + } +} + +static int do_insert(int argc, char *argv[]) +{ + struct kmod_ctx *ctx; + struct kmod_list *list = NULL, *l; + const char *name; + int err, r = EXIT_SUCCESS; + + for (;;) { + int c, idx = 0; + c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx); + if (c == -1) + break; + switch (c) { + case 'h': + help(); + return EXIT_SUCCESS; + default: + ERR("Unexpected getopt_long() value '%c'.\n", c); + return EXIT_FAILURE; + } + } + + if (optind >= argc) { + ERR("Missing module name\n"); + return EXIT_FAILURE; + } + + ctx = kmod_new(NULL, NULL); + if (!ctx) { + ERR("kmod_new() failed!\n"); + return EXIT_FAILURE; + } + + name = argv[optind]; + err = kmod_module_new_from_lookup(ctx, name, &list); + if (err < 0) { + ERR("Could not lookup module matching '%s': %s\n", name, strerror(-err)); + r = EXIT_FAILURE; + goto end; + } + + if (list == NULL) { + ERR("No module matches '%s'\n", name); + r = EXIT_FAILURE; + goto end; + } + + kmod_list_foreach(l, list) { + struct kmod_module *mod = kmod_module_get_module(l); + + err = kmod_module_probe_insert_module(mod, KMOD_PROBE_APPLY_BLACKLIST, NULL, NULL, NULL, NULL); + if (err != 0) { + r = EXIT_FAILURE; + ERR("Could not insert '%s': %s\n", kmod_module_get_name(mod), mod_strerror(err)); + } + + kmod_module_unref(mod); + } + + kmod_module_unref_list(list); +end: + kmod_unref(ctx); + return r; +} + +const struct kmod_cmd kmod_cmd_insert = { + .name = "insert", + .cmd = do_insert, + .help = "insert a module into the kernel", +}; diff --git a/tools/insmod.c b/tools/insmod.c new file mode 100644 index 0000000..c422971 --- /dev/null +++ b/tools/insmod.c @@ -0,0 +1,166 @@ +/* + * kmod-insmod - insert modules into linux kernel using libkmod. + * + * Copyright (C) 2011-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include + +#include + +#include + +#include "kmod.h" + +static const char cmdopts_s[] = "psfVh"; +static const struct option cmdopts[] = { + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {NULL, 0, 0, 0} +}; + +static void help(void) +{ + printf("Usage:\n" + "\t%s [options] filename [args]\n" + "Options:\n" + "\t-V, --version show version\n" + "\t-h, --help show this help\n", + program_invocation_short_name); +} + +static const char *mod_strerror(int err) +{ + switch (err) { + case ENOEXEC: + return "Invalid module format"; + case ENOENT: + return "Unknown symbol in module"; + case ESRCH: + return "Module has wrong symbol version"; + case EINVAL: + return "Invalid parameters"; + default: + return strerror(err); + } +} + +static int do_insmod(int argc, char *argv[]) +{ + struct kmod_ctx *ctx; + struct kmod_module *mod; + const char *filename; + char *opts = NULL; + size_t optslen = 0; + int i, err; + const char *null_config = NULL; + unsigned int flags = 0; + + for (;;) { + int c, idx = 0; + c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx); + if (c == -1) + break; + switch (c) { + case 'p': + case 's': + /* ignored, for compatibility only */ + break; + case 'f': + flags |= KMOD_PROBE_FORCE_MODVERSION; + flags |= KMOD_PROBE_FORCE_VERMAGIC; + break; + case 'h': + help(); + return EXIT_SUCCESS; + case 'V': + puts(PACKAGE " version " VERSION); + puts(KMOD_FEATURES); + return EXIT_SUCCESS; + case '?': + return EXIT_FAILURE; + default: + ERR("unexpected getopt_long() value '%c'.\n", + c); + return EXIT_FAILURE; + } + } + + if (optind >= argc) { + ERR("missing filename.\n"); + return EXIT_FAILURE; + } + + filename = argv[optind]; + if (streq(filename, "-")) { + ERR("this tool does not support loading from stdin!\n"); + return EXIT_FAILURE; + } + + for (i = optind + 1; i < argc; i++) { + size_t len = strlen(argv[i]); + void *tmp = realloc(opts, optslen + len + 2); + if (tmp == NULL) { + ERR("out of memory\n"); + free(opts); + return EXIT_FAILURE; + } + opts = tmp; + if (optslen > 0) { + opts[optslen] = ' '; + optslen++; + } + memcpy(opts + optslen, argv[i], len); + optslen += len; + opts[optslen] = '\0'; + } + + ctx = kmod_new(NULL, &null_config); + if (!ctx) { + ERR("kmod_new() failed!\n"); + free(opts); + return EXIT_FAILURE; + } + + err = kmod_module_new_from_path(ctx, filename, &mod); + if (err < 0) { + ERR("could not load module %s: %s\n", filename, + strerror(-err)); + goto end; + } + + err = kmod_module_insert_module(mod, flags, opts); + if (err < 0) { + ERR("could not insert module %s: %s\n", filename, + mod_strerror(-err)); + } + kmod_module_unref(mod); + +end: + kmod_unref(ctx); + free(opts); + return err >= 0 ? EXIT_SUCCESS : EXIT_FAILURE; +} + +const struct kmod_cmd kmod_cmd_compat_insmod = { + .name = "insmod", + .cmd = do_insmod, + .help = "compat insmod command", +}; diff --git a/tools/kmod.c b/tools/kmod.c new file mode 100644 index 0000000..55689c0 --- /dev/null +++ b/tools/kmod.c @@ -0,0 +1,179 @@ +/* + * kmod - one tool to rule them all + * + * Copyright (C) 2011-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include + +#include + +#include + +#include "kmod.h" + +static const char options_s[] = "+hV"; +static const struct option options[] = { + { "help", no_argument, NULL, 'h' }, + { "version", no_argument, NULL, 'V' }, + {} +}; + +static const struct kmod_cmd kmod_cmd_help; + +static const struct kmod_cmd *kmod_cmds[] = { + &kmod_cmd_help, + &kmod_cmd_list, + &kmod_cmd_static_nodes, + +#ifdef ENABLE_EXPERIMENTAL + &kmod_cmd_insert, + &kmod_cmd_remove, +#endif +}; + +static const struct kmod_cmd *kmod_compat_cmds[] = { + &kmod_cmd_compat_lsmod, + &kmod_cmd_compat_rmmod, + &kmod_cmd_compat_insmod, + &kmod_cmd_compat_modinfo, + &kmod_cmd_compat_modprobe, + &kmod_cmd_compat_depmod, +}; + +static int kmod_help(int argc, char *argv[]) +{ + size_t i; + + printf("kmod - Manage kernel modules: list, load, unload, etc\n" + "Usage:\n" + "\t%s [options] command [command_options]\n\n" + "Options:\n" + "\t-V, --version show version\n" + "\t-h, --help show this help\n\n" + "Commands:\n", basename(argv[0])); + + for (i = 0; i < ARRAY_SIZE(kmod_cmds); i++) { + if (kmod_cmds[i]->help != NULL) { + printf(" %-12s %s\n", kmod_cmds[i]->name, + kmod_cmds[i]->help); + } + } + + puts("\nkmod also handles gracefully if called from following symlinks:"); + + for (i = 0; i < ARRAY_SIZE(kmod_compat_cmds); i++) { + if (kmod_compat_cmds[i]->help != NULL) { + printf(" %-12s %s\n", kmod_compat_cmds[i]->name, + kmod_compat_cmds[i]->help); + } + } + + return EXIT_SUCCESS; +} + +static const struct kmod_cmd kmod_cmd_help = { + .name = "help", + .cmd = kmod_help, + .help = "Show help message", +}; + +static int handle_kmod_commands(int argc, char *argv[]) +{ + const char *cmd; + int err = 0; + size_t i; + + for (;;) { + int c; + + c = getopt_long(argc, argv, options_s, options, NULL); + if (c == -1) + break; + + switch (c) { + case 'h': + kmod_help(argc, argv); + return EXIT_SUCCESS; + case 'V': + puts(PACKAGE " version " VERSION); + puts(KMOD_FEATURES); + return EXIT_SUCCESS; + case '?': + return EXIT_FAILURE; + default: + fprintf(stderr, "Error: unexpected getopt_long() value '%c'.\n", c); + return EXIT_FAILURE; + } + } + + if (optind >= argc) { + fputs("missing command\n", stderr); + goto fail; + } + + cmd = argv[optind]; + + for (i = 0, err = -EINVAL; i < ARRAY_SIZE(kmod_cmds); i++) { + if (streq(kmod_cmds[i]->name, cmd)) { + err = kmod_cmds[i]->cmd(--argc, ++argv); + break; + } + } + + if (err < 0) { + fprintf(stderr, "invalid command '%s'\n", cmd); + goto fail; + } + + return err; + +fail: + kmod_help(argc, argv); + return EXIT_FAILURE; +} + + +static int handle_kmod_compat_commands(int argc, char *argv[]) +{ + const char *cmd; + size_t i; + + cmd = basename(argv[0]); + + for (i = 0; i < ARRAY_SIZE(kmod_compat_cmds); i++) { + if (streq(kmod_compat_cmds[i]->name, cmd)) + return kmod_compat_cmds[i]->cmd(argc, argv); + } + + return -ENOENT; +} + +int main(int argc, char *argv[]) +{ + int err; + + if (streq(program_invocation_short_name, "kmod")) + err = handle_kmod_commands(argc, argv); + else + err = handle_kmod_compat_commands(argc, argv); + + return err; +} diff --git a/tools/kmod.h b/tools/kmod.h new file mode 100644 index 0000000..1770786 --- /dev/null +++ b/tools/kmod.h @@ -0,0 +1,42 @@ +/* + * kmod - one tool to rule them all + * + * Copyright (C) 2011-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include + +struct kmod_cmd { + const char *name; + int (*cmd)(int argc, char *argv[]); + const char *help; +}; + +extern const struct kmod_cmd kmod_cmd_compat_lsmod; +extern const struct kmod_cmd kmod_cmd_compat_rmmod; +extern const struct kmod_cmd kmod_cmd_compat_insmod; +extern const struct kmod_cmd kmod_cmd_compat_modinfo; +extern const struct kmod_cmd kmod_cmd_compat_modprobe; +extern const struct kmod_cmd kmod_cmd_compat_depmod; + +extern const struct kmod_cmd kmod_cmd_insert; +extern const struct kmod_cmd kmod_cmd_list; +extern const struct kmod_cmd kmod_cmd_static_nodes; +extern const struct kmod_cmd kmod_cmd_remove; + +#include "log.h" diff --git a/tools/kmod.pc.in b/tools/kmod.pc.in new file mode 100644 index 0000000..97215c8 --- /dev/null +++ b/tools/kmod.pc.in @@ -0,0 +1,10 @@ +prefix=@prefix@ +sysconfdir=@sysconfdir@ +distconfdir=@distconfdir@ +module_directory=@module_directory@ +module_compressions=@module_compressions@ +module_signatures=@module_signatures@ + +Name: kmod +Description: Tools to deal with kernel modules +Version: @VERSION@ diff --git a/tools/log.c b/tools/log.c new file mode 100644 index 0000000..3317a35 --- /dev/null +++ b/tools/log.c @@ -0,0 +1,149 @@ +/* + * kmod - log infrastructure + * + * Copyright (C) 2012-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include + +#include + +#include "kmod.h" + +#define PRIO_MAX_SIZE 32 + +static bool log_use_syslog; +static int log_priority = LOG_WARNING; + +static const char *prio_to_str(char buf[static PRIO_MAX_SIZE], int prio) +{ + const char *prioname; + + switch (prio) { + case LOG_CRIT: + prioname = "FATAL"; + break; + case LOG_ERR: + prioname = "ERROR"; + break; + case LOG_WARNING: + prioname = "WARNING"; + break; + case LOG_NOTICE: + prioname = "NOTICE"; + break; + case LOG_INFO: + prioname = "INFO"; + break; + case LOG_DEBUG: + prioname = "DEBUG"; + break; + default: + snprintf(buf, PRIO_MAX_SIZE, "LOG-%03d", prio); + prioname = buf; + } + + return prioname; +} + +_printf_format_(6, 0) +static void log_kmod(void *data, int priority, const char *file, int line, + const char *fn, const char *format, va_list args) +{ + char buf[PRIO_MAX_SIZE]; + const char *prioname; + char *str; + + prioname = prio_to_str(buf, priority); + + if (vasprintf(&str, format, args) < 0) + return; + + if (log_use_syslog) { +#ifdef ENABLE_DEBUG + syslog(priority, "%s: %s:%d %s() %s", prioname, file, line, + fn, str); +#else + syslog(priority, "%s: %s", prioname, str); +#endif + } else { +#ifdef ENABLE_DEBUG + fprintf(stderr, "%s: %s: %s:%d %s() %s", + program_invocation_short_name, prioname, file, line, + fn, str); +#else + fprintf(stderr, "%s: %s: %s", program_invocation_short_name, + prioname, str); +#endif + } + + free(str); + (void)data; +} +void log_open(bool use_syslog) +{ + log_use_syslog = use_syslog; + + if (log_use_syslog) + openlog(program_invocation_short_name, LOG_CONS, LOG_DAEMON); +} + +void log_close(void) +{ + if (log_use_syslog) + closelog(); +} + +void log_printf(int prio, const char *fmt, ...) +{ + char buf[PRIO_MAX_SIZE]; + const char *prioname; + char *msg; + va_list args; + + if (prio > log_priority) + return; + + va_start(args, fmt); + if (vasprintf(&msg, fmt, args) < 0) + msg = NULL; + va_end(args); + if (msg == NULL) + return; + + prioname = prio_to_str(buf, prio); + + if (log_use_syslog) + syslog(prio, "%s: %s", prioname, msg); + else + fprintf(stderr, "%s: %s: %s", program_invocation_short_name, + prioname, msg); + free(msg); + + if (prio <= LOG_CRIT) + exit(EXIT_FAILURE); +} + +void log_setup_kmod_log(struct kmod_ctx *ctx, int priority) +{ + log_priority = priority; + + kmod_set_log_priority(ctx, log_priority); + kmod_set_log_fn(ctx, log_kmod, NULL); +} diff --git a/tools/log.h b/tools/log.h new file mode 100644 index 0000000..d55a4c6 --- /dev/null +++ b/tools/log.h @@ -0,0 +1,37 @@ +/* + * kmod - log infrastructure + * + * Copyright (C) 2012-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include + +#include "kmod.h" + +void log_open(bool use_syslog); +void log_close(void); +void log_printf(int prio, const char *fmt, ...) _printf_format_(2, 3); +#define CRIT(...) log_printf(LOG_CRIT, __VA_ARGS__) +#define ERR(...) log_printf(LOG_ERR, __VA_ARGS__) +#define WRN(...) log_printf(LOG_WARNING, __VA_ARGS__) +#define INF(...) log_printf(LOG_INFO, __VA_ARGS__) +#define DBG(...) log_printf(LOG_DEBUG, __VA_ARGS__) + +struct kmod_ctx; +void log_setup_kmod_log(struct kmod_ctx *ctx, int priority); diff --git a/tools/lsmod.c b/tools/lsmod.c new file mode 100644 index 0000000..d9a27f2 --- /dev/null +++ b/tools/lsmod.c @@ -0,0 +1,102 @@ +/* + * kmod-lsmod - list modules from linux kernel using libkmod. + * + * Copyright (C) 2011-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include "kmod.h" + +static int do_lsmod(int argc, char *argv[]) +{ + struct kmod_ctx *ctx; + const char *null_config = NULL; + struct kmod_list *list, *itr; + int err; + + if (argc != 1) { + fprintf(stderr, "Usage: %s\n", argv[0]); + return EXIT_FAILURE; + } + + ctx = kmod_new(NULL, &null_config); + if (ctx == NULL) { + fputs("Error: kmod_new() failed!\n", stderr); + return EXIT_FAILURE; + } + + err = kmod_module_new_from_loaded(ctx, &list); + if (err < 0) { + fprintf(stderr, "Error: could not get list of modules: %s\n", + strerror(-err)); + kmod_unref(ctx); + return EXIT_FAILURE; + } + + puts("Module Size Used by"); + + kmod_list_foreach(itr, list) { + struct kmod_module *mod = kmod_module_get_module(itr); + const char *name = kmod_module_get_name(mod); + int use_count = kmod_module_get_refcnt(mod); + long size = kmod_module_get_size(mod); + struct kmod_list *holders, *hitr; + int first = 1; + + printf("%-19s %8ld %d", name, size, use_count); + holders = kmod_module_get_holders(mod); + kmod_list_foreach(hitr, holders) { + struct kmod_module *hm = kmod_module_get_module(hitr); + + if (!first) { + putchar(','); + } else { + putchar(' '); + first = 0; + } + + fputs(kmod_module_get_name(hm), stdout); + kmod_module_unref(hm); + } + putchar('\n'); + kmod_module_unref_list(holders); + kmod_module_unref(mod); + } + kmod_module_unref_list(list); + kmod_unref(ctx); + + return EXIT_SUCCESS; +} + +const struct kmod_cmd kmod_cmd_compat_lsmod = { + .name = "lsmod", + .cmd = do_lsmod, + .help = "compat lsmod command", +}; + +const struct kmod_cmd kmod_cmd_list = { + .name = "list", + .cmd = do_lsmod, + .help = "list currently loaded modules", +}; diff --git a/tools/modinfo.c b/tools/modinfo.c new file mode 100644 index 0000000..cacc32d --- /dev/null +++ b/tools/modinfo.c @@ -0,0 +1,500 @@ +/* + * kmod-modinfo - query kernel module information using libkmod. + * + * Copyright (C) 2011-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include "kmod.h" + +static char separator = '\n'; +static const char *field = NULL; + +struct param { + struct param *next; + const char *name; + const char *param; + const char *type; + int namelen; + int paramlen; + int typelen; +}; + +static struct param *add_param(const char *name, int namelen, const char *param, int paramlen, const char *type, int typelen, struct param **list) +{ + struct param *it; + + for (it = *list; it != NULL; it = it->next) { + if (it->namelen == namelen && + memcmp(it->name, name, namelen) == 0) + break; + } + + if (it == NULL) { + it = malloc(sizeof(struct param)); + if (it == NULL) + return NULL; + it->next = *list; + *list = it; + it->name = name; + it->namelen = namelen; + it->param = NULL; + it->type = NULL; + it->paramlen = 0; + it->typelen = 0; + } + + if (param != NULL) { + it->param = param; + it->paramlen = paramlen; + } + + if (type != NULL) { + it->type = type; + it->typelen = typelen; + } + + return it; +} + +static int process_parm(const char *key, const char *value, struct param **params) +{ + const char *name, *param, *type; + int namelen, paramlen, typelen; + struct param *it; + const char *colon = strchr(value, ':'); + if (colon == NULL) { + ERR("Found invalid \"%s=%s\": missing ':'\n", + key, value); + return 0; + } + + name = value; + namelen = colon - value; + if (streq(key, "parm")) { + param = colon + 1; + paramlen = strlen(param); + type = NULL; + typelen = 0; + } else { + param = NULL; + paramlen = 0; + type = colon + 1; + typelen = strlen(type); + } + + it = add_param(name, namelen, param, paramlen, type, typelen, params); + if (it == NULL) { + ERR("Out of memory!\n"); + return -ENOMEM; + } + + return 0; +} + +static int modinfo_params_do(const struct kmod_list *list) +{ + const struct kmod_list *l; + struct param *params = NULL; + int err = 0; + + kmod_list_foreach(l, list) { + const char *key = kmod_module_info_get_key(l); + const char *value = kmod_module_info_get_value(l); + if (!streq(key, "parm") && !streq(key, "parmtype")) + continue; + + err = process_parm(key, value, ¶ms); + if (err < 0) + goto end; + } + + while (params != NULL) { + struct param *p = params; + params = p->next; + + if (p->param == NULL) + printf("%.*s: (%.*s)%c", + p->namelen, p->name, p->typelen, p->type, + separator); + else if (p->type != NULL) + printf("%.*s:%.*s (%.*s)%c", + p->namelen, p->name, + p->paramlen, p->param, + p->typelen, p->type, + separator); + else + printf("%.*s:%.*s%c", + p->namelen, p->name, + p->paramlen, p->param, + separator); + + free(p); + } + +end: + while (params != NULL) { + void *tmp = params; + params = params->next; + free(tmp); + } + + return err; +} + +static int modinfo_do(struct kmod_module *mod) +{ + struct kmod_list *l, *list = NULL; + struct param *params = NULL; + int err, is_builtin; + const char *filename = kmod_module_get_path(mod); + + is_builtin = (filename == NULL); + + if (is_builtin) { + if (field == NULL) + printf("%-16s%s%c", "name:", + kmod_module_get_name(mod), separator); + else if (field != NULL && streq(field, "name")) + printf("%s%c", kmod_module_get_name(mod), separator); + filename = "(builtin)"; + } + + if (field != NULL && streq(field, "filename")) { + printf("%s%c", filename, separator); + return 0; + } else if (field == NULL) { + printf("%-16s%s%c", "filename:", + filename, separator); + } + + err = kmod_module_get_info(mod, &list); + if (err < 0) { + if (is_builtin && err == -ENOENT) { + /* + * This is an old kernel that does not have a file + * with information about built-in modules. + */ + return 0; + } + ERR("could not get modinfo from '%s': %s\n", + kmod_module_get_name(mod), strerror(-err)); + return err; + } + + if (field != NULL && streq(field, "parm")) { + err = modinfo_params_do(list); + goto end; + } + + kmod_list_foreach(l, list) { + const char *key = kmod_module_info_get_key(l); + const char *value = kmod_module_info_get_value(l); + int keylen; + + if (field != NULL) { + if (!streq(field, key)) + continue; + /* filtered output contains no key, just value */ + printf("%s%c", value, separator); + continue; + } + + if (streq(key, "parm") || streq(key, "parmtype")) { + err = process_parm(key, value, ¶ms); + if (err < 0) + goto end; + continue; + } + + if (separator == '\0') { + printf("%s=%s%c", key, value, separator); + continue; + } + + keylen = strlen(key); + printf("%s:%-*s%s%c", key, 15 - keylen, "", value, separator); + } + + if (field != NULL) + goto end; + + while (params != NULL) { + struct param *p = params; + params = p->next; + + if (p->param == NULL) + printf("%-16s%.*s:%.*s%c", "parm:", + p->namelen, p->name, p->typelen, p->type, + separator); + else if (p->type != NULL) + printf("%-16s%.*s:%.*s (%.*s)%c", "parm:", + p->namelen, p->name, + p->paramlen, p->param, + p->typelen, p->type, + separator); + else + printf("%-16s%.*s:%.*s%c", + "parm:", + p->namelen, p->name, + p->paramlen, p->param, + separator); + + free(p); + } + +end: + while (params != NULL) { + void *tmp = params; + params = params->next; + free(tmp); + } + kmod_module_info_free_list(list); + + return err; +} + +static int modinfo_path_do(struct kmod_ctx *ctx, const char *path) +{ + struct kmod_module *mod; + int err = kmod_module_new_from_path(ctx, path, &mod); + if (err < 0) { + ERR("Module file %s not found.\n", path); + return err; + } + err = modinfo_do(mod); + kmod_module_unref(mod); + return err; +} + +static int modinfo_name_do(struct kmod_ctx *ctx, const char *name) +{ + struct kmod_module *mod = NULL; + int err; + + err = kmod_module_new_from_name_lookup(ctx, name, &mod); + if (err < 0 || mod == NULL) { + ERR("Module name %s not found.\n", name); + return err < 0 ? err : -ENOENT; + } + + err = modinfo_do(mod); + kmod_module_unref(mod); + + return err; +} + + +static int modinfo_alias_do(struct kmod_ctx *ctx, const char *alias) +{ + struct kmod_list *l, *list = NULL; + int err = kmod_module_new_from_lookup(ctx, alias, &list); + if (err < 0) { + ERR("Module alias %s not found.\n", alias); + return err; + } + + if (list == NULL) { + ERR("Module %s not found.\n", alias); + return -ENOENT; + } + + kmod_list_foreach(l, list) { + struct kmod_module *mod = kmod_module_get_module(l); + int r = modinfo_do(mod); + kmod_module_unref(mod); + if (r < 0) + err = r; + } + kmod_module_unref_list(list); + return err; +} + +static const char cmdopts_s[] = "adlpn0mF:k:b:Vh"; +static const struct option cmdopts[] = { + {"author", no_argument, 0, 'a'}, + {"description", no_argument, 0, 'd'}, + {"license", no_argument, 0, 'l'}, + {"parameters", no_argument, 0, 'p'}, + {"filename", no_argument, 0, 'n'}, + {"null", no_argument, 0, '0'}, + {"modname", no_argument, 0, 'm'}, + {"field", required_argument, 0, 'F'}, + {"set-version", required_argument, 0, 'k'}, + {"basedir", required_argument, 0, 'b'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {NULL, 0, 0, 0} +}; + +static void help(void) +{ + printf("Usage:\n" + "\t%s [options] [args]\n" + "Options:\n" + "\t-a, --author Print only 'author'\n" + "\t-d, --description Print only 'description'\n" + "\t-l, --license Print only 'license'\n" + "\t-p, --parameters Print only 'parm'\n" + "\t-n, --filename Print only 'filename'\n" + "\t-0, --null Use \\0 instead of \\n\n" + "\t-m, --modname Handle argument as module name instead of alias or filename\n" + "\t-F, --field=FIELD Print only provided FIELD\n" + "\t-k, --set-version=VERSION Use VERSION instead of `uname -r`\n" + "\t-b, --basedir=DIR Use DIR as filesystem root for " MODULE_DIRECTORY "\n" + "\t-V, --version Show version\n" + "\t-h, --help Show this help\n", + program_invocation_short_name); +} + +static bool is_module_filename(const char *name) +{ + struct stat st; + + if (stat(name, &st) == 0 && S_ISREG(st.st_mode) && + path_ends_with_kmod_ext(name, strlen(name))) + return true; + + return false; +} + +static int do_modinfo(int argc, char *argv[]) +{ + struct kmod_ctx *ctx; + char dirname_buf[PATH_MAX]; + const char *dirname = NULL; + const char *kversion = NULL; + const char *root = NULL; + const char *null_config = NULL; + bool arg_is_modname = false; + int i, err; + + for (;;) { + int c, idx = 0; + c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx); + if (c == -1) + break; + switch (c) { + case 'a': + field = "author"; + break; + case 'd': + field = "description"; + break; + case 'l': + field = "license"; + break; + case 'p': + field = "parm"; + break; + case 'n': + field = "filename"; + break; + case '0': + separator = '\0'; + break; + case 'm': + arg_is_modname = true; + break; + case 'F': + field = optarg; + break; + case 'k': + kversion = optarg; + break; + case 'b': + root = optarg; + break; + case 'h': + help(); + return EXIT_SUCCESS; + case 'V': + puts(PACKAGE " version " VERSION); + puts(KMOD_FEATURES); + return EXIT_SUCCESS; + case '?': + return EXIT_FAILURE; + default: + ERR("unexpected getopt_long() value '%c'.\n", c); + return EXIT_FAILURE; + } + } + + if (optind >= argc) { + ERR("missing module or filename.\n"); + return EXIT_FAILURE; + } + + if (root != NULL || kversion != NULL) { + struct utsname u; + if (root == NULL) + root = ""; + if (kversion == NULL) { + if (uname(&u) < 0) { + ERR("uname() failed: %m\n"); + return EXIT_FAILURE; + } + kversion = u.release; + } + snprintf(dirname_buf, sizeof(dirname_buf), "%s" MODULE_DIRECTORY "/%s", + root, kversion); + dirname = dirname_buf; + } + + ctx = kmod_new(dirname, &null_config); + if (!ctx) { + ERR("kmod_new() failed!\n"); + return EXIT_FAILURE; + } + + err = 0; + for (i = optind; i < argc; i++) { + const char *name = argv[i]; + int r; + + if (arg_is_modname) + r = modinfo_name_do(ctx, name); + else if (is_module_filename(name)) + r = modinfo_path_do(ctx, name); + else + r = modinfo_alias_do(ctx, name); + + if (r < 0) + err = r; + } + + kmod_unref(ctx); + return err >= 0 ? EXIT_SUCCESS : EXIT_FAILURE; +} + +const struct kmod_cmd kmod_cmd_compat_modinfo = { + .name = "modinfo", + .cmd = do_modinfo, + .help = "compat modinfo command", +}; diff --git a/tools/modprobe.c b/tools/modprobe.c new file mode 100644 index 0000000..5306bef --- /dev/null +++ b/tools/modprobe.c @@ -0,0 +1,1054 @@ +/* + * kmod-modprobe - manage linux kernel modules using libkmod. + * + * Copyright (C) 2011-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include "kmod.h" + +static int log_priority = LOG_CRIT; +static int use_syslog = 0; +#define LOG(...) log_printf(log_priority, __VA_ARGS__) + +#define DEFAULT_VERBOSE LOG_WARNING +static int verbose = DEFAULT_VERBOSE; +static int do_show = 0; +static int dry_run = 0; +static int ignore_loaded = 0; +static int lookup_only = 0; +static int first_time = 0; +static int ignore_commands = 0; +static int use_blacklist = 0; +static int force = 0; +static int strip_modversion = 0; +static int strip_vermagic = 0; +static int remove_holders = 0; +static unsigned long long wait_msec = 0; +static int quiet_inuse = 0; + +static const char cmdopts_s[] = "arw:RibfDcnC:d:S:sqvVh"; +static const struct option cmdopts[] = { + {"all", no_argument, 0, 'a'}, + + {"remove", no_argument, 0, 'r'}, + {"remove-dependencies", no_argument, 0, 5}, + {"remove-holders", no_argument, 0, 5}, + {"wait", required_argument, 0, 'w'}, + + {"resolve-alias", no_argument, 0, 'R'}, + {"first-time", no_argument, 0, 3}, + {"ignore-install", no_argument, 0, 'i'}, + {"ignore-remove", no_argument, 0, 'i'}, + {"use-blacklist", no_argument, 0, 'b'}, + {"force", no_argument, 0, 'f'}, + {"force-modversion", no_argument, 0, 2}, + {"force-vermagic", no_argument, 0, 1}, + + {"show-depends", no_argument, 0, 'D'}, + {"showconfig", no_argument, 0, 'c'}, + {"show-config", no_argument, 0, 'c'}, + {"show-modversions", no_argument, 0, 4}, + {"dump-modversions", no_argument, 0, 4}, + {"show-exports", no_argument, 0, 6}, + + {"dry-run", no_argument, 0, 'n'}, + {"show", no_argument, 0, 'n'}, + + {"config", required_argument, 0, 'C'}, + {"dirname", required_argument, 0, 'd'}, + {"set-version", required_argument, 0, 'S'}, + + {"syslog", no_argument, 0, 's'}, + {"quiet", no_argument, 0, 'q'}, + {"verbose", no_argument, 0, 'v'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {NULL, 0, 0, 0} +}; + +static void help(void) +{ + printf("Usage:\n" + "\t%s [options] [-i] [-b] modulename\n" + "\t%s [options] -a [-i] [-b] modulename [modulename...]\n" + "\t%s [options] -r [-i] modulename\n" + "\t%s [options] -r -a [-i] modulename [modulename...]\n" + "\t%s [options] -c\n" + "\t%s [options] --dump-modversions filename\n" + "Management Options:\n" + "\t-a, --all Consider every non-argument to\n" + "\t be a module name to be inserted\n" + "\t or removed (-r)\n" + "\t-r, --remove Remove modules instead of inserting\n" + "\t --remove-dependencies Deprecated: use --remove-holders\n" + "\t --remove-holders Also remove module holders (use together with -r)\n" + "\t-w, --wait When removing a module, wait up to MSEC for\n" + "\t module's refcount to become 0 so it can be\n" + "\t removed (use together with -r)\n" + "\t --first-time Fail if module already inserted or removed\n" + "\t-i, --ignore-install Ignore install commands\n" + "\t-i, --ignore-remove Ignore remove commands\n" + "\t-b, --use-blacklist Apply blacklist to resolved alias.\n" + "\t-f, --force Force module insertion or removal.\n" + "\t implies --force-modversions and\n" + "\t --force-vermagic\n" + "\t --force-modversion Ignore module's version\n" + "\t --force-vermagic Ignore module's version magic\n" + "\n" + "Query Options:\n" + "\t-R, --resolve-alias Only lookup and print alias and exit\n" + "\t-D, --show-depends Only print module dependencies and exit\n" + "\t-c, --showconfig Print out known configuration and exit\n" + "\t-c, --show-config Same as --showconfig\n" + "\t --show-modversions Dump module symbol version and exit\n" + "\t --dump-modversions Same as --show-modversions\n" + "\t --show-exports Only print module exported symbol versions and exit\n" + "\n" + "General Options:\n" + "\t-n, --dry-run Do not execute operations, just print out\n" + "\t-n, --show Same as --dry-run\n" + + "\t-C, --config=FILE Use FILE instead of default search paths\n" + "\t-d, --dirname=DIR Use DIR as filesystem root for " MODULE_DIRECTORY "\n" + "\t-S, --set-version=VERSION Use VERSION instead of `uname -r`\n" + + "\t-s, --syslog print to syslog, not stderr\n" + "\t-q, --quiet disable messages\n" + "\t-v, --verbose enables more messages\n" + "\t-V, --version show version\n" + "\t-h, --help show this help\n", + program_invocation_short_name, program_invocation_short_name, + program_invocation_short_name, program_invocation_short_name, + program_invocation_short_name, program_invocation_short_name); +} + +_printf_format_(1, 2) +static inline void _show(const char *fmt, ...) +{ + va_list args; + + if (!do_show && verbose <= DEFAULT_VERBOSE) + return; + + va_start(args, fmt); + vfprintf(stdout, fmt, args); + fflush(stdout); + va_end(args); +} +#define SHOW(...) _show(__VA_ARGS__) + +static int show_config(struct kmod_ctx *ctx) +{ + struct config_iterators { + const char *name; + struct kmod_config_iter *(*get_iter)(const struct kmod_ctx *ctx); + } ci[] = { + { "blacklist", kmod_config_get_blacklists }, + { "install", kmod_config_get_install_commands }, + { "remove", kmod_config_get_remove_commands }, + { "alias", kmod_config_get_aliases }, + { "options", kmod_config_get_options }, + { "softdep", kmod_config_get_softdeps }, + }; + size_t i; + + for (i = 0; i < ARRAY_SIZE(ci); i++) { + struct kmod_config_iter *iter = ci[i].get_iter(ctx); + + if (iter == NULL) + continue; + + while (kmod_config_iter_next(iter)) { + const char *val; + + printf("%s %s", ci[i].name, + kmod_config_iter_get_key(iter)); + val = kmod_config_iter_get_value(iter); + if (val != NULL) { + putchar(' '); + puts(val); + } else + putchar('\n'); + } + + kmod_config_iter_free_iter(iter); + } + + puts("\n# End of configuration files. Dumping indexes now:\n"); + fflush(stdout); + + kmod_dump_index(ctx, KMOD_INDEX_MODULES_ALIAS, STDOUT_FILENO); + kmod_dump_index(ctx, KMOD_INDEX_MODULES_SYMBOL, STDOUT_FILENO); + + return 0; +} + +static int show_modversions(struct kmod_ctx *ctx, const char *filename) +{ + struct kmod_list *l, *list = NULL; + struct kmod_module *mod; + int err = kmod_module_new_from_path(ctx, filename, &mod); + if (err < 0) { + LOG("Module %s not found.\n", filename); + return err; + } + + err = kmod_module_get_versions(mod, &list); + if (err < 0) { + LOG("could not get modversions of %s: %s\n", + filename, strerror(-err)); + kmod_module_unref(mod); + return err; + } + + kmod_list_foreach(l, list) { + const char *symbol = kmod_module_version_get_symbol(l); + uint64_t crc = kmod_module_version_get_crc(l); + printf("0x%08"PRIx64"\t%s\n", crc, symbol); + } + kmod_module_versions_free_list(list); + kmod_module_unref(mod); + return 0; +} + +static int show_exports(struct kmod_ctx *ctx, const char *filename) +{ + struct kmod_list *l, *list = NULL; + struct kmod_module *mod; + int err = kmod_module_new_from_path(ctx, filename, &mod); + if (err < 0) { + LOG("Module %s not found.\n", filename); + return err; + } + + err = kmod_module_get_symbols(mod, &list); + if (err < 0) { + LOG("could not get symbols of %s: %s\n", + filename, strerror(-err)); + kmod_module_unref(mod); + return err; + } + + kmod_list_foreach(l, list) { + const char *symbol = kmod_module_symbol_get_symbol(l); + uint64_t crc = kmod_module_symbol_get_crc(l); + printf("0x%08"PRIx64"\t%s\n", crc, symbol); + } + kmod_module_symbols_free_list(list); + kmod_module_unref(mod); + return 0; +} + +static int command_do(struct kmod_module *module, const char *type, + const char *command, const char *cmdline_opts) +{ + const char *modname = kmod_module_get_name(module); + char *p, *cmd = NULL; + size_t cmdlen, cmdline_opts_len, varlen; + int ret = 0; + + if (cmdline_opts == NULL) + cmdline_opts = ""; + cmdline_opts_len = strlen(cmdline_opts); + + cmd = strdup(command); + if (cmd == NULL) + return -ENOMEM; + cmdlen = strlen(cmd); + varlen = sizeof("$CMDLINE_OPTS") - 1; + while ((p = strstr(cmd, "$CMDLINE_OPTS")) != NULL) { + size_t prefixlen = p - cmd; + size_t suffixlen = cmdlen - prefixlen - varlen; + size_t slen = cmdlen - varlen + cmdline_opts_len; + char *suffix = p + varlen; + char *s = malloc(slen + 1); + if (s == NULL) { + free(cmd); + return -ENOMEM; + } + memcpy(s, cmd, p - cmd); + memcpy(s + prefixlen, cmdline_opts, cmdline_opts_len); + memcpy(s + prefixlen + cmdline_opts_len, suffix, suffixlen); + s[slen] = '\0'; + + free(cmd); + cmd = s; + cmdlen = slen; + } + + SHOW("%s %s\n", type, cmd); + if (dry_run) + goto end; + + setenv("MODPROBE_MODULE", modname, 1); + ret = system(cmd); + unsetenv("MODPROBE_MODULE"); + if (ret == -1 || WEXITSTATUS(ret)) { + LOG("Error running %s command for %s\n", type, modname); + if (ret != -1) + ret = -WEXITSTATUS(ret); + } + +end: + free(cmd); + return ret; +} + +static int rmmod_do_remove_module(struct kmod_module *mod) +{ + const char *modname = kmod_module_get_name(mod); + unsigned long long interval_msec = 0, t0_msec = 0, + tend_msec = 0; + int flags = 0, err; + + SHOW("rmmod %s\n", modname); + + if (dry_run) + return 0; + + if (force) + flags |= KMOD_REMOVE_FORCE; + + if (wait_msec) + flags |= KMOD_REMOVE_NOLOG; + + do { + err = kmod_module_remove_module(mod, flags); + if (err == -EEXIST) { + if (!first_time) + err = 0; + else + LOG("Module %s is not in kernel.\n", modname); + break; + } else if (err == -EAGAIN && wait_msec) { + unsigned long long until_msec; + + if (!t0_msec) { + t0_msec = now_msec(); + tend_msec = t0_msec + wait_msec; + interval_msec = 1; + } + + until_msec = get_backoff_delta_msec(t0_msec, tend_msec, + &interval_msec); + err = sleep_until_msec(until_msec); + + if (!t0_msec) + err = -ENOTSUP; + + if (err < 0) { + ERR("Failed to sleep: %s\n", strerror(-err)); + err = -EAGAIN; + break; + } + } else { + break; + } + } while (interval_msec); + + if (err < 0 && wait_msec) + ERR("could not remove '%s': %s\n", modname, strerror(-err)); + + return err; +} + +#define RMMOD_FLAG_REMOVE_HOLDERS 0x1 +#define RMMOD_FLAG_IGNORE_BUILTIN 0x2 +static int rmmod_do_module(struct kmod_module *mod, int flags); + +/* Remove modules in reverse order */ +static int rmmod_do_modlist(struct kmod_list *list, bool stop_on_errors) +{ + struct kmod_list *l; + + kmod_list_foreach_reverse(l, list) { + struct kmod_module *m = kmod_module_get_module(l); + int r = rmmod_do_module(m, RMMOD_FLAG_IGNORE_BUILTIN); + kmod_module_unref(m); + + if (r < 0 && stop_on_errors) + return r; + } + + return 0; +} + +static int rmmod_do_module(struct kmod_module *mod, int flags) +{ + const char *modname = kmod_module_get_name(mod); + struct kmod_list *pre = NULL, *post = NULL; + const char *cmd = NULL; + int err; + + if (!ignore_commands) { + err = kmod_module_get_softdeps(mod, &pre, &post); + if (err < 0) { + WRN("could not get softdeps of '%s': %s\n", + modname, strerror(-err)); + return err; + } + + cmd = kmod_module_get_remove_commands(mod); + } + + /* Quick check if module is loaded, otherwise there's nothing to do */ + if (!cmd && !ignore_loaded) { + int state = kmod_module_get_initstate(mod); + + if (state < 0) { + if (first_time) { + LOG("Module %s is not in kernel.\n", modname); + err = -ENOENT; + } else { + err = 0; + } + goto error; + } else if (state == KMOD_MODULE_BUILTIN) { + if (flags & RMMOD_FLAG_IGNORE_BUILTIN) { + err = 0; + } else { + LOG("Module %s is builtin.\n", modname); + err = -ENOENT; + } + goto error; + } + } + + /* 1. @mod's post-softdeps in reverse order */ + rmmod_do_modlist(post, false); + + /* 2. Other modules holding @mod */ + if (flags & RMMOD_FLAG_REMOVE_HOLDERS) { + struct kmod_list *holders = kmod_module_get_holders(mod); + + err = rmmod_do_modlist(holders, true); + kmod_module_unref_list(holders); + if (err < 0) + goto error; + } + + /* 3. @mod itself, but check for refcnt first */ + if (!cmd && !ignore_loaded && !wait_msec) { + int usage = kmod_module_get_refcnt(mod); + + if (usage > 0) { + if (!quiet_inuse) + LOG("Module %s is in use.\n", modname); + + err = -EBUSY; + goto error; + } + } + + if (!cmd) + err = rmmod_do_remove_module(mod); + else + err = command_do(mod, "remove", cmd, NULL); + + if (err < 0) + goto error; + + /* 4. Other modules that became unused: errors are non-fatal */ + if (!cmd) { + struct kmod_list *deps, *itr; + + deps = kmod_module_get_dependencies(mod); + kmod_list_foreach(itr, deps) { + struct kmod_module *dep = kmod_module_get_module(itr); + if (kmod_module_get_refcnt(dep) == 0) + rmmod_do_remove_module(dep); + kmod_module_unref(dep); + } + kmod_module_unref_list(deps); + } + + /* 5. @mod's pre-softdeps in reverse order: errors are non-fatal */ + rmmod_do_modlist(pre, false); + +error: + kmod_module_unref_list(pre); + kmod_module_unref_list(post); + + return err; +} + +static int rmmod(struct kmod_ctx *ctx, const char *alias) +{ + struct kmod_list *l, *list = NULL; + int err; + + err = kmod_module_new_from_lookup(ctx, alias, &list); + if (err < 0) + return err; + + if (list == NULL) { + LOG("Module %s not found.\n", alias); + err = -ENOENT; + } + + kmod_list_foreach(l, list) { + struct kmod_module *mod = kmod_module_get_module(l); + int flags = remove_holders ? RMMOD_FLAG_REMOVE_HOLDERS : 0; + + err = rmmod_do_module(mod, flags); + kmod_module_unref(mod); + if (err < 0) + break; + } + + kmod_module_unref_list(list); + return err; +} + +static int rmmod_all(struct kmod_ctx *ctx, char **args, int nargs) +{ + int i, err = 0; + + for (i = 0; i < nargs; i++) { + int r = rmmod(ctx, args[i]); + if (r < 0) + err = r; + } + + return err; +} + +static void print_action(struct kmod_module *m, bool install, + const char *options) +{ + const char *path; + + if (install) { + printf("install %s %s\n", kmod_module_get_install_commands(m), + options); + return; + } + + path = kmod_module_get_path(m); + + if (path == NULL) { + /* + * Either a builtin module, or an alias, print only for + * builtin + */ + if (kmod_module_get_initstate(m) == KMOD_MODULE_BUILTIN) + printf("builtin %s\n", kmod_module_get_name(m)); + } else + printf("insmod %s %s\n", kmod_module_get_path(m), options); +} + +static int insmod_insert(struct kmod_module *mod, int flags, + const char *extra_options) +{ + int err = 0; + void (*show)(struct kmod_module *m, bool install, + const char *options) = NULL; + + if (do_show || verbose > DEFAULT_VERBOSE) + show = &print_action; + + if (lookup_only) + printf("%s\n", kmod_module_get_name(mod)); + else + err = kmod_module_probe_insert_module(mod, flags, + extra_options, NULL, NULL, show); + + if (err >= 0) + /* ignore flag return values such as a mod being blacklisted */ + err = 0; + else { + switch (err) { + case -EEXIST: + ERR("could not insert '%s': Module already in kernel\n", + kmod_module_get_name(mod)); + break; + case -ENOENT: + ERR("could not insert '%s': Unknown symbol in module, " + "or unknown parameter (see dmesg)\n", + kmod_module_get_name(mod)); + break; + default: + ERR("could not insert '%s': %s\n", + kmod_module_get_name(mod), + strerror(-err)); + break; + } + } + + return err; +} + +static int insmod(struct kmod_ctx *ctx, const char *alias, + const char *extra_options) +{ + struct kmod_list *l, *list = NULL; + struct kmod_module *mod = NULL; + int err, flags = 0; + + if (strncmp(alias, "/", 1) == 0 || strncmp(alias, "./", 2) == 0) { + err = kmod_module_new_from_path(ctx, alias, &mod); + if (err < 0) { + LOG("Failed to get module from path %s: %s\n", alias, + strerror(-err)); + return -ENOENT; + } + } else { + err = kmod_module_new_from_lookup(ctx, alias, &list); + if (list == NULL || err < 0) { + LOG("Module %s not found in directory %s\n", alias, + ctx ? kmod_get_dirname(ctx) : "(missing)"); + return -ENOENT; + } + } + + if (strip_modversion || force) + flags |= KMOD_PROBE_FORCE_MODVERSION; + if (strip_vermagic || force) + flags |= KMOD_PROBE_FORCE_VERMAGIC; + if (ignore_commands) + flags |= KMOD_PROBE_IGNORE_COMMAND; + if (ignore_loaded) + flags |= KMOD_PROBE_IGNORE_LOADED; + if (dry_run) + flags |= KMOD_PROBE_DRY_RUN; + + flags |= KMOD_PROBE_APPLY_BLACKLIST_ALIAS_ONLY; + + if (use_blacklist) + flags |= KMOD_PROBE_APPLY_BLACKLIST; + if (first_time) + flags |= KMOD_PROBE_FAIL_ON_LOADED; + + /* If module is loaded from path */ + if (mod != NULL) { + err = insmod_insert(mod, flags, extra_options); + kmod_module_unref(mod); + } else { + kmod_list_foreach(l, list) { + mod = kmod_module_get_module(l); + err = insmod_insert(mod, flags, extra_options); + kmod_module_unref(mod); + } + kmod_module_unref_list(list); + } + return err; +} + +static int insmod_all(struct kmod_ctx *ctx, char **args, int nargs) +{ + int i, err = 0; + + for (i = 0; i < nargs; i++) { + int r = insmod(ctx, args[i], NULL); + if (r < 0) + err = r; + } + + return err; +} + +static void env_modprobe_options_append(const char *value) +{ + const char *old = getenv("MODPROBE_OPTIONS"); + char *env; + + if (old == NULL) { + setenv("MODPROBE_OPTIONS", value, 1); + return; + } + + if (asprintf(&env, "%s %s", old, value) < 0) { + ERR("could not append value to $MODPROBE_OPTIONS\n"); + return; + } + + if (setenv("MODPROBE_OPTIONS", env, 1) < 0) + ERR("could not setenv(MODPROBE_OPTIONS, \"%s\")\n", env); + free(env); +} + +static int options_from_array(char **args, int nargs, char **output) +{ + char *opts = NULL; + size_t optslen = 0; + int i, err = 0; + + for (i = 1; i < nargs; i++) { + size_t len = strlen(args[i]); + size_t qlen = 0; + const char *value; + void *tmp; + + value = strchr(args[i], '='); + if (value) { + value++; + if (*value != '"' && *value != '\'') { + if (strchr(value, ' ')) + qlen = 2; + } + } + + tmp = realloc(opts, optslen + len + qlen + 2); + if (!tmp) { + err = -errno; + free(opts); + opts = NULL; + ERR("could not gather module options: out-of-memory\n"); + break; + } + opts = tmp; + if (optslen > 0) { + opts[optslen] = ' '; + optslen++; + } + if (qlen == 0) { + memcpy(opts + optslen, args[i], len + 1); + optslen += len; + } else { + size_t keylen = value - args[i]; + size_t valuelen = len - keylen; + memcpy(opts + optslen, args[i], keylen); + optslen += keylen; + opts[optslen] = '"'; + optslen++; + memcpy(opts + optslen, value, valuelen); + optslen += valuelen; + opts[optslen] = '"'; + optslen++; + opts[optslen] = '\0'; + } + } + + *output = opts; + return err; +} + +static char **prepend_options_from_env(int *p_argc, char **orig_argv) +{ + const char *p, *env = getenv("MODPROBE_OPTIONS"); + char **new_argv, *str_end, *str, *s, *quote; + int i, argc = *p_argc; + size_t envlen, space_count = 0; + + if (env == NULL) + return orig_argv; + + for (p = env; *p != '\0'; p++) { + if (*p == ' ') + space_count++; + } + + envlen = p - env; + new_argv = malloc(sizeof(char *) * (argc + space_count + 3 + envlen)); + if (new_argv == NULL) + return NULL; + + new_argv[0] = orig_argv[0]; + str = (char *) (new_argv + argc + space_count + 3); + memcpy(str, env, envlen + 1); + + str_end = str + envlen; + + quote = NULL; + for (i = 1, s = str; *s != '\0'; s++) { + if (quote == NULL) { + if (*s == ' ') { + new_argv[i] = str; + i++; + *s = '\0'; + str = s + 1; + } else if (*s == '"' || *s == '\'') + quote = s; + } else { + if (*s == *quote) { + if (quote == str) { + new_argv[i] = str + 1; + i++; + *s = '\0'; + str = s + 1; + } else { + char *it; + for (it = quote; it < s - 1; it++) + it[0] = it[1]; + for (it = s - 1; it < str_end - 2; it++) + it[0] = it[2]; + str_end -= 2; + *str_end = '\0'; + s -= 2; + } + quote = NULL; + } + } + } + if (str < s) { + new_argv[i] = str; + i++; + } + + memcpy(new_argv + i, orig_argv + 1, sizeof(char *) * (argc - 1)); + new_argv[i + argc - 1] = NULL; + *p_argc = i + argc - 1; + + return new_argv; +} + +static int do_modprobe(int argc, char **orig_argv) +{ + struct kmod_ctx *ctx; + char **args = NULL, **argv; + const char **config_paths = NULL; + int nargs = 0, n_config_paths = 0; + char dirname_buf[PATH_MAX]; + const char *dirname = NULL; + const char *root = NULL; + const char *kversion = NULL; + int use_all = 0; + int do_remove = 0; + int do_show_config = 0; + int do_show_modversions = 0; + int do_show_exports = 0; + int err; + struct stat stat_buf; + + argv = prepend_options_from_env(&argc, orig_argv); + if (argv == NULL) { + ERR("Could not prepend options from command line\n"); + return EXIT_FAILURE; + } + + for (;;) { + int c, idx = 0; + c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx); + if (c == -1) + break; + switch (c) { + case 'a': + log_priority = LOG_WARNING; + use_all = 1; + break; + case 'r': + do_remove = 1; + break; + case 5: + remove_holders = 1; + break; + case 'w': { + char *endptr = NULL; + wait_msec = strtoul(optarg, &endptr, 0); + if (!*optarg || *endptr) { + ERR("unexpected wait value '%s'.\n", optarg); + err = -1; + goto done; + } + break; + } + case 3: + first_time = 1; + break; + case 'i': + ignore_commands = 1; + break; + case 'b': + use_blacklist = 1; + break; + case 'f': + force = 1; + break; + case 2: + strip_modversion = 1; + break; + case 1: + strip_vermagic = 1; + break; + case 'D': + ignore_loaded = 1; + dry_run = 1; + do_show = 1; + break; + case 'R': + lookup_only = 1; + break; + case 'c': + do_show_config = 1; + break; + case 4: + do_show_modversions = 1; + break; + case 6: + do_show_exports = 1; + break; + case 'n': + dry_run = 1; + break; + case 'C': { + size_t bytes = sizeof(char *) * (n_config_paths + 2); + void *tmp = realloc(config_paths, bytes); + if (!tmp) { + ERR("out-of-memory\n"); + err = -1; + goto done; + } + config_paths = tmp; + config_paths[n_config_paths] = optarg; + n_config_paths++; + config_paths[n_config_paths] = NULL; + + env_modprobe_options_append("-C"); + env_modprobe_options_append(optarg); + break; + } + case 'd': + root = optarg; + break; + case 'S': + kversion = optarg; + break; + case 's': + env_modprobe_options_append("-s"); + use_syslog = 1; + break; + case 'q': + env_modprobe_options_append("-q"); + verbose = LOG_EMERG; + break; + case 'v': + env_modprobe_options_append("-v"); + verbose++; + break; + case 'V': + puts(PACKAGE " version " VERSION); + puts(KMOD_FEATURES); + err = 0; + goto done; + case 'h': + help(); + err = 0; + goto done; + case '?': + err = -1; + goto done; + default: + ERR("unexpected getopt_long() value '%c'.\n", c); + err = -1; + goto done; + } + } + + args = argv + optind; + nargs = argc - optind; + + if (!use_syslog && + (!stderr || + fileno(stderr) == -1 || + fstat(fileno(stderr), &stat_buf))) + use_syslog = 1; + + log_open(use_syslog); + + if (!do_show_config) { + if (nargs == 0) { + ERR("missing parameters. See -h.\n"); + err = -1; + goto done; + } + } + + if (root != NULL || kversion != NULL) { + struct utsname u; + if (root == NULL) + root = ""; + if (kversion == NULL) { + if (uname(&u) < 0) { + ERR("uname() failed: %m\n"); + err = -1; + goto done; + } + kversion = u.release; + } + snprintf(dirname_buf, sizeof(dirname_buf), + "%s" MODULE_DIRECTORY "/%s", root, + kversion); + dirname = dirname_buf; + } + + ctx = kmod_new(dirname, config_paths); + if (!ctx) { + ERR("kmod_new() failed!\n"); + err = -1; + goto done; + } + + log_setup_kmod_log(ctx, verbose); + + kmod_load_resources(ctx); + + if (do_show_config) + err = show_config(ctx); + else if (do_show_modversions) + err = show_modversions(ctx, args[0]); + else if (do_show_exports) + err = show_exports(ctx, args[0]); + else if (do_remove) + err = rmmod_all(ctx, args, nargs); + else if (use_all) + err = insmod_all(ctx, args, nargs); + else { + char *opts; + err = options_from_array(args, nargs, &opts); + if (err == 0) { + err = insmod(ctx, args[0], opts); + free(opts); + } + } + + kmod_unref(ctx); + +done: + log_close(); + + if (argv != orig_argv) + free(argv); + + free(config_paths); + + return err >= 0 ? EXIT_SUCCESS : EXIT_FAILURE; +} + +const struct kmod_cmd kmod_cmd_compat_modprobe = { + .name = "modprobe", + .cmd = do_modprobe, + .help = "compat modprobe command", +}; diff --git a/tools/remove.c b/tools/remove.c new file mode 100644 index 0000000..387ef0e --- /dev/null +++ b/tools/remove.c @@ -0,0 +1,153 @@ +/* + * kmod-remove - remove modules from the kernel. + * + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * Copyright (C) 2011-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include + +#include + +#include "kmod.h" + +static const char cmdopts_s[] = "h"; +static const struct option cmdopts[] = { + {"help", no_argument, 0, 'h'}, + { } +}; + +static void help(void) +{ + printf("Usage:\n" + "\t%s remove [options] module\n" + "Options:\n" + "\t-h, --help show this help\n", + program_invocation_short_name); +} + +static int check_module_inuse(struct kmod_module *mod) { + struct kmod_list *holders; + int state, ret; + + state = kmod_module_get_initstate(mod); + + if (state == KMOD_MODULE_BUILTIN) { + ERR("Module %s is builtin.\n", kmod_module_get_name(mod)); + return -ENOENT; + } else if (state < 0) { + ERR("Module %s is not currently loaded\n", + kmod_module_get_name(mod)); + return -ENOENT; + } + + holders = kmod_module_get_holders(mod); + if (holders != NULL) { + struct kmod_list *itr; + + ERR("Module %s is in use by:", kmod_module_get_name(mod)); + + kmod_list_foreach(itr, holders) { + struct kmod_module *hm = kmod_module_get_module(itr); + fprintf(stderr, " %s", kmod_module_get_name(hm)); + kmod_module_unref(hm); + } + fputc('\n', stderr); + + kmod_module_unref_list(holders); + return -EBUSY; + } + + ret = kmod_module_get_refcnt(mod); + if (ret > 0) { + ERR("Module %s is in use\n", kmod_module_get_name(mod)); + return -EBUSY; + } else if (ret == -ENOENT) { + ERR("Module unloading is not supported\n"); + } + + return ret; +} + +static int do_remove(int argc, char *argv[]) +{ + struct kmod_ctx *ctx; + struct kmod_module *mod; + const char *name; + int err, r = EXIT_SUCCESS; + + for (;;) { + int c, idx =0; + c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx); + if (c == -1) + break; + switch (c) { + case 'h': + help(); + return EXIT_SUCCESS; + + default: + ERR("Unexpected getopt_long() value '%c'.\n", c); + return EXIT_FAILURE; + } + } + + if (optind >= argc) { + ERR("Missing module name\n"); + return EXIT_FAILURE; + } + + ctx = kmod_new(NULL, NULL); + if (!ctx) { + ERR("kmod_new() failed!\n"); + return EXIT_FAILURE; + } + + name = argv[optind]; + err = kmod_module_new_from_name(ctx, name, &mod); + if (err < 0) { + ERR("Could not remove module %s: %s\n", name, strerror(-err)); + goto end; + } + + err = check_module_inuse(mod); + if (err < 0) + goto unref; + + err = kmod_module_remove_module(mod, 0); + if (err < 0) + goto unref; + +unref: + kmod_module_unref(mod); + +end: + kmod_unref(ctx); + if (err < 0) { + r = EXIT_FAILURE; + ERR("Could not remove module %s: %s\n", name, strerror(-err)); + } + return r; +} + +const struct kmod_cmd kmod_cmd_remove = { + .name = "remove", + .cmd = do_remove, + .help = "remove module from kernel", +}; diff --git a/tools/rmmod.c b/tools/rmmod.c new file mode 100644 index 0000000..3942e7b --- /dev/null +++ b/tools/rmmod.c @@ -0,0 +1,203 @@ +/* + * kmod-rmmod - remove modules from linux kernel using libkmod. + * + * Copyright (C) 2011-2013 ProFUSION embedded systems + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include "kmod.h" + +#define DEFAULT_VERBOSE LOG_ERR +static int verbose = DEFAULT_VERBOSE; +static int use_syslog; + +static const char cmdopts_s[] = "fsvVwh"; +static const struct option cmdopts[] = { + {"force", no_argument, 0, 'f'}, + {"syslog", no_argument, 0, 's'}, + {"verbose", no_argument, 0, 'v'}, + {"version", no_argument, 0, 'V'}, + {"help", no_argument, 0, 'h'}, + {NULL, 0, 0, 0} +}; + +static void help(void) +{ + printf("Usage:\n" + "\t%s [options] modulename ...\n" + "Options:\n" + "\t-f, --force forces a module unload and may crash your\n" + "\t machine. This requires Forced Module Removal\n" + "\t option in your kernel. DANGEROUS\n" + "\t-s, --syslog print to syslog, not stderr\n" + "\t-v, --verbose enables more messages\n" + "\t-V, --version show version\n" + "\t-h, --help show this help\n", + program_invocation_short_name); +} + +static int check_module_inuse(struct kmod_module *mod) { + struct kmod_list *holders; + int state, ret; + + state = kmod_module_get_initstate(mod); + + if (state == KMOD_MODULE_BUILTIN) { + ERR("Module %s is builtin.\n", kmod_module_get_name(mod)); + return -ENOENT; + } else if (state < 0) { + ERR("Module %s is not currently loaded\n", + kmod_module_get_name(mod)); + return -ENOENT; + } + + holders = kmod_module_get_holders(mod); + if (holders != NULL) { + struct kmod_list *itr; + + ERR("Module %s is in use by:", kmod_module_get_name(mod)); + + kmod_list_foreach(itr, holders) { + struct kmod_module *hm = kmod_module_get_module(itr); + fprintf(stderr, " %s", kmod_module_get_name(hm)); + kmod_module_unref(hm); + } + fputc('\n', stderr); + + kmod_module_unref_list(holders); + return -EBUSY; + } + + ret = kmod_module_get_refcnt(mod); + if (ret > 0) { + ERR("Module %s is in use\n", kmod_module_get_name(mod)); + return -EBUSY; + } else if (ret == -ENOENT) { + ERR("Module unloading is not supported\n"); + } + + return ret; +} + +static int do_rmmod(int argc, char *argv[]) +{ + struct kmod_ctx *ctx; + const char *null_config = NULL; + int flags = 0; + int i, err, r = 0; + + for (;;) { + int c, idx = 0; + c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx); + if (c == -1) + break; + switch (c) { + case 'f': + flags |= KMOD_REMOVE_FORCE; + break; + case 's': + use_syslog = 1; + break; + case 'v': + verbose++; + break; + case 'h': + help(); + return EXIT_SUCCESS; + case 'V': + puts(PACKAGE " version " VERSION); + puts(KMOD_FEATURES); + return EXIT_SUCCESS; + case '?': + return EXIT_FAILURE; + default: + ERR("unexpected getopt_long() value '%c'.\n", c); + return EXIT_FAILURE; + } + } + + log_open(use_syslog); + + if (optind >= argc) { + ERR("missing module name.\n"); + r = EXIT_FAILURE; + goto done; + } + + ctx = kmod_new(NULL, &null_config); + if (!ctx) { + ERR("kmod_new() failed!\n"); + r = EXIT_FAILURE; + goto done; + } + + log_setup_kmod_log(ctx, verbose); + + for (i = optind; i < argc; i++) { + struct kmod_module *mod; + const char *arg = argv[i]; + struct stat st; + if (stat(arg, &st) == 0) + err = kmod_module_new_from_path(ctx, arg, &mod); + else + err = kmod_module_new_from_name(ctx, arg, &mod); + + if (err < 0) { + ERR("could not use module %s: %s\n", arg, + strerror(-err)); + break; + } + + if (!(flags & KMOD_REMOVE_FORCE) && check_module_inuse(mod) < 0) { + r++; + goto next; + } + + err = kmod_module_remove_module(mod, flags); + if (err < 0) { + ERR("could not remove module %s: %s\n", arg, + strerror(-err)); + r++; + } +next: + kmod_module_unref(mod); + } + + kmod_unref(ctx); + +done: + log_close(); + + return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE; +} + +const struct kmod_cmd kmod_cmd_compat_rmmod = { + .name = "rmmod", + .cmd = do_rmmod, + .help = "compat rmmod command", +}; diff --git a/tools/static-nodes.c b/tools/static-nodes.c new file mode 100644 index 0000000..5ef3743 --- /dev/null +++ b/tools/static-nodes.c @@ -0,0 +1,277 @@ +/* + * kmod-static-nodes - manage modules.devname + * + * Copyright (C) 2004-2012 Kay Sievers + * Copyright (C) 2011-2013 ProFUSION embedded systems + * Copyright (C) 2013 Tom Gundersen + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "kmod.h" + +struct static_nodes_format { + const char *name; + int (*write)(FILE *, char[], char[], char, unsigned int, unsigned int); + const char *description; +}; + +static const struct static_nodes_format static_nodes_format_human; +static const struct static_nodes_format static_nodes_format_tmpfiles; +static const struct static_nodes_format static_nodes_format_devname; + +static const struct static_nodes_format *static_nodes_formats[] = { + &static_nodes_format_human, + &static_nodes_format_tmpfiles, + &static_nodes_format_devname, +}; + +static const char cmdopts_s[] = "o:f:h"; +static const struct option cmdopts[] = { + { "output", required_argument, 0, 'o'}, + { "format", required_argument, 0, 'f'}, + { "help", no_argument, 0, 'h'}, + { }, +}; + +static int write_human(FILE *out, char modname[], char devname[], char type, unsigned int maj, unsigned int min) +{ + int ret; + + ret = fprintf(out, + "Module: %s\n" + "\tDevice node: /dev/%s\n" + "\t\tType: %s device\n" + "\t\tMajor: %u\n" + "\t\tMinor: %u\n", + modname, devname, + (type == 'c') ? "character" : "block", maj, min); + if (ret >= 0) + return EXIT_SUCCESS; + else + return EXIT_FAILURE; +} + +static const struct static_nodes_format static_nodes_format_human = { + .name = "human", + .write = write_human, + .description = "(default) a human readable format. Do not parse.", +}; + +static int write_tmpfiles(FILE *out, char modname[], char devname[], char type, unsigned int maj, unsigned int min) +{ + const char *dir; + int ret; + + dir = strrchr(devname, '/'); + if (dir) { + ret = fprintf(out, "d /dev/%.*s 0755 - - -\n", + (int)(dir - devname), devname); + if (ret < 0) + return EXIT_FAILURE; + } + + ret = fprintf(out, "%c! /dev/%s 0600 - - - %u:%u\n", + type, devname, maj, min); + if (ret < 0) + return EXIT_FAILURE; + + return EXIT_SUCCESS; +} + +static const struct static_nodes_format static_nodes_format_tmpfiles = { + .name = "tmpfiles", + .write = write_tmpfiles, + .description = "the tmpfiles.d(5) format used by systemd-tmpfiles.", +}; + +static int write_devname(FILE *out, char modname[], char devname[], char type, unsigned int maj, unsigned int min) +{ + int ret; + + ret = fprintf(out, "%s %s %c%u:%u\n", modname, devname, type, maj, min); + if (ret >= 0) + return EXIT_SUCCESS; + else + return EXIT_FAILURE; +} + +static const struct static_nodes_format static_nodes_format_devname = { + .name = "devname", + .write = write_devname, + .description = "the modules.devname format.", +}; + +static void help(void) +{ + size_t i; + + printf("Usage:\n" + "\t%s static-nodes [options]\n" + "\n" + "kmod static-nodes outputs the static-node information of the currently running kernel.\n" + "\n" + "Options:\n" + "\t-f, --format=FORMAT choose format to use: see \"Formats\"\n" + "\t-o, --output=FILE write output to file\n" + "\t-h, --help show this help\n" + "\n" + "Formats:\n", + program_invocation_short_name); + + for (i = 0; i < ARRAY_SIZE(static_nodes_formats); i++) { + if (static_nodes_formats[i]->description != NULL) { + printf("\t%-12s %s\n", static_nodes_formats[i]->name, + static_nodes_formats[i]->description); + } + } +} + +static int do_static_nodes(int argc, char *argv[]) +{ + struct utsname kernel; + char modules[PATH_MAX], buf[4096]; + const char *output = "/dev/stdout"; + FILE *in = NULL, *out = NULL; + const struct static_nodes_format *format = &static_nodes_format_human; + int r, ret = EXIT_SUCCESS; + + for (;;) { + int c, idx = 0, valid; + size_t i; + + c = getopt_long(argc, argv, cmdopts_s, cmdopts, &idx); + if (c == -1) { + break; + } + switch (c) { + case 'o': + output = optarg; + break; + case 'f': + valid = 0; + + for (i = 0; i < ARRAY_SIZE(static_nodes_formats); i++) { + if (streq(static_nodes_formats[i]->name, optarg)) { + format = static_nodes_formats[i]; + valid = 1; + } + } + + if (!valid) { + fprintf(stderr, "Unknown format: '%s'.\n", + optarg); + help(); + ret = EXIT_FAILURE; + goto finish; + } + break; + case 'h': + help(); + goto finish; + case '?': + ret = EXIT_FAILURE; + goto finish; + default: + fprintf(stderr, "Unexpected commandline option '%c'.\n", + c); + help(); + ret = EXIT_FAILURE; + goto finish; + } + } + + if (uname(&kernel) < 0) { + fputs("Error: uname failed!\n", stderr); + ret = EXIT_FAILURE; + goto finish; + } + + snprintf(modules, sizeof(modules), MODULE_DIRECTORY "/%s/modules.devname", kernel.release); + in = fopen(modules, "re"); + if (in == NULL) { + if (errno == ENOENT) { + fprintf(stderr, "Warning: " MODULE_DIRECTORY "/%s/modules.devname not found - ignoring\n", + kernel.release); + ret = EXIT_SUCCESS; + } else { + fprintf(stderr, "Error: could not open " MODULE_DIRECTORY "/%s/modules.devname - %m\n", + kernel.release); + ret = EXIT_FAILURE; + } + goto finish; + } + + r = mkdir_parents(output, 0755); + if (r < 0) { + fprintf(stderr, "Error: could not create parent directory for %s - %m.\n", output); + ret = EXIT_FAILURE; + goto finish; + } + + out = fopen(output, "we"); + if (out == NULL) { + fprintf(stderr, "Error: could not create %s - %m\n", output); + ret = EXIT_FAILURE; + goto finish; + } + + while (fgets(buf, sizeof(buf), in) != NULL) { + char modname[PATH_MAX]; + char devname[PATH_MAX]; + char type; + unsigned int maj, min; + int matches; + + if (buf[0] == '#') + continue; + + matches = sscanf(buf, "%s %s %c%u:%u", modname, devname, + &type, &maj, &min); + if (matches != 5 || (type != 'c' && type != 'b')) { + fprintf(stderr, "Error: invalid devname entry: %s", buf); + ret = EXIT_FAILURE; + continue; + } + + format->write(out, modname, devname, type, maj, min); + } + +finish: + if (in) + fclose(in); + if (out) + fclose(out); + return ret; +} + +const struct kmod_cmd kmod_cmd_static_nodes = { + .name = "static-nodes", + .cmd = do_static_nodes, + .help = "outputs the static-node information installed with the currently running kernel", +}; -- cgit v1.2.3