forked from martinpitt/umockdev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathumockdev.vala
2134 lines (1893 loc) · 79.3 KB
/
umockdev.vala
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2012-2013 Canonical Ltd.
* Author: Martin Pitt <[email protected]>
*
* umockdev is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* umockdev 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; If not, see <http://www.gnu.org/licenses/>.
*/
namespace UMockdev {
using UMockdevUtils;
#if HAVE_SELINUX
using Selinux;
#endif
private bool __in_mock_env_initialized = false;
private bool __in_mock_env_result = false;
static void checked_mkdir (string path, int mode)
{
if (DirUtils.create(path, mode) < 0)
error("cannot create directory %s: %m", path);
}
static void checked_mkdir_with_parents (string path, int mode)
{
if (DirUtils.create_with_parents(path, mode) < 0)
error("cannot create directory with parents %s: %m", path);
}
/**
* SECTION:umockdev
* @title: umockdev
* @short_description: Build a test bed for testing software that handles Linux
* hardware devices.
*
* Please see README.md about an overview of the parts of umockdev, and how
* they fit together.
*/
/**
* UMockdevTestbed:
*
* The #UMockdevTestbed class builds a temporary sandbox for mock devices.
* You can add a number of devices including arbitrary sysfs attributes and
* udev properties, and then run your software in that test bed that is
* independent of the actual hardware it is running on. With this you can
* simulate particular hardware in virtual environments up to some degree,
* without needing any particular privileges or disturbing the whole system.
*
* You can either add devices by specifying individual device paths,
* properties, and attributes, or use the umockdev-record tool to create a human
* readable/editable record of a real device (and all its parents) and load
* that into the testbed with umockdev_testbed_add_from_string().
*
* Instantiating a #UMockdevTestbed object creates a temporary directory with
* an empty sysfs tree and sets the $UMOCKDEV_DIR environment variable so that
* programs subsequently started under umockdev-wrapper will use the test bed
* instead of the system's real sysfs.
*/
/* This avoids taking a reference on the Testbed */
private static Thread<void>
create_worker_thread(MainLoop loop)
{
return new Thread<void> ("umockdev-testbed-worker", () => {
MainContext ctx = loop.get_context();
ctx.push_thread_default();
loop.run();
ctx.pop_thread_default();
});
}
public class Testbed: GLib.Object {
/**
* umockdev_testbed_new:
*
* Create a new #UMockdevTestbed object. This is initially empty, call
* methods like #umockdev_testbed_add_device or
* #umockdev_testbed_add_from_string to fill it.
*
* Returns: The newly created #UMockdevTestbed object.
*/
public Testbed()
{
try {
this.root_dir = DirUtils.make_tmp("umockdev.XXXXXX");
} catch (FileError e) {
error("Cannot create temporary directory: %s", e.message);
}
this.sys_dir = Path.build_filename(this.root_dir, "sys");
checked_mkdir(this.sys_dir, 0755);
/* Create "bus" and "class" directories to make libudev happy */
string bus_path = Path.build_filename(this.sys_dir, "bus");
checked_mkdir(bus_path, 0755);
string class_path = Path.build_filename(this.sys_dir, "class");
checked_mkdir(class_path, 0755);
this.dev_fd = new HashTable<string, int> (str_hash, str_equal);
this.dev_script_runner = new HashTable<string, ScriptRunner> (str_hash, str_equal);
this.custom_handlers = new HashTable<string, IoctlBase> (str_hash, str_equal);
checked_setenv ("UMOCKDEV_DIR", this.root_dir);
this.worker_ctx = new MainContext();
this.worker_loop = new MainLoop(this.worker_ctx);
this.worker_thread = create_worker_thread(this.worker_loop);
/* Create fallback ioctl handler */
IoctlBase handler = new IoctlBase();
string sockpath = Path.build_filename(this.root_dir, "ioctl", "_default");
handler.register_path(this.worker_ctx, "_default", sockpath);
debug("Created udev test bed %s", this.root_dir);
}
~Testbed()
{
// merely calling remove_all() does not invoke ScriptRunner dtor, so stop manually
foreach (unowned ScriptRunner r in this.dev_script_runner.get_values())
r.stop ();
this.dev_script_runner.remove_all();
this.custom_handlers.foreach((key, val) => {
val.unregister_path(key);
});
this.custom_handlers.remove_all();
/* FIXME: When running from `meson test`, this causes SIGHUP
foreach (int fd in this.dev_fd.get_values()) {
debug ("closing master pty fd %i for emulated device", fd);
Posix.close (fd);
} */
if (this.socket_server != null) {
debug ("shutting down socket server thread");
this.socket_server.stop ();
this.socket_server = null;
}
debug ("Removing test bed %s", this.root_dir);
remove_dir (this.root_dir);
this.worker_loop.quit();
Environment.unset_variable("UMOCKDEV_DIR");
}
/**
* umockdev_testbed_get_root_dir:
* @self: A #UMockdevTestbed.
*
* Get the root directory for the testbed. This is mostly useful for
* setting up the "dev/" or "proc/" testbed directories in this root
* directory. For getting the mocked "sys/" dir, use
* #umockdev_testbed_get_sys_dir.
*
* Returns: The testbed's root directory.
*/
public string get_root_dir()
{
return this.root_dir;
}
/**
* umockdev_testbed_get_sys_dir:
* @self: A #UMockdevTestbed.
*
* Get the sysfs directory for the testbed.
*
* Returns: The testbed's sysfs directory.
*/
public string get_sys_dir()
{
return this.sys_dir;
}
/**
* umockdev_testbed_set_attribute:
* @self: A #UMockdevTestbed.
* @devpath: The full device path, as returned by #umockdev_testbed_add_device()
* @name: Attribute name
* @value: Attribute string value
*
* Set a text sysfs attribute for a device.
*/
public void set_attribute(string devpath, string name, string value)
{
this.set_attribute_binary(devpath, name, value.data);
}
/**
* umockdev_testbed_set_attribute_binary:
* @self: A #UMockdevTestbed.
* @devpath: The full device path, as returned by #umockdev_testbed_add_device()
* @name: Attribute name (may contain leading directories like
* "queue/rotational")
* @value: Attribute binary value
* @value_length1: Length of @value in bytes.
*
* Set a binary sysfs attribute for a device.
*/
public void set_attribute_binary(string devpath, string name, uint8[] value)
{
var attr_path = Path.build_filename(this.root_dir, devpath, name);
if ("/" in name) {
string d = Path.get_dirname(attr_path);
checked_mkdir_with_parents(d, 0755);
}
try {
FileUtils.set_data(attr_path, value);
} catch (FileError e) {
error("Cannot write attribute file: %s", e.message);
}
}
/**
* umockdev_testbed_set_attribute_int:
* @self: A #UMockdevTestbed.
* @devpath: The full device path, as returned by #umockdev_testbed_add_device()
* @name: Attribute name (may contain leading directories like
* "queue/rotational")
* @value: Attribute integer value
*
* Set an integer sysfs attribute for a device.
*/
public void set_attribute_int(string devpath, string name, int value)
{
this.set_attribute(devpath, name, value.to_string());
}
/**
* umockdev_testbed_set_attribute_hex:
* @self: A #UMockdevTestbed.
* @devpath: The full device path, as returned by #umockdev_testbed_add_device()
* @name: Attribute name
* @value: Attribute integer value
*
* Set an integer sysfs attribute for a device. Set an integer udev
* property for a device. @value is interpreted as a hexadecimal number.
* For example, for value==31 this sets the attribute contents to "1f".
*/
public void set_attribute_hex(string devpath, string name, uint value)
{
this.set_attribute(devpath, name, "%x".printf(value));
}
/**
* umockdev_testbed_set_attribute_link:
* @self: A #UMockdevTestbed.
* @devpath: The full device path, as returned by #umockdev_testbed_add_device()
* @name: Attribute name
* @value: Attribute link target value
*
* Set a symlink sysfs attribute for a device; this is primarily important
* for setting "driver" links.
*/
public void set_attribute_link(string devpath, string name, string value)
{
var path = Path.build_filename(this.root_dir, devpath, name);
var dir = Path.get_dirname(path);
checked_mkdir_with_parents(dir, 0755);
if (FileUtils.symlink(value, path) < 0) {
error("Cannot create symlink %s: %m", path);
}
}
private string get_attribute(string devpath, string name)
{
string read = null;
var attr_path = Path.build_filename(this.root_dir, devpath, name);
try {
FileUtils.get_contents(attr_path, out read);
} catch (FileError e) {
error("Cannot read attribute file: %s", e.message);
}
return read;
}
/**
* umockdev_testbed_get_property:
* @self: A #UMockdevTestbed.
* @devpath: The full device path, as returned by #umockdev_testbed_add_device()
* @name: Property name
*
* Get a string udev property for a device. Note that this is mostly for
* testing umockdev itself; for real application testing, use
* libudev/gudev.
*
* Returns: property value, or %NULL if it does not exist
*/
public new string? get_property(string devpath, string name)
{
var uevent_path = Path.build_filename(this.root_dir, devpath, "uevent");
string? ret = null;
File f = File.new_for_path(uevent_path);
string prefix = name + "=";
try {
var inp = new DataInputStream(f.read());
string line;
size_t len;
while ((line = inp.read_line(out len)) != null) {
if (line.has_prefix(prefix)) {
ret = line.substring(prefix.length);
break;
}
}
inp.close();
} catch (GLib.Error e) {
error("Cannot read uevent file: %s", e.message);
}
return ret;
}
/**
* umockdev_testbed_set_property:
* @self: A #UMockdevTestbed.
* @devpath: The full device path, as returned by #umockdev_testbed_add_device()
* @name: Property name
* @value: Property string value
*
* Set a string udev property for a device.
*/
public new void set_property(string devpath, string name, string value)
{
var uevent_path = Path.build_filename(this.root_dir, devpath, "uevent");
string props = "";
string real_value;
/* the kernel sets DEVNAME without prefix */
if (name == "DEVNAME" && value.has_prefix("/dev/"))
real_value = value.substring(5);
else
real_value = value;
/* read current properties from the uevent file; if name is already set,
* replace its value with the new one */
File f = File.new_for_path(uevent_path);
bool existing = false;
string prefix = name + "=";
try {
var inp = new DataInputStream(f.read());
string line;
size_t len;
while ((line = inp.read_line(out len)) != null) {
if (line.has_prefix(prefix)) {
existing = true;
props += prefix + real_value + "\n";
} else {
props += line + "\n";
}
}
inp.close();
/* if property name does not yet exist, append it */
if (!existing)
props += prefix + real_value + "\n";
/* write it back */
FileUtils.set_data(uevent_path, props.data);
} catch (GLib.Error e) {
error("Cannot update uevent file: %s", e.message);
}
}
/**
* umockdev_testbed_set_property_int:
* @self: A #UMockdevTestbed.
* @devpath: The full device path, as returned by #umockdev_testbed_add_device()
* @name: Property name
* @value: Property integer value
*
* Set an integer udev property for a device.
*/
public void set_property_int(string devpath, string name, int value)
{
this.set_property(devpath, name, value.to_string());
}
/**
* umockdev_testbed_set_property_hex:
* @self: A #UMockdevTestbed.
* @devpath: The full device path, as returned by #umockdev_testbed_add_device()
* @name: Property name
* @value: Property integer value
*
* Set an integer udev property for a device. @value is interpreted as a
* hexadecimal number. For example, for value==31 this sets the property's
* value to "1f".
*/
public void set_property_hex(string devpath, string name, uint value)
{
this.set_property(devpath, name, "%x".printf(value));
}
private string? add_devicev_no_uevent(string subsystem, string name, string? parent,
[CCode(array_null_terminated=true, array_length=false)] string[] attributes,
[CCode(array_null_terminated=true, array_length=false)] string[] properties)
{
string dev_path;
string? dev_node = null;
if (parent != null) {
if (!parent.has_prefix("/sys/")) {
critical("add_devicev(): parent device %s does not start with /sys/", parent);
return null;
}
if (!FileUtils.test(parent, FileTest.IS_DIR)) {
critical("add_devicev(): parent device %s does not exist", parent);
return null;
}
dev_path = Path.build_filename(parent, name);
} else
dev_path = Path.build_filename("/sys/devices", name);
var dev_dir = Path.build_filename(this.root_dir, dev_path);
/* must not exist yet; do allow existing children, though */
if (FileUtils.test(dev_dir, FileTest.EXISTS) &&
FileUtils.test(Path.build_filename(dev_dir, "uevent"), FileTest.EXISTS))
error("device %s already exists", dev_dir);
string dev_path_no_sys = dev_path.substring(dev_path.index_of("/devices/"));
/* create device and corresponding subsystem dir */
checked_mkdir_with_parents(dev_dir, 0755);
if (!subsystem_is_bus(subsystem)) {
/* class/ symlinks */
var class_dir = Path.build_filename(this.sys_dir, "class", subsystem);
checked_mkdir_with_parents(class_dir, 0755);
/* subsystem symlink */
assert(FileUtils.symlink(Path.build_filename(make_dotdots(dev_path), "class", subsystem),
Path.build_filename(dev_dir, "subsystem")) == 0);
/* device symlink from class/; skip directories in name; this happens
* when being called from add_from_string() when the parent devices do
* not exist yet */
assert(FileUtils.symlink(Path.build_filename("..", "..", dev_path_no_sys),
Path.build_filename(class_dir, Path.get_basename(name))) == 0);
} else {
/* bus symlink */
var bus_dir = Path.build_filename(this.sys_dir, "bus", subsystem, "devices");
checked_mkdir_with_parents(bus_dir, 0755);
assert(FileUtils.symlink(Path.build_filename("..", "..", "..", dev_path_no_sys),
Path.build_filename(bus_dir, Path.get_basename(name))) == 0);
/* subsystem symlink */
assert(FileUtils.symlink(Path.build_filename(make_dotdots(dev_path), "bus", subsystem),
Path.build_filename(dev_dir, "subsystem")) == 0);
}
/* /sys/block symlink */
if (subsystem == "block") {
var block_dir = Path.build_filename(this.sys_dir, "block");
checked_mkdir_with_parents(block_dir, 0755);
assert (FileUtils.symlink(Path.build_filename("..", dev_path_no_sys),
Path.build_filename(block_dir, Path.get_basename(name))) == 0);
}
/* properties; they go into the "uevent" sysfs attribute */
string props = "";
for (int i = 0; i < properties.length - 1; i += 2) {
/* the kernel sets DEVNAME without prefix */
if (properties[i] == "DEVNAME" && properties[i+1].has_prefix("/dev/")) {
dev_node = properties[i+1].substring(5);
props += "DEVNAME=" + dev_node + "\n";
} else
props += properties[i] + "=" + properties[i+1] + "\n";
}
if (properties.length % 2 != 0)
warning("add_devicev: Ignoring property key '%s' without value", properties[properties.length-1]);
this.set_attribute(dev_path, "uevent", props);
/* attributes */
for (int i = 0; i < attributes.length - 1; i += 2) {
this.set_attribute(dev_path, attributes[i], attributes[i+1]);
if (attributes[i] == "dev" && dev_node != null) {
var val = attributes[i+1].strip(); // strip off trailing \n
/* put the major/minor information into /dev for our preload */
string infodir = Path.build_filename(this.root_dir, "dev", ".node");
checked_mkdir_with_parents(infodir, 0755);
assert(FileUtils.symlink(val, Path.build_filename(infodir, dev_node.replace("/", "_"))) == 0);
/* create a /sys/dev link for it, like in real sysfs */
string sysdev_dir = Path.build_filename(this.sys_dir, "dev",
(dev_path.contains("/block/") ? "block" : "char"));
checked_mkdir_with_parents(sysdev_dir, 0755);
string dest = Path.build_filename(sysdev_dir, val);
if (!FileUtils.test(dest, FileTest.EXISTS)) {
if (FileUtils.symlink("../../" + dev_path.substring(5), dest) < 0)
error("add_device %s: failed to symlink %s to %s: %m", name, dest,
dev_path.substring(5));
}
}
}
if (attributes.length % 2 != 0)
warning("add_devicev: Ignoring attribute key '%s' without value", attributes[attributes.length-1]);
return dev_path;
}
/**
* umockdev_testbed_add_devicev:
* @self: A #UMockdevTestbed.
* @subsystem: The subsystem name, e. g. "usb"
* @name: The device name; arbitrary, but needs to be unique within the testbed
* @parent: (allow-none): device path of the parent device. Use %NULL for a
* top-level device.
* @attributes: (array zero-terminated=1):
* A list of device sysfs attributes, alternating names and
* values, terminated with %NULL:
* { "key1", "value1", "key2", "value2", ..., NULL }
* @properties: (array zero-terminated=1):
* A list of device udev properties; same format as @attributes
*
* This method is mostly meant for language bindings (where it is named
* umockdev_testbed_add_device()). For C programs it is usually more convenient to
* use umockdev_testbed_add_device().
*
* Add a new device to the testbed. A Linux kernel device always has a
* subsystem (such as "usb" or "pci"), and a device name. The test bed only
* builds a very simple sysfs structure without nested namespaces, so it
* requires device names to be unique. Some gudev client programs might make
* assumptions about the name (e. g. a SCSI disk block device should be called
* sdaN). A device also has an arbitrary number of sysfs attributes and udev
* properties; usually you should specify them upon creation, but it is also
* possible to change them later on with umockdev_testbed_set_attribute() and
* umockdev_testbed_set_property().
*
* If the pseudo-property "__DEVCONTEXT" is present, the SELinux context of the device's
* DEVNODE will be set to that value.
*
* This will synthesize an "add" uevent.
*
* Returns: The sysfs path for the newly created device. Free with g_free().
*
* Rename to: umockdev_testbed_add_device
*/
public string? add_devicev(string subsystem, string name, string? parent,
[CCode(array_null_terminated=true, array_length=false)] string[] attributes,
[CCode(array_null_terminated=true, array_length=false)] string[] properties)
{
string? dev_path = this.add_devicev_no_uevent(subsystem, name, parent, attributes, properties);
if (dev_path != null && in_mock_environment ())
uevent(dev_path, "add");
return dev_path;
}
/**
* umockdev_testbed_add_device: (skip)
* @self: A #UMockdevTestbed.
* @subsystem: The subsystem name, e. g. "usb"
* @name: The device name; arbitrary, but needs to be unique within the testbed
* @parent: (allow-none): device path of the parent device. Use %NULL for a
* top-level device.
* @...: Arbitrarily many pairs of sysfs attributes (alternating names and
* values), terminated by %NULL, followed by arbitrarily many pairs of udev
* properties, terminated by another %NULL.
*
* Add a new device to the testbed. A Linux kernel device always has a
* subsystem (such as "usb" or "pci"), and a device name. The test bed only
* builds a very simple sysfs structure without nested namespaces, so it
* requires device names to be unique. Some gudev client programs might make
* assumptions about the name (e. g. a SCSI disk block device should be called
* sdaN). A device also has an arbitrary number of sysfs attributes and udev
* properties; usually you should specify them upon creation, but it is also
* possible to change them later on with umockdev_testbed_set_attribute() and
* umockdev_testbed_set_property().
*
* If the pseudo-property "__DEVCONTEXT" is present, the SELinux context of the device's
* DEVNODE will be set to that value.
*
* This will synthesize an "add" uevent.
*
* Example:
* |[
* umockdev_testbed_add_device (testbed, "usb", "dev1", NULL,
* "idVendor", "0815", "idProduct", "AFFE", NULL,
* "ID_MODEL", "KoolGadget", NULL);
* ]|
*
* Returns: The sysfs path for the newly created device. Free with g_free().
*/
public string? add_device(string subsystem, string name, string? parent, ...)
{
string[] attributes = {};
string[] properties = {};
int arg_set = 0; /* 0 -> attributes, 1 -> properties */
/* we iterate arguments until NULL twice; first for the attributes,
* then for the properties */
var l = va_list();
while (true) {
string? arg = l.arg();
if (arg == null) {
if (++arg_set > 1)
break;
else
continue;
}
if (arg_set == 0)
attributes += arg;
else
properties += arg;
}
return this.add_devicev(subsystem, name, parent, attributes, properties);
}
/**
* umockdev_testbed_remove_device:
* @self: A #UMockdevTestbed.
* @syspath: Sysfs path of device
*
* Remove a device from the testbed. This removes the sysfs directory, the
* /sys/class/ link, the device node, and all other information related to
* it. Note that this will also remove all child devices (i. e.
* subdirectories of @syspath).
*/
public void remove_device (string syspath)
{
string real_path = Path.build_filename(this.root_dir, syspath);
string devname = Path.get_basename(syspath);
if (!FileUtils.test(real_path, FileTest.IS_DIR)) {
critical("umockdev_testbed_remove_device(): device %s does not exist", syspath);
return;
}
string subsystem;
try {
subsystem = Path.get_basename(
FileUtils.read_link(Path.build_filename(real_path, "subsystem")));
} catch (FileError e) {
critical("umockdev_testbed_remove_device(): cannot determine subsystem of %s: %s",
syspath, e.message);
return;
}
// /dev and pointers to it
try {
string dev_maj_min;
FileUtils.get_contents(Path.build_filename(real_path, "dev"), out dev_maj_min);
FileUtils.unlink(Path.build_filename(this.sys_dir, "dev",
(syspath.contains("/block/") ? "block" : "char"), dev_maj_min));
string? dev_node = find_devnode(real_path);
if (dev_node != null) {
string real_node = Path.build_filename(this.root_dir, dev_node);
FileUtils.unlink(real_node);
DirUtils.remove(Path.get_dirname(real_node));
FileUtils.unlink(Path.build_filename(this.root_dir, "dev", ".node", dev_node.substring(5).replace("/", "_")));
}
} catch (FileError e) {}
// class symlink
FileUtils.unlink(Path.build_filename(this.sys_dir, "class", subsystem, devname));
DirUtils.remove(Path.build_filename(this.sys_dir, "class", subsystem));
// bus symlink
if (subsystem_is_bus(subsystem)) {
FileUtils.unlink(Path.build_filename(this.sys_dir, "bus", subsystem, "devices", devname));
DirUtils.remove(Path.build_filename(this.sys_dir, "bus", subsystem, "devices"));
DirUtils.remove(Path.build_filename(this.sys_dir, "bus", subsystem));
}
// sysfs dir
remove_dir(real_path, true);
}
/**
* umockdev_testbed_add_from_string:
* @self: A #UMockdevTestbed.
* @data: Description of the device(s) as generated with umockdev-record
* @error: return location for a GError, or %NULL
*
* Add a set of devices to the testbed from a textual description. This reads
* the format generated by the umockdev-record tool.
*
* Each paragraph defines one device. A line starts with a type tag (like 'E'),
* followed by a colon, followed by either a value or a "key=value" assignment,
* depending on the type tag. A device description must start with a 'P:' line.
* Available type tags are:
* <itemizedlist>
* <listitem><type>P:</type> <emphasis>path</emphasis>: device path in sysfs, starting with
* <filename>/devices/</filename>; must occur exactly once at the
* start of device definition</listitem>
* <listitem><type>E:</type> <emphasis>key=value</emphasis>: udev property
* </listitem>
* <listitem><type>A:</type> <emphasis>key=value</emphasis>: ASCII sysfs
* attribute, with backslash-style escaping of \ (\\) and newlines
* (\n)</listitem>
* <listitem><type>H:</type> <emphasis>key=value</emphasis>: binary sysfs
* attribute, with the value being written as continuous hex string
* (e. g. 0081FE0A..)</listitem>
* <listitem><type>N:</type> <emphasis>devname</emphasis>[=<emphasis>contents</emphasis>]:
* device node name (without the <filename>/dev/</filename>
* prefix); if <emphasis>contents</emphasis> is given (encoded in a
* continuous hex string), it creates a
* <filename>/dev/devname</filename> in the mock environment with
* the given contents, otherwise the created dev file will be a
* pty; see #umockdev_testbed_get_dev_fd for details.</listitem>
* <listitem><type>S:</type> <emphasis>linkname</emphasis>: device node
* symlink (without the <filename>/dev/</filename> prefix); ignored right
* now.</listitem>
* </itemizedlist>
*
* Returns: %TRUE on success, %FALSE if the data is invalid and an error
* occurred.
*/
public bool add_from_string (string data) throws UMockdev.Error
{
/* lazily initialize the parsing regexps */
try {
if (this.re_record_val == null)
this.re_record_val = new Regex("^([PS]): (.*)(?>\n|$)");
if (this.re_record_keyval == null)
this.re_record_keyval = new Regex("^([EAHL]): ([^=\n]+)=(.*)(?>\n|$)");
if (this.re_record_optval == null)
this.re_record_optval = new Regex("^([N]): ([^=\n]+)(?>=([0-9A-F]+))?(?>\n|$)");
} catch (RegexError e) {
error("Internal error, cannot create regex: %s", e.message);
}
string cur_data = data;
while (cur_data[0] != '\0')
cur_data = this.add_dev_from_string (cur_data);
return true;
}
/**
* umockdev_testbed_add_from_file:
* @self: A #UMockdevTestbed.
* @path: Path to file with description of the device(s) as generated with umockdev-record
* @error: return location for a GError, or %NULL
*
* Add a set of devices to the testbed from a textual description. This
* reads a file with the format generated by the umockdev-record tool, and
* is mostly a convenience wrapper around
* @umockdev_testbed_add_from_string.
*
* Returns: %TRUE on success, %FALSE if the @path cannot be read or thhe
* data is invalid and an error occurred.
*/
public bool add_from_file (string path) throws UMockdev.Error, FileError
{
string contents;
FileUtils.get_contents(path, out contents);
return this.add_from_string(contents);
}
/**
* umockdev_testbed_uevent:
* @self: A #UMockdevTestbed.
* @devpath: The full device path, as returned by #umockdev_testbed_add_device()
* @action: "add", "remove", or "change"
*
* Generate an uevent for a device.
*/
public void uevent (string devpath, string action)
{
if (this.ev_sender == null) {
debug("umockdev_testbed_uevent: lazily initializing uevent_sender");
this.ev_sender = new UeventSender.sender(this.root_dir);
assert(this.ev_sender != null);
}
debug("umockdev_testbed_uevent: sending uevent %s for device %s", action, devpath);
var uevent_path = Path.build_filename(this.root_dir, devpath, "uevent");
var properties = "";
try {
FileUtils.get_contents(uevent_path, out properties);
} catch (FileError e) {
debug("uevent: devpath %s has no uevent file: %s", devpath, e.message);
}
this.ev_sender.send(devpath, action, properties);
}
/**
* umockdev_testbed_attach_ioctl:
* @self: A #UMockdevTestbed.
* @dev: Device path (/dev/...) to attach to.
* @handler: a #UMockdevIoctlBase instance to handle requests
* @error: return location for a GError, or %NULL
*
* Attach an #UMockdevIoctlBase object to handle ioctl, read and write
* syscalls on the given device file. This allows emulating arbitrary
* ioctl's and read/write calls for which umockdev does not have builtin
* support.
*
* Returns: %TRUE on success, %FALSE on error.
* Since: 0.16
*/
public bool attach_ioctl (string dev, IoctlBase handler) throws GLib.Error
{
assert (!this.custom_handlers.contains (dev));
string sockpath = Path.build_filename(this.root_dir, "ioctl", dev);
handler.register_path(this.worker_ctx, dev, sockpath);
this.custom_handlers.insert(dev, handler);
return true;
}
/**
* umockdev_testbed_detach_ioctl:
* @self: A #UMockdevTestbed.
* @dev: Device path (/dev/...) to detach.
* @error: return location for a GError, or %NULL
*
* Detach a custom #UMockdevIoctlBase object from an device node again. See
* umockdev_testbed_attach_ioctl(). It is an error to call this function
* if the path is not currently attached.
*
* Returns: %TRUE on success, %FALSE on error.
* Since: 0.16
*/
public bool detach_ioctl (string dev) throws GLib.Error
{
IoctlBase handler = this.custom_handlers[dev];
if (handler == null)
throw new IOError.NOT_FOUND("No handler for device was registered.");
handler.unregister_path(dev);
this.custom_handlers.remove(dev);
return true;
}
/**
* umockdev_testbed_load_ioctl:
* @self: A #UMockdevTestbed.
* @dev: Device path (/dev/...) for which to load the ioctl record.
* %NULL is valid; in this case the ioctl record is associated with
* the device node it was recorded from.
* @recordfile: Path of the ioctl record file.
* @error: return location for a GError, or %NULL
*
* Load an ioctl record file for a particular device into the testbed.
* ioctl records can be created with umockdev-record --ioctl.
* They can optionally be xz compressed to save space (but then are
* required to have an .xz file name suffix).
*
* Returns: %TRUE on success, %FALSE if the data is invalid and an error
* occurred.
*/
public bool load_ioctl (string? dev, string recordfile) throws GLib.Error, FileError, IOError, RegexError
{
string format = "";
DataInputStream recording;
// Apparently valac isn't smart enough to turn a parameter into an owned
// variable when we assign to it, so we need an explicit copy here.
string? owned_dev = dev;
if (recordfile.has_suffix(".xz")) {
try {
string contents;
int exit;
Process.spawn_sync(null, {"xz", "-cd", recordfile}, null,
SpawnFlags.SEARCH_PATH,
null,
out contents,
null,
out exit);
assert(exit == 0);
recording = new DataInputStream(new MemoryInputStream.from_data(contents.data, null));
} catch (SpawnError e) {
error("Cannot call xz to decompress %s: %s", recordfile, e.message);
}
} else
recording = new DataInputStream(File.new_for_path(recordfile).read());
// Grab information from header file
// Ignore any leading comments
string line = recording.read_line();
while (line != null && line.has_prefix("#"))
line = recording.read_line();
// Next must be our @DEV <devicenode> header
MatchInfo header_matcher = null;
if (line != null && (new Regex("^@DEV (.*?)( \\((?P<format>[^)]*)\\))?(\n|$)")).match(line, 0, out header_matcher)) {
if (owned_dev == null)
owned_dev = header_matcher.fetch(1);
format = header_matcher.fetch_named("format");
} else if (owned_dev == null) {
error("null passed for device node, but recording %s has no @DEV header", recordfile);
}
recording.seek(0, SeekType.SET);
string dest = Path.build_filename(this.root_dir, "ioctl", owned_dev + ".tree");
checked_mkdir_with_parents(Path.get_dirname(dest), 0755);
string? contents = recording.read_upto("", 0, null);
if (contents == null)
contents = "";
if (!FileUtils.set_contents(dest, contents))
return false;
IoctlBase handler;
if (format == "SPI")
handler = new IoctlSpiHandler(dest);
else
handler = new IoctlTreeHandler(dest);
string sockpath = Path.build_filename(this.root_dir, "ioctl", owned_dev);
handler.register_path(this.worker_ctx, owned_dev, sockpath);
return true;
}
/**
* umockdev_testbed_load_pcap:
* @self: A #UMockdevTestbed.
* @sysfs: sysfs path for device (/sys/...)
* @recordfile: Path of the pcap or pcapng file.
* @error: return location for a GError, or %NULL
*
* Load a USB pcap/pcapng recording created using e.g. wireshark.
* The device must have been added previously as the device path in /dev
* as well as the bus and device numbers need to be extraced from the udev
* information.
*
* Returns: %TRUE on success, %FALSE if the recording could not be loaded
* Since: 0.16
*/
public bool load_pcap (string sysfs, string recordfile) throws GLib.Error, FileError, IOError, RegexError
{
string owned_dev;
string sockpath;
int busnum;
int devnum;
busnum = int.parse(get_attribute(sysfs, "busnum"));
devnum = int.parse(get_attribute(sysfs, "devnum"));
owned_dev = Path.build_filename("/dev", "bus", "usb",
busnum.to_string("%03d"), devnum.to_string("%03d"));
sockpath = Path.build_filename(this.root_dir, "ioctl", owned_dev);
checked_mkdir_with_parents(Path.get_dirname(sockpath), 0755);
IoctlUsbPcapHandler handler = new IoctlUsbPcapHandler(recordfile, busnum, devnum);
handler.register_path(this.worker_ctx, owned_dev, sockpath);
return true;
}
/**
* umockdev_testbed_load_script:
* @self: A #UMockdevTestbed.
* @dev: Device path (/dev/...) for which to load the script record.
* %NULL is valid; in this case the script is associated with
* the device node it was recorded from.
* @recordfile: Path of the script record file.
* @error: return location for a GError, or %NULL
*
* Load a script record file for a particular device into the testbed.
* script records can be created with umockdev-record --script.
*
* Returns: %TRUE on success, %FALSE if @recordfile is invalid and an error
* occurred.
*/
public bool load_script (string? dev, string recordfile)
throws GLib.Error, FileError, IOError, RegexError
{
string? owned_dev = dev;
if (owned_dev == null) {
var recording = new DataInputStream(File.new_for_path(recordfile).read());
// Ignore any leading comments
string line = recording.read_line();
while (line != null && line.has_prefix("#"))
line = recording.read_line();
// Next must be our d 0 <devicenode> header
if (line == null)