Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(5)

Unified Diff: include/core/SkTypes.h

Issue 1510683002: Add sk_careful_memcpy to catch undefined behavior in memcpy. (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: reed Created 5 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « include/core/SkTDArray.h ('k') | src/core/SkPathRef.cpp » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: include/core/SkTypes.h
diff --git a/include/core/SkTypes.h b/include/core/SkTypes.h
index 5720c30970e5d2ce1ad9f69922caa6a32eeb1163..6c2e6361530ac9674da7f69f7b2dd978bb80ce32 100644
--- a/include/core/SkTypes.h
+++ b/include/core/SkTypes.h
@@ -24,6 +24,28 @@
#include <string.h>
+/**
+ * sk_careful_memcpy() is just like memcpy(), but guards against undefined behavior.
+ *
+ * It is undefined behavior to call memcpy() with null dst or src, even if len is 0.
+ * If an optimizer is "smart" enough, it can exploit this to do unexpected things.
+ * memcpy(dst, src, 0);
+ * if (src) {
+ * printf("%x\n", *src);
+ * }
+ * In this code the compiler can assume src is not null and omit the if (src) {...} check,
+ * unconditionally running the printf, crashing the program if src really is null.
+ * Of the compilers we pay attention to only GCC performs this optimization in practice.
+ */
+static inline void* sk_careful_memcpy(void* dst, const void* src, size_t len) {
+ // When we pass >0 len we had better already be passing valid pointers.
+ // So we just need to skip calling memcpy when len == 0.
+ if (len) {
+ memcpy(dst,src,len);
+ }
+ return dst;
+}
+
/** \file SkTypes.h
*/
« no previous file with comments | « include/core/SkTDArray.h ('k') | src/core/SkPathRef.cpp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698