Browse Source

[fault] Add inject_corruption() to randomly corrupt data

Provide an inject_corruption() function that can be used to randomly
corrupt data bytes with configurable probabilities.

Signed-off-by: Michael Brown <mcb30@ipxe.org>
tags/v1.20.1
Michael Brown 9 years ago
parent
commit
89816af2a4
2 changed files with 50 additions and 0 deletions
  1. 29
    0
      src/core/fault.c
  2. 21
    0
      src/include/ipxe/fault.h

+ 29
- 0
src/core/fault.c View File

@@ -51,3 +51,32 @@ int inject_fault_nonzero ( unsigned int rate ) {
51 51
 	 */
52 52
 	return -EFAULT;
53 53
 }
54
+
55
+/**
56
+ * Corrupt data with a specified probability
57
+ *
58
+ * @v rate		Reciprocal of fault probability (must be non-zero)
59
+ * @v data		Data
60
+ * @v len		Length of data
61
+ * @ret rc		Return status code
62
+ */
63
+void inject_corruption_nonzero ( unsigned int rate, const void *data,
64
+				 size_t len ) {
65
+	uint8_t *writable;
66
+	size_t offset;
67
+
68
+	/* Do nothing if we have no data to corrupt */
69
+	if ( ! len )
70
+		return;
71
+
72
+	/* Do nothing unless we want to inject a fault now */
73
+	if ( ! inject_fault_nonzero ( rate ) )
74
+		return;
75
+
76
+	/* Get a writable pointer to the nominally read-only data */
77
+	writable = ( ( uint8_t * ) data );
78
+
79
+	/* Pick a random victim byte and zap it */
80
+	offset = ( random() % len );
81
+	writable[offset] ^= random();
82
+}

+ 21
- 0
src/include/ipxe/fault.h View File

@@ -9,9 +9,12 @@
9 9
 
10 10
 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
11 11
 
12
+#include <stdint.h>
12 13
 #include <config/fault.h>
13 14
 
14 15
 extern int inject_fault_nonzero ( unsigned int rate );
16
+extern void inject_corruption_nonzero ( unsigned int rate, const void *data,
17
+					size_t len );
15 18
 
16 19
 /**
17 20
  * Inject fault with a specified probability
@@ -29,4 +32,22 @@ inject_fault ( unsigned int rate ) {
29 32
 	return inject_fault_nonzero ( rate );
30 33
 }
31 34
 
35
+/**
36
+ * Corrupt data with a specified probability
37
+ *
38
+ * @v rate		Reciprocal of fault probability (zero for no faults)
39
+ * @v data		Data
40
+ * @v len		Length of data
41
+ * @ret rc		Return status code
42
+ */
43
+static inline __attribute__ (( always_inline )) void
44
+inject_corruption ( unsigned int rate, const void *data, size_t len ) {
45
+
46
+	/* Force dead code elimination in non-fault-injecting builds */
47
+	if ( rate == 0 )
48
+		return;
49
+
50
+	return inject_corruption_nonzero ( rate, data, len );
51
+}
52
+
32 53
 #endif /* _IPXE_FAULT_H */

Loading…
Cancel
Save