Fix: Initialize .bss in sp environment startup code

Clear .bss on SP startup to have a clear starting point regardless of
the behavior of the loader. The code relies on having the .bss filled
with zeroes on startup, otherwise it will result in undefined behavior.

Signed-off-by: Imre Kis <imre.kis@arm.com>
Change-Id: Ic5cdafc2a041b0e709cd8e8acb59caa45957fa1d
diff --git a/environments/sp/entry.S b/environments/sp/entry.S
index 5fc0af3..29c61c3 100644
--- a/environments/sp/entry.S
+++ b/environments/sp/entry.S
@@ -1,6 +1,6 @@
 /* SPDX-License-Identifier: BSD-3-Clause */
 /*
- * Copyright (c) 2021-2022, Arm Limited and Contributors. All rights reserved.
+ * Copyright (c) 2021-2023, Arm Limited and Contributors. All rights reserved.
  */
 
 #include <asm.S>
@@ -43,7 +43,7 @@
 
 	/* Only R_AARCH64_RELATIVE type is supported */
 	cmp	w8, #R_AARCH64_RELATIVE
-	bne	3f	/* Error */
+	bne	relocation_error
 
 	/*
 	 * Apply relative adjustment on address
@@ -56,9 +56,24 @@
 	bne	1b
 
 2:
+	/* Clear BSS */
+	adrp	x4, __bss_start
+	add	x4, x4, :lo12:__bss_start
+	adrp	x5, __bss_end
+	add	x5, x5, :lo12:__bss_end
+
+	cmp	x4,	x5
+	b.eq	clear_bss_end
+
+clear_bss:
+	str	xzr,	[x4],	#8
+	cmp	x4,	x5
+	b.lt	clear_bss
+
+clear_bss_end:
 	b	_sp_entry
 
-3:
+relocation_error:
 	adr	X0,	error_invalid_relocation
 	bl	trace_puts
 	b	.
diff --git a/environments/sp/sp.ld.S b/environments/sp/sp.ld.S
index e0380e3..7a57a97 100644
--- a/environments/sp/sp.ld.S
+++ b/environments/sp/sp.ld.S
@@ -2,7 +2,7 @@
 /*
  * Copyright (c) 2014, STMicroelectronics International N.V. All rights reserved.
  * Copyright (c) 2015, Linaro Limited. All rights reserved.
- * Copyright (c) 2021-2022, Arm Limited and Contributors. All rights reserved.
+ * Copyright (c) 2021-2023, Arm Limited and Contributors. All rights reserved.
  */
 #ifdef ARM32
 OUTPUT_FORMAT("elf32-littlearm")
@@ -92,7 +92,9 @@
 
 	.data : { *(.data .data.* .gnu.linkonce.d.*) }
 	.bss : {
+		__bss_start = .;
 		*(.bss .bss.* .gnu.linkonce.b.* COMMON)
+		__bss_end = .;
 	}
 	.stack : {
 		. = ALIGN(4);