From 83f89912e0f9e9e2b62743b1a3d9080ada280a52 Mon Sep 17 00:00:00 2001
From: Jeremy Soller <jeremy@system76.com>
Date: Sat, 20 Apr 2019 10:36:18 -0600
Subject: [PATCH] Do not copy kernel-allocated TLS

---
 src/ld_so/tcb.rs    | 13 +++++++------
 src/platform/pte.rs | 14 +++++++++-----
 2 files changed, 16 insertions(+), 11 deletions(-)

diff --git a/src/ld_so/tcb.rs b/src/ld_so/tcb.rs
index 643e5122..662ef4c5 100644
--- a/src/ld_so/tcb.rs
+++ b/src/ld_so/tcb.rs
@@ -55,6 +55,7 @@ impl Tcb {
         let (tls, tcb_page) = Self::os_new(size)?;
 
         let tcb_ptr = tcb_page.as_mut_ptr() as *mut Self;
+        // println!("New TCB: {:p}", tcb_ptr);
         ptr::write(tcb_ptr, Self {
             tls_end: tls.as_mut_ptr().add(tls.len()),
             tls_len: tls.len(),
@@ -111,12 +112,12 @@ impl Tcb {
                     let range = master.range();
                     let data = master.data();
                     if let Some(tls_data) = tls.get_mut(range) {
-                        println!(
-                            "tls master {}: {:p}, {:#x}: {:p}, {:#x}",
-                            i,
-                            data.as_ptr(), data.len(),
-                            tls_data.as_mut_ptr(), tls_data.len()
-                        );
+                        // println!(
+                        //     "tls master {}: {:p}, {:#x}: {:p}, {:#x}",
+                        //     i,
+                        //     data.as_ptr(), data.len(),
+                        //     tls_data.as_mut_ptr(), tls_data.len()
+                        // );
 
                         tls_data.copy_from_slice(data);
                     } else {
diff --git a/src/platform/pte.rs b/src/platform/pte.rs
index 2a4bf5e9..2948f76d 100644
--- a/src/platform/pte.rs
+++ b/src/platform/pte.rs
@@ -68,11 +68,15 @@ unsafe extern "C" fn pte_osThreadShim(
     tls_masters_ptr: *mut Master,
     tls_masters_len: usize
 ) {
-    let mut tcb = Tcb::new(tls_size).unwrap();
-    tcb.masters_ptr = tls_masters_ptr;
-    tcb.masters_len = tls_masters_len;
-    tcb.copy_masters().unwrap();
-    tcb.activate();
+    // The kernel allocated TLS does not have masters set, so do not attempt to copy it.
+    // It will be copied by the kernel.
+    if ! tls_masters_ptr.is_null() {
+        let mut tcb = Tcb::new(tls_size).unwrap();
+        tcb.masters_ptr = tls_masters_ptr;
+        tcb.masters_len = tls_masters_len;
+        tcb.copy_masters().unwrap();
+        tcb.activate();
+    }
 
     // Wait until pte_osThreadStart
     pte_osMutexLock(mutex);
-- 
GitLab