From 84a0333eeaaa82ccd3e9acc6943ccba1cad7e9ae Mon Sep 17 00:00:00 2001
From: Moe Jette <jette1@llnl.gov>
Date: Wed, 1 Jul 2009 15:41:20 +0000
Subject: [PATCH] Strip brackets off of allocated cores string built for SPANK.
 Fix memory leak in allocated cores string logic. Add check for malloc failure
 in  allocated cores string logic.

---
 src/common/slurm_cred.c | 21 +++++++++++++++++----
 src/common/slurm_cred.h |  4 +++-
 2 files changed, 20 insertions(+), 5 deletions(-)

diff --git a/src/common/slurm_cred.c b/src/common/slurm_cred.c
index 7419c28a971..904d9e60d3d 100644
--- a/src/common/slurm_cred.c
+++ b/src/common/slurm_cred.c
@@ -1119,7 +1119,7 @@ char*
 format_core_allocs(slurm_cred_t cred, char *node_name)
 {
 	bitstr_t	*core_bitmap;
-	char		*str = NULL;
+	char		str[1024], *bracket_ptr;
 	hostset_t	hset = NULL;
 	int		host_index = -1;
 	uint32_t	i, j, i_first_bit=0, i_last_bit=0;
@@ -1134,6 +1134,7 @@ format_core_allocs(slurm_cred_t cred, char *node_name)
 	if ((host_index < 0) || (host_index >= cred->job_nhosts)) {
 		error("Invalid host_index %d for job %u",
 		      host_index, cred->jobid);
+		hostset_destroy(hset);
 		return NULL;
 	}
 	host_index++;	/* change from 0-origin to 1-origin */
@@ -1155,16 +1156,28 @@ format_core_allocs(slurm_cred_t cred, char *node_name)
 	}
 
 	core_bitmap = bit_alloc(i_last_bit - i_first_bit);
+	if (core_bitmap == NULL) {
+		error("bit_alloc malloc failure");
+		hostset_destroy(hset);
+		return NULL;
+	}
 	for (i = i_first_bit, j = 0; i < i_last_bit; i++, j++) {
 		if (bit_test(cred->core_bitmap, i))
 			bit_set(core_bitmap, j);
 	}
 
-	str = xmalloc(1024);
-	bit_fmt(str, 1024, core_bitmap);
+	bit_fmt(str, sizeof(str), core_bitmap);
 	bit_free(core_bitmap);
+	hostset_destroy(hset);
+
+	if (str[0] != '[')
+		return xstrdup(str);
 
-	return str;
+	/* strip off brackets */
+	bracket_ptr = strchr(str, ']');
+	if (bracket_ptr)
+		bracket_ptr[0] = '\0';
+	return xstrdup(str+1);
 }
 
 void
diff --git a/src/common/slurm_cred.h b/src/common/slurm_cred.h
index c3090d0c7cb..80111247c8f 100644
--- a/src/common/slurm_cred.h
+++ b/src/common/slurm_cred.h
@@ -294,7 +294,9 @@ int slurm_cred_get_signature(slurm_cred_t cred, char **datap,
 
 /*
  * Retrieve the set of cores that were allocated to the job and format them
- * in the List Format (e.g., "0-2,7,12-14")
+ * in the List Format (e.g., "0-2,7,12-14").
+ *
+ * NOTE: caller must xfree the returned string.
  */
 char* format_core_allocs(slurm_cred_t cred, char *node_name);
 
-- 
GitLab