1 /*
2  * Copyright (C) 2022 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 #include <err.h>
18 #include <errno.h>
19 #include <kernel/thread.h>
20 #include <stdlib.h>
21 #include <trusty/libc_state.h>
22 #include "locale_impl.h"
23 
libc_state_create(void)24 static struct libc_state* libc_state_create(void) {
25     struct libc_state* state = calloc(1, sizeof(struct libc_state));
26     if (state != NULL) {
27         state->errno_val = 0;
28         state->locale = C_LOCALE;
29     }
30     return state;
31 }
32 
libc_state_thread_init(thread_t * t)33 int libc_state_thread_init(thread_t* t) {
34     if (t == NULL) {
35         return ERR_INVALID_ARGS;
36     }
37     struct libc_state* state = libc_state_create();
38     if (state == NULL) {
39         return ERR_NO_RESOURCES;
40     }
41     thread_tls_set(t, TLS_ENTRY_LIBC, (uintptr_t)state);
42     return NO_ERROR;
43 }
44 
libc_state_thread_free(thread_t * t)45 int libc_state_thread_free(thread_t* t) {
46     if (t == NULL) {
47         return ERR_INVALID_ARGS;
48     }
49     struct libc_state* state =
50             (struct libc_state*)thread_tls_get(t, TLS_ENTRY_LIBC);
51     ASSERT(state);
52     free(state);
53 
54     /* Replace the old TLS entry with NULL to remove the dangling pointer and
55      * catch double frees */
56     thread_tls_set(t, TLS_ENTRY_LIBC, (uintptr_t)NULL);
57 
58     return NO_ERROR;
59 }
60 
current_thread_libc_state(void)61 struct libc_state* current_thread_libc_state(void) {
62     return (struct libc_state*)tls_get(TLS_ENTRY_LIBC);
63 }
64 
__errno_location(void)65 int* __errno_location(void) {
66     struct libc_state* state = current_thread_libc_state();
67     DEBUG_ASSERT(state);
68     return &state->errno_val;
69 }
70 
71 weak_alias(__errno_location, ___errno_location);
72