arm: Fix encoding of SG stubs in BE8 mode

The Secure Gateway veneers in section .gnu.sgstubs are not part of the
stub group (see dedicated_output_section handling in
elf32_arm_create_or_find_stub_sec).

As a result, elf32_arm_final_link does not perform BE8 encoding when
it processes the regular stub sections.

This patch adds the same handling for cmse_stub_sec, and a new
testcase which checks the raw encoding of the instructions in the
veneer.
For the instructions:
    e97f e97f    sg
    f7ef bffe    b.w <__acle_se_exported_entry_veneer3>
    e97f e97f    sg
    f7ef bff8    b.w <__acle_se_exported_entry_veneer2>

We expect
7fe97fe9 eff7febf 7fe97fe9 eff7f8bf

but without the fix, we generate:
e97fe97f f7efbffe e97fe97f f7efbff8
(that is, bytes are swapped compared to the expected output)

Tested on:
arm-linux-gnueabihf
armv8l-linux-gnueabihf
armeb-linux-gnueabihf
arm-linux-gnueabi
arm-none-eabi
armeb-none-eabi
arm-netbsdelf
arm-pe
arm-wince-pe
arm-uclinuxfdpiceabi
arm-vxworks
diff --git a/bfd/elf32-arm.c b/bfd/elf32-arm.c
index a8fca76..8a04021 100644
--- a/bfd/elf32-arm.c
+++ b/bfd/elf32-arm.c
@@ -13843,6 +13843,19 @@
 	}
     }
 
+  /* Process CMSE stubs (they are not part of the stub_group above).  */
+  if (htab->cmse_stub_sec != NULL)
+    {
+      sec = htab->cmse_stub_sec;
+      osec = sec->output_section;
+
+      elf32_arm_write_section (abfd, info, sec, sec->contents);
+
+      if (!bfd_set_section_contents (abfd, osec, sec->contents,
+				     sec->output_offset, sec->size))
+	return false;
+    }
+
   /* Write out any glue sections now that we have created all the
      stubs.  */
   if (globals->bfd_of_glue_owner != NULL)
diff --git a/ld/testsuite/ld-arm/arm-elf.exp b/ld/testsuite/ld-arm/arm-elf.exp
index cacd3bd..fce05b7 100644
--- a/ld/testsuite/ld-arm/arm-elf.exp
+++ b/ld/testsuite/ld-arm/arm-elf.exp
@@ -820,6 +820,15 @@
       {cmse_main.s cmse_sec_debug.s}
       {{objdump --dwarf=info cmse_main_sec_debug.d}}
       "cmse_main_sec_debug"}
+    {"Secure gateway veneers: BE8 encoding"
+      "-EB --be8 --section-start .gnu.sgstubs=0x20000 \
+      --section-start .text=0x10000 \
+      --out-implib=tmpdir/cmse-be8.lib --cmse-implib"
+     ""
+     "-EB -march=armv8-m.base -mthumb --defsym VER=1"
+     {cmse-implib.s}
+     {{objdump {-s -j .gnu.sgstubs} cmse-be8.d}}
+     "cmse-be8"}
 
     {"R_ARM_THM_JUMP19 Relocation veneers: Short"
      "--section-start destsect=0x000108002 --section-start .text=0x8000" ""
diff --git a/ld/testsuite/ld-arm/cmse-be8.d b/ld/testsuite/ld-arm/cmse-be8.d
new file mode 100644
index 0000000..dda1d2d
--- /dev/null
+++ b/ld/testsuite/ld-arm/cmse-be8.d
@@ -0,0 +1,5 @@
+.*: +file format elf32-bigarm
+
+Contents of section .gnu.sgstubs:
+ 20000 7fe97fe9 eff7febf 7fe97fe9 eff7f8bf .*
+ 20010 00000000 00000000 00000000 00000000 .*