From eee9a80baac785654e6fd446ddbcb5c9bbddc370 Mon Sep 17 00:00:00 2001
From: Mateusz Tabaka <tab.debugteam@gmail.com>
Date: Thu, 1 Oct 2020 11:14:10 +0200
Subject: [PATCH] Fix tls tests for dynamic linker

* load TLS segment for executable - while we can skip PT_LOAD for executable,
  we still have to load TLS segment.
* set TCB address based on if elf is position independent
---
 src/ld_so/linker.rs | 16 +++++++++++-----
 tests/Makefile      |  4 +---
 2 files changed, 12 insertions(+), 8 deletions(-)

diff --git a/src/ld_so/linker.rs b/src/ld_so/linker.rs
index 3f6b4d4c4..012d6f211 100644
--- a/src/ld_so/linker.rs
+++ b/src/ld_so/linker.rs
@@ -604,9 +604,6 @@ impl Linker {
             } else {
                 false
             };
-            if same_elf {
-                continue;
-            }
             let object = match lib.objects.get(*elf_name) {
                 Some(some) => some,
                 None => continue,
@@ -627,6 +624,9 @@ impl Linker {
 
                 match ph.p_type {
                     program_header::PT_LOAD => {
+                        if same_elf {
+                            continue;
+                        }
                         let obj_data = {
                             let range = ph.file_range();
                             match object.get(range.clone()) {
@@ -671,9 +671,15 @@ impl Linker {
                         } else {
                             ph.p_memsz
                         } as usize;
-
+                        let ptr = unsafe {
+                            if is_pie_enabled(elf) {
+                                mmap.as_ptr().add(ph.p_vaddr as usize)
+                            } else {
+                                ph.p_vaddr as *const u8
+                            }
+                        };
                         let mut tcb_master = Master {
-                            ptr: unsafe { mmap.as_ptr().add(ph.p_vaddr as usize - base_addr) },
+                            ptr: ptr,
                             len: ph.p_filesz as usize,
                             offset: tls_size - valign,
                         };
diff --git a/tests/Makefile b/tests/Makefile
index 77113745e..ff866d3f0 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -73,6 +73,7 @@ EXPECT_NAMES=\
 	time/mktime \
 	time/strftime \
 	time/time \
+	tls \
 	unistd/access \
 	unistd/brk \
 	unistd/dup \
@@ -121,9 +122,6 @@ STATIC_ONLY_NAMES=\
 # need to call fini in ld_so's _start
 STATIC_ONLY_NAMES+=\
 	destructor \
-# comparison issue
-STATIC_ONLY_NAMES+=\
-	tls \
 # issues with linking optarg, optind etc.
 STATIC_ONLY_NAMES+=\
 	unistd/getopt \
-- 
GitLab