[stgt] [PATCH 02/13] mem_copy_n32: safe memcpy, accumulates copied count, tracks remaining space

nezhinsky at gmail.com nezhinsky at gmail.com
Wed Jan 16 10:01:42 CET 2013


From: Alexander Nezhinsky <nezhinsky at gmail.com>

To assist safe generation of data-in buffer for SPC-type read commands
two new utility functions are defined:

int mem_copy_n32(uint8_t *dst, uint8_t *src, uint32_t src_len,
                 uint32_t *avail_len, uint32_t *remain_len)

Copies up to src_len bytes from src, making sure
  not to exceed *remain_len bytes available at dst.
  Returns actually copied length, updates remaining space
  in *remain_len (mandatory parameter),
  accumulate copied length in *avail_len (optional parameter).

void set_byte_n32(int val, uint8_t *dst, uint32_t index, uint32_t max_len)

Sets a byte at the given index within dst buffer to val,
  making sure not to exceed max_len bytes available at dst.

Signed-off-by: Alexander Nezhinsky <nezhinsky at gmail.com>
---
 usr/util.c |   31 +++++++++++++++++++++++++++++++
 usr/util.h |    4 ++++
 2 files changed, 35 insertions(+)

diff --git a/usr/util.c b/usr/util.c
index 6c9bad7..3392b0b 100644
--- a/usr/util.c
+++ b/usr/util.c
@@ -196,3 +196,34 @@ int get_blk_shift(unsigned int size)
 	return shift;
 }
 
+/*
+ * Copy up to src_len bytes from src,
+ * not exceeding *remain_len bytes available at dst.
+ * Return actually copied length.
+ * Reflect decreased space in *remain_len (mandatory).
+ * Accumulate copied length in *avail_len (optional).
+ */
+int mem_copy_n32(uint8_t *dst, uint8_t *src, uint32_t src_len,
+		 uint32_t *avail_len, uint32_t *remain_len)
+{
+	int copy_len = min_t(uint32_t, *remain_len, src_len);
+
+	if (copy_len) {
+		memcpy(dst, src, copy_len);
+		*remain_len -= copy_len;
+	}
+	if (avail_len)
+		*avail_len += src_len;
+	return copy_len;
+}
+
+/*
+ * Set a byte at the given index within dst buffer to val,
+ * not exceeding max_len bytes available at dst.
+ */
+void set_byte_n32(int val, uint8_t *dst, uint32_t index, uint32_t max_len)
+{
+	if (index < max_len)
+		dst[index] = (uint8_t)val;
+}
+
diff --git a/usr/util.h b/usr/util.h
index 76cff2a..d4c7d59 100644
--- a/usr/util.h
+++ b/usr/util.h
@@ -67,6 +67,10 @@ extern int backed_file_open(char *path, int oflag, uint64_t *size,
 extern int set_non_blocking(int fd);
 extern int str_to_open_flags(char *buf);
 extern char *open_flags_to_str(char *dest, int flags);
+extern int mem_copy_n32(uint8_t *dst, uint8_t *src, uint32_t src_len,
+			uint32_t *avail_len, uint32_t *remain_len);
+extern void set_byte_n32(int val, uint8_t *dst, uint32_t index,
+			 uint32_t max_len);
 
 #define zalloc(size)			\
 ({					\
-- 
1.7.9.6

--
To unsubscribe from this list: send the line "unsubscribe stgt" in
the body of a message to majordomo at vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html



More information about the stgt mailing list