1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <info/fatal_message.h>
17
18 #include <pthread.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <sys/mman.h>
22 #include <sys/prctl.h>
23 #include "musl_log.h"
24
25 static pthread_mutex_t fatal_msg_lock = PTHREAD_MUTEX_INITIALIZER;
26 static fatal_msg_t *fatal_message = NULL;
27
set_fatal_message(const char * msg)28 void set_fatal_message(const char *msg)
29 {
30 if (pthread_mutex_trylock(&fatal_msg_lock) != 0) {
31 return;
32 }
33
34 if (msg == NULL) {
35 MUSL_LOGW("message null");
36 pthread_mutex_unlock(&fatal_msg_lock);
37 return;
38 }
39
40 if (fatal_message != NULL) {
41 pthread_mutex_unlock(&fatal_msg_lock);
42 return;
43 }
44
45 size_t size = sizeof(fatal_msg_t) + strlen(msg) + 1;
46 void *map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
47 if (map == MAP_FAILED) {
48 MUSL_LOGW("mmap failed");
49 fatal_message = NULL;
50 pthread_mutex_unlock(&fatal_msg_lock);
51 return;
52 }
53
54 int ret = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, map, size, "fatal message");
55 if (ret < 0) {
56 MUSL_LOGW("prctl set vma failed");
57 munmap(map, size);
58 fatal_message = NULL;
59 pthread_mutex_unlock(&fatal_msg_lock);
60 return;
61 }
62
63 fatal_message = (fatal_msg_t *)(map);
64 fatal_message->size = size;
65 strcpy(fatal_message->msg, msg);
66 pthread_mutex_unlock(&fatal_msg_lock);
67 return;
68 }
69
get_fatal_message(void)70 fatal_msg_t *get_fatal_message(void)
71 {
72 return fatal_message;
73 }
74