• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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     pthread_mutex_lock(&fatal_msg_lock);
31 
32     if (msg == NULL) {
33         MUSL_LOGW("message null");
34         pthread_mutex_unlock(&fatal_msg_lock);
35         return;
36     }
37 
38     if (fatal_message != NULL) {
39         pthread_mutex_unlock(&fatal_msg_lock);
40         return;
41     }
42 
43     size_t size = sizeof(fatal_msg_t) + strlen(msg) + 1;
44     void *map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
45     if (map == MAP_FAILED) {
46         MUSL_LOGW("mmap failed");
47         fatal_message = NULL;
48         pthread_mutex_unlock(&fatal_msg_lock);
49         return;
50     }
51 
52     int ret = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, map, size, "fatal message");
53     if (ret < 0) {
54         MUSL_LOGW("prctl set vma failed");
55         munmap(map, size);
56         fatal_message = NULL;
57         pthread_mutex_unlock(&fatal_msg_lock);
58         return;
59     }
60 
61     fatal_message = (fatal_msg_t *)(map);
62     fatal_message->size = size;
63     strcpy(fatal_message->msg, msg);
64     pthread_mutex_unlock(&fatal_msg_lock);
65     return;
66 }
67 
get_fatal_message(void)68 fatal_msg_t *get_fatal_message(void)
69 {
70     return fatal_message;
71 }
72