Browse Source

mem: add memtaint().

Useful if you're going to reuse a buffer later.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Rusty Russell 10 years ago
parent
commit
a934320836
2 changed files with 35 additions and 0 deletions
  1. 19 0
      ccan/mem/mem.c
  2. 16 0
      ccan/mem/mem.h

+ 19 - 0
ccan/mem/mem.c

@@ -107,3 +107,22 @@ bool memeqzero(const void *data, size_t length)
 	/* Now we know that's zero, memcmp with self. */
 	return memcmp(data, p, length) == 0;
 }
+
+void memtaint(void *data, size_t len)
+{
+	/* Using 16 bytes is a bit quicker than 4 */
+	const unsigned tainter[]
+		= { 0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef };
+	char *p = data;
+
+	while (len >= sizeof(tainter)) {
+		memcpy(p, tainter, sizeof(tainter));
+		p += sizeof(tainter);
+		len -= sizeof(tainter);
+	}
+	memcpy(p, tainter, len);
+
+#if HAVE_VALGRIND_MEMCHECK_H
+	VALGRIND_MAKE_MEM_UNDEFINED(data, len);
+#endif
+}

+ 16 - 0
ccan/mem/mem.h

@@ -275,4 +275,20 @@ static inline void *memcheck_(const void *data, size_t len)
 #else
 #define memcheck(data, len) memcheck_((data), (len))
 #endif
+
+/**
+ * memtaint - mark a memory region unused
+ * @data: start of region
+ * @len: length in bytes
+ *
+ * This writes an "0xdeadbeef" eyecatcher repeatedly to the memory.
+ * When running under valgrind, it also tells valgrind that the memory is
+ * uninitialized, triggering valgrind errors if it is used for branches
+ * or written out (or passed to memcheck!) in future.
+ *
+ * Example:
+ *	// We'll reuse this buffer later, but be sure we don't access it.
+ *	memtaint(somebytes, bytes_len);
+ */
+void memtaint(void *data, size_t len);
 #endif /* CCAN_MEM_H */