]> git.ipfire.org Git - thirdparty/ipxe.git/commitdiff
[fault] Add inject_corruption() to randomly corrupt data
authorMichael Brown <mcb30@ipxe.org>
Wed, 22 Jul 2015 13:29:20 +0000 (14:29 +0100)
committerMichael Brown <mcb30@ipxe.org>
Wed, 22 Jul 2015 20:17:47 +0000 (21:17 +0100)
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>
src/core/fault.c
src/include/ipxe/fault.h

index 91289fdeab35e6d08cb2ef955a0f6a57f431eb94..63d3ccacf8b4ca71b9413e20191d219666928e93 100644 (file)
@@ -51,3 +51,32 @@ int inject_fault_nonzero ( unsigned int rate ) {
         */
        return -EFAULT;
 }
+
+/**
+ * Corrupt data with a specified probability
+ *
+ * @v rate             Reciprocal of fault probability (must be non-zero)
+ * @v data             Data
+ * @v len              Length of data
+ * @ret rc             Return status code
+ */
+void inject_corruption_nonzero ( unsigned int rate, const void *data,
+                                size_t len ) {
+       uint8_t *writable;
+       size_t offset;
+
+       /* Do nothing if we have no data to corrupt */
+       if ( ! len )
+               return;
+
+       /* Do nothing unless we want to inject a fault now */
+       if ( ! inject_fault_nonzero ( rate ) )
+               return;
+
+       /* Get a writable pointer to the nominally read-only data */
+       writable = ( ( uint8_t * ) data );
+
+       /* Pick a random victim byte and zap it */
+       offset = ( random() % len );
+       writable[offset] ^= random();
+}
index 32aa064842c0ba6a79cc8bacf9d8bc7312b26ef0..356296c3544fbb121f10f40d86ea9f6e9711f51d 100644 (file)
@@ -9,9 +9,12 @@
 
 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
 
+#include <stdint.h>
 #include <config/fault.h>
 
 extern int inject_fault_nonzero ( unsigned int rate );
+extern void inject_corruption_nonzero ( unsigned int rate, const void *data,
+                                       size_t len );
 
 /**
  * Inject fault with a specified probability
@@ -29,4 +32,22 @@ inject_fault ( unsigned int rate ) {
        return inject_fault_nonzero ( rate );
 }
 
+/**
+ * Corrupt data with a specified probability
+ *
+ * @v rate             Reciprocal of fault probability (zero for no faults)
+ * @v data             Data
+ * @v len              Length of data
+ * @ret rc             Return status code
+ */
+static inline __attribute__ (( always_inline )) void
+inject_corruption ( unsigned int rate, const void *data, size_t len ) {
+
+       /* Force dead code elimination in non-fault-injecting builds */
+       if ( rate == 0 )
+               return;
+
+       return inject_corruption_nonzero ( rate, data, len );
+}
+
 #endif /* _IPXE_FAULT_H */