Elliott Hughes | 42b2c6a | 2013-02-07 10:14:39 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2013 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #ifndef KERNEL_ARGUMENT_BLOCK_H |
| 18 | #define KERNEL_ARGUMENT_BLOCK_H |
| 19 | |
| 20 | #include <elf.h> |
| 21 | #include <stdint.h> |
| 22 | #include <sys/auxv.h> |
| 23 | |
| 24 | // When the kernel starts the dynamic linker, it passes a pointer to a block |
| 25 | // of memory containing argc, the argv array, the environment variable array, |
| 26 | // and the array of ELF aux vectors. This class breaks that block up into its |
| 27 | // constituents for easy access. |
| 28 | class KernelArgumentBlock { |
| 29 | public: |
| 30 | KernelArgumentBlock(void* raw_args) { |
| 31 | uint32_t* args = reinterpret_cast<uint32_t*>(raw_args); |
| 32 | argc = static_cast<int>(*args); |
| 33 | argv = reinterpret_cast<char**>(args + 1); |
| 34 | envp = argv + argc + 1; |
| 35 | |
| 36 | // Skip over all environment variable definitions to find aux vector. |
| 37 | // The end of the environment block is marked by two NULL pointers. |
| 38 | char** p = envp; |
| 39 | while (*p != NULL) { |
| 40 | ++p; |
| 41 | } |
| 42 | ++p; // Skip second NULL; |
| 43 | |
| 44 | auxv = reinterpret_cast<Elf32_auxv_t*>(p); |
| 45 | } |
| 46 | |
| 47 | // Similar to ::getauxval but doesn't require the libc global variables to be set up, |
| 48 | // so it's safe to call this really early on. This function also lets you distinguish |
| 49 | // between the inability to find the given type and its value just happening to be 0. |
| 50 | unsigned long getauxval(unsigned long type, bool* found_match = NULL) { |
| 51 | for (Elf32_auxv_t* v = auxv; v->a_type != AT_NULL; ++v) { |
| 52 | if (v->a_type == type) { |
| 53 | if (found_match != NULL) { |
| 54 | *found_match = true; |
| 55 | } |
| 56 | return v->a_un.a_val; |
| 57 | } |
| 58 | } |
| 59 | if (found_match != NULL) { |
| 60 | *found_match = false; |
| 61 | } |
| 62 | return 0; |
| 63 | } |
| 64 | |
| 65 | int argc; |
| 66 | char** argv; |
| 67 | char** envp; |
| 68 | Elf32_auxv_t* auxv; |
| 69 | |
| 70 | private: |
| 71 | // Disallow copy and assignment. |
| 72 | KernelArgumentBlock(const KernelArgumentBlock&); |
| 73 | void operator=(const KernelArgumentBlock&); |
| 74 | }; |
| 75 | |
| 76 | #endif // KERNEL_ARGUMENT_BLOCK_H |