lib: Add a function to split a string into substrings

Some environment variables provide a space-separated list of strings. It
is easier to process these when they are broken out into an array of
strings.

Add a utility function to handle this.

Signed-off-by: Simon Glass <sjg@chromium.org>
diff --git a/lib/strto.c b/lib/strto.c
index 6462d4f..1549211 100644
--- a/lib/strto.c
+++ b/lib/strto.c
@@ -11,6 +11,7 @@
 
 #include <common.h>
 #include <errno.h>
+#include <malloc.h>
 #include <linux/ctype.h>
 
 /* from lib/kstrtox.c */
@@ -222,3 +223,43 @@
 	if (len)
 		*out = '\0';
 }
+
+const char **str_to_list(const char *instr)
+{
+	const char **ptr;
+	char *str, *p;
+	int count, i;
+
+	/* don't allocate if the string is empty */
+	str = *instr ? strdup(instr) : (char *)instr;
+	if (!str)
+		return NULL;
+
+	/* count the number of space-separated strings */
+	for (count = *str != '\0', p = str; *p; p++) {
+		if (*p == ' ') {
+			count++;
+			*p = '\0';
+		}
+	}
+
+	/* allocate the pointer array, allowing for a NULL terminator */
+	ptr = calloc(count + 1, sizeof(char *));
+	if (!ptr) {
+		if (*str)
+			free(str);
+		return NULL;
+	}
+
+	for (i = 0, p = str; i < count; p += strlen(p) + 1, i++)
+		ptr[i] = p;
+
+	return ptr;
+}
+
+void str_free_list(const char **ptr)
+{
+	if (ptr)
+		free((char *)ptr[0]);
+	free(ptr);
+}