-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlsuhwi.c
134 lines (105 loc) · 3.28 KB
/
lsuhwi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <stdio.h>
#include <stdlib.h>
#include "uhwi.h"
int show_usage(const char* argv0) {
fprintf(stderr, "Usage: %s [-u|-l|-?]\n", argv0);
return 1;
}
#define UHWI_DEV_TYPE_TO_CSTR(type) \
((type == UHWI_DEV_USB) ? "USB" : "PCI")
void format_as_json(uhwi_dev* current, FILE* where) {
if (!current || current->type == UHWI_DEV_NULL)
return; // impossible though
fprintf(where, "{");
fprintf(where, "\"type\":\"%s\",\"vendor\":%u,\"device\":%u,",
UHWI_DEV_TYPE_TO_CSTR(current->type),
current->vendor, current->device);
fprintf(where, "\"subvendor\":%u,\"subdevice\":%u,",
current->subvendor, current->subdevice);
fprintf(where, "\"name\":\"");
size_t index = 0;
while (1) {
const char cc = current->name[index];
if (cc == '\0')
break;
switch (cc) {
case '"':
case '\\': {
fputc('\\', where);
break;
}
default:
break;
}
fputc(cc, where);
index++;
}
fprintf(where, "\"}");
if (current->next)
fputc(',', where);
}
#ifdef UHWI_ENABLE_PCI_DB
uhwi_dev* uhwi_db_init(void);
#else
uhwi_dev* uhwi_db_init(void) {
return NULL;
}
#endif
int main(const int argc, const char** argv) {
uhwi_dev_t type = UHWI_DEV_NULL;
size_t as_json = 0;
size_t dump_pci_db = 0;
for (size_t index = 1; index < (size_t)argc; index++) {
if (argv[index][0] == '-' && argv[index][1] != '\0') {
switch (argv[index][1]) {
case 'u': {
type = UHWI_DEV_USB;
break;
}
case 'l': {
type = UHWI_DEV_PCI;
break;
}
case 'd': {
dump_pci_db = 1;
break;
}
case 'J': {
as_json = 1;
break;
}
default:
return show_usage(argv[0]);
}
}
}
uhwi_dev* first = dump_pci_db ? uhwi_db_init() : uhwi_get_devs(type);
if (!first && uhwi_get_errno() != UHWI_ERRNO_OK) {
fprintf(stderr, "failed to obtain UHWI device info (or no devices of this type are connected to the system)!!\n");
return 1;
}
if (as_json)
fputc('[', stdout);
while (first) {
uhwi_dev* next = first->next;
if (as_json)
format_as_json(first, stdout);
else {
if (type == UHWI_DEV_NULL)
fprintf(stdout, "[%s] ", UHWI_DEV_TYPE_TO_CSTR(first->type));
fprintf(stdout, "vendor=0x%04x, device=0x%04x", first->vendor,
first->device);
if (first->type == UHWI_DEV_PCI)
fprintf(stdout, ", subvendor=0x%04x, subdevice=0x%04x",
first->subvendor, first->subdevice);
if (first->name[0] != '\0')
fprintf(stdout, ", name: %s", first->name);
fprintf(stdout, "%c", '\n');
}
free(first);
first = next;
}
if (as_json)
fputc(']', stdout);
return 0;
}