LZ4_initStream() checks alignment restriction
authorYann Collet <cyan@fb.com>
Mon, 8 Apr 2019 19:49:54 +0000 (12:49 -0700)
committerYann Collet <cyan@fb.com>
Mon, 8 Apr 2019 19:49:54 +0000 (12:49 -0700)
updated associated documentation

lib/lz4.c
lib/lz4.h

index e0fcf0f..a2e58c0 100644 (file)
--- a/lib/lz4.c
+++ b/lib/lz4.c
@@ -1284,10 +1284,17 @@ LZ4_stream_t* LZ4_createStream(void)
     return lz4s;
 }
 
+static size_t LZ4_stream_t_alignment(void)
+{
+    struct { char c; LZ4_stream_t t; } t_a;
+    return sizeof(t_a) - sizeof(t_a.t);
+}
+
 LZ4_stream_t* LZ4_initStream (void* buffer, size_t size)
 {
     DEBUGLOG(5, "LZ4_initStream");
     if (size < sizeof(LZ4_stream_t)) return NULL;
+    if (((size_t)buffer) & (LZ4_stream_t_alignment() - 1)) return NULL;  /* alignment check */
     MEM_INIT(buffer, 0, sizeof(LZ4_stream_t));
     return (LZ4_stream_t*)buffer;
 }
index 5aa4229..e55e1c6 100644 (file)
--- a/lib/lz4.h
+++ b/lib/lz4.h
@@ -528,13 +528,16 @@ union LZ4_stream_u {
 
 /*! LZ4_initStream() :
  *  An LZ4_stream_t structure must be initialized at least once.
- *  While this is automatically done when invoking LZ4_createStream(),
- *  it's not when the structure is simply declared on stack (for example).
- *  Use this function to properly initialize a newly declared LZ4_stream_t.
- *  It can also accept any arbitrary buffer of sufficient size as input,
- *  and will return a pointer of proper type upon initialization.
- *  Note : initialization can fail if size < sizeof(LZ4_stream_t).
- *  In which case, the function will @return NULL.
+ *  This is automatically done when invoking LZ4_createStream(),
+ *  but it's not when the structure is simply declared on stack (for example).
+ *
+ *  Use LZ4_initStream() to properly initialize a newly declared LZ4_stream_t.
+ *  It can also initialize any arbitrary buffer of sufficient size,
+ *  and will @return a pointer of proper type upon initialization.
+ *
+ *  Note : initialization fails if size and alignment conditions are not respected.
+ *         In which case, the function will @return NULL.
+ *  Note2: An LZ4_stream_t structure guarantees correct alignment and size.
  */
 LZ4LIB_API LZ4_stream_t* LZ4_initStream (void* buffer, size_t size);