start.rs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // Start code adapted from https://gitlab.redox-os.org/redox-os/relibc/blob/master/src/start.rs
  2. use alloc::{
  3. borrow::ToOwned,
  4. boxed::Box,
  5. collections::BTreeMap,
  6. string::{String, ToString},
  7. vec::Vec,
  8. };
  9. use crate::{
  10. c_str::CStr,
  11. header::{sys_auxv::AT_NULL, unistd},
  12. platform::{new_mspace, types::c_char},
  13. start::Stack,
  14. sync::mutex::Mutex,
  15. ALLOCATOR,
  16. };
  17. use super::{
  18. access::accessible,
  19. debug::_r_debug,
  20. linker::{Linker, DSO, PATH_SEP},
  21. tcb::Tcb,
  22. };
  23. use crate::header::sys_auxv::{AT_ENTRY, AT_PHDR};
  24. unsafe fn get_argv(mut ptr: *const usize) -> (Vec<String>, *const usize) {
  25. //traverse the stack and collect argument vector
  26. let mut argv = Vec::new();
  27. while *ptr != 0 {
  28. let arg = *ptr;
  29. match CStr::from_ptr(arg as *const c_char).to_str() {
  30. Ok(arg_str) => argv.push(arg_str.to_owned()),
  31. _ => {
  32. eprintln!("ld.so: failed to parse argv[{}]", argv.len());
  33. unistd::_exit(1);
  34. loop {}
  35. }
  36. }
  37. ptr = ptr.add(1);
  38. }
  39. return (argv, ptr);
  40. }
  41. unsafe fn get_env(mut ptr: *const usize) -> (BTreeMap<String, String>, *const usize) {
  42. //traverse the stack and collect argument environment variables
  43. let mut envs = BTreeMap::new();
  44. while *ptr != 0 {
  45. let env = *ptr;
  46. if let Ok(arg_str) = CStr::from_ptr(env as *const c_char).to_str() {
  47. let mut parts = arg_str.splitn(2, '=');
  48. if let Some(key) = parts.next() {
  49. if let Some(value) = parts.next() {
  50. envs.insert(key.to_owned(), value.to_owned());
  51. }
  52. }
  53. }
  54. ptr = ptr.add(1);
  55. }
  56. return (envs, ptr);
  57. }
  58. unsafe fn get_auxv(mut ptr: *const usize) -> BTreeMap<usize, usize> {
  59. //traverse the stack and collect argument environment variables
  60. let mut auxv = BTreeMap::new();
  61. while *ptr != AT_NULL {
  62. let kind = *ptr;
  63. ptr = ptr.add(1);
  64. let value = *ptr;
  65. ptr = ptr.add(1);
  66. auxv.insert(kind, value);
  67. }
  68. return auxv;
  69. }
  70. unsafe fn adjust_stack(sp: &'static mut Stack) {
  71. let mut argv = sp.argv() as *mut usize;
  72. // Move arguments
  73. loop {
  74. let next_argv = argv.add(1);
  75. let arg = *next_argv;
  76. *argv = arg;
  77. argv = next_argv;
  78. if arg == 0 {
  79. break;
  80. }
  81. }
  82. // Move environment
  83. loop {
  84. let next_argv = argv.add(1);
  85. let arg = *next_argv;
  86. *argv = arg;
  87. argv = next_argv;
  88. if arg == 0 {
  89. break;
  90. }
  91. if let Ok(arg_str) = CStr::from_ptr(arg as *const c_char).to_str() {
  92. let mut parts = arg_str.splitn(2, '=');
  93. if let Some(key) = parts.next() {
  94. if let Some(value) = parts.next() {
  95. if let "LD_LIBRARY_PATH" = key {
  96. //library_path = value
  97. }
  98. }
  99. }
  100. }
  101. }
  102. // Move auxiliary vectors
  103. loop {
  104. let next_argv = argv.add(1);
  105. let kind = *next_argv;
  106. *argv = kind;
  107. argv = next_argv;
  108. let next_argv = argv.add(1);
  109. let value = *next_argv;
  110. *argv = value;
  111. argv = next_argv;
  112. if kind == 0 {
  113. break;
  114. }
  115. }
  116. sp.argc -= 1;
  117. }
  118. fn resolve_path_name(
  119. name_or_path: &str,
  120. envs: &BTreeMap<String, String>,
  121. ) -> Option<(String, String)> {
  122. if accessible(name_or_path, unistd::F_OK) == 0 {
  123. return Some((
  124. name_or_path.to_string(),
  125. name_or_path
  126. .split("/")
  127. .collect::<Vec<&str>>()
  128. .last()
  129. .unwrap()
  130. .to_string(),
  131. ));
  132. }
  133. if name_or_path.split("/").collect::<Vec<&str>>().len() != 1 {
  134. return None;
  135. }
  136. let env_path = envs.get("PATH")?;
  137. for part in env_path.split(PATH_SEP) {
  138. let path = if part.is_empty() {
  139. format!("./{}", name_or_path)
  140. } else {
  141. format!("{}/{}", part, name_or_path)
  142. };
  143. if accessible(&path, unistd::F_OK) == 0 {
  144. return Some((path.to_string(), name_or_path.to_string()));
  145. }
  146. }
  147. None
  148. }
  149. #[no_mangle]
  150. pub extern "C" fn relibc_ld_so_start(sp: &'static mut Stack, ld_entry: usize) -> usize {
  151. // First thing we initialize the mspace
  152. ALLOCATOR.set_book_keeper(new_mspace());
  153. // next we get the arguments, the environment, and the auxilary vector
  154. let (argv, envs, auxv) = unsafe {
  155. let argv_start = sp.argv() as *mut usize;
  156. let (argv, argv_end) = get_argv(argv_start);
  157. let (envs, envs_end) = get_env(argv_end.add(1));
  158. let auxv = get_auxv(envs_end.add(1));
  159. (argv, envs, auxv)
  160. };
  161. let is_manual = if let Some(img_entry) = auxv.get(&AT_ENTRY) {
  162. *img_entry == ld_entry
  163. } else {
  164. true
  165. };
  166. // we might need global lock for this kind of stuff
  167. unsafe {
  168. _r_debug.r_ldbase = ld_entry;
  169. }
  170. // Some variables that will be overridden by environment and auxiliary vectors
  171. let ld_library_path = envs.get("LD_LIBRARY_PATH").map(|s| s.to_owned());
  172. let name_or_path = if is_manual {
  173. // ld.so is run directly by user and not via execve() or similar systemcall
  174. println!("argv: {:#?}", argv);
  175. println!("envs: {:#?}", envs);
  176. println!("auxv: {:#x?}", auxv);
  177. if sp.argc < 2 {
  178. eprintln!("ld.so [executable] [arguments...]");
  179. unistd::_exit(1);
  180. loop {}
  181. }
  182. unsafe { adjust_stack(sp) };
  183. argv[1].to_string()
  184. } else {
  185. argv[0].to_string()
  186. };
  187. let (path, name) = match resolve_path_name(&name_or_path, &envs) {
  188. Some((p, n)) => (p, n),
  189. None => {
  190. eprintln!("ld.so: failed to locate '{}'", name_or_path);
  191. unistd::_exit(1);
  192. loop {}
  193. }
  194. };
  195. // if we are not running in manual mode, then the main
  196. // program is already loaded by the kernel and we want
  197. // to use it. on redox, we treat it the same.
  198. let program = {
  199. let mut pr = None;
  200. if !is_manual && cfg!(not(target_os = "redox")) {
  201. let phdr = *auxv.get(&AT_PHDR).unwrap();
  202. if phdr != 0 {
  203. let p = DSO {
  204. name: path.to_owned(),
  205. entry_point: *auxv.get(&AT_ENTRY).unwrap(),
  206. // The 0x40 is the size of Elf header not a good idea for different bit size
  207. // compatiablility but it will always work on 64 bit systems,
  208. base_addr: phdr - 0x40,
  209. };
  210. pr = Some(p);
  211. }
  212. }
  213. pr
  214. };
  215. let mut linker = Linker::new(ld_library_path, false);
  216. match linker.load(&path, &path) {
  217. Ok(()) => (),
  218. Err(err) => {
  219. eprintln!("ld.so: failed to load '{}': {}", path, err);
  220. unistd::_exit(1);
  221. loop {}
  222. }
  223. }
  224. let entry = match linker.link(Some(&path), program, None) {
  225. Ok(ok) => match ok {
  226. Some(some) => some,
  227. None => {
  228. eprintln!("ld.so: failed to link '{}': missing entry", path);
  229. unistd::_exit(1);
  230. loop {}
  231. }
  232. },
  233. Err(err) => {
  234. eprintln!("ld.so: failed to link '{}': {}", path, err);
  235. unistd::_exit(1);
  236. loop {}
  237. }
  238. };
  239. if let Err(e) = linker.run_init(None) {
  240. eprintln!("ld.so: failed to run .init_array");
  241. unistd::_exit(1);
  242. loop {}
  243. }
  244. if let Some(tcb) = unsafe { Tcb::current() } {
  245. tcb.linker_ptr = Box::into_raw(Box::new(Mutex::new(linker)));
  246. tcb.mspace = ALLOCATOR.get_book_keeper();
  247. }
  248. if is_manual {
  249. eprintln!("ld.so: entry '{}': {:#x}", path, entry);
  250. }
  251. entry
  252. }