#include #include #include #include #include #include #include #include #include bool new_kld_is_loaded_method(const char *kmod) { /* * A driver was either loaded as a module, or built in to the kernel * already. */ return (modfind(kmod) != -1); } bool old_kld_is_loaded_method(const char *kmod) { struct kld_file_stat fstat = { .version = sizeof(fstat) }; struct module_stat mstat = { .version = sizeof(mstat) }; size_t len = strlen(kmod); int fid, mid; /* Need to see if a file with the name, `kmod`, is loaded. */ for (fid = kldnext(0); fid > 0; fid = kldnext(fid)) { if (kldstat(fid, &fstat) != 0) continue; if (strcmp(fstat.name, kmod) == 0) { fprintf(stderr, "fstat.name matched\n"); return true; } if (strncmp(fstat.name, kmod, len) == 0 && strcmp(fstat.name + len, ".ko") == 0) return true; for (mid = kldfirstmod(fid); mid > 0; mid = modfnext(mid)) { if (modstat(mid, &mstat) != 0) continue; fprintf(stderr, "mstat.name: %s\n", mstat.name); if (strcmp(mstat.name, kmod) == 0) return true; } } return false; } void usage(void) __dead2; void usage(void) { fprintf(stderr, "usage: mod_loaded \n"); exit(1); } int main(int argc, char **argv) { if (argc != 2) usage(); const char *kmod = argv[1]; printf("Is `%s` loaded?\n", kmod); printf("Old method: %s\n", old_kld_is_loaded_method(kmod) ? "yes" : "no"); printf("New method: %s\n", new_kld_is_loaded_method(kmod) ? "yes" : "no"); return 0; }