• 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 <stdio.h>
17 #include <malloc.h>
18 #include <stdlib.h>
19 #include <pthread.h>
20 #include <stdint.h>
21 #include <memory.h>
22 #include <unistd.h>
23 
24 #include "test-malloc-api-common.h"
25 
26 #define BARRIER_HEIGHT 2
27 
28 pthread_barrier_t routine_disabled;
29 pthread_barrier_t routine_allocated;
30 
31 const size_t SLEEP_TIME_SECONDS = 2;
32 
disable_routine(void * vargp)33 void *disable_routine(void *vargp)
34 {
35 	malloc_disable();
36 	pthread_barrier_wait(&routine_disabled);
37 	sleep(SLEEP_TIME_SECONDS);
38 	malloc_enable();
39 	pthread_barrier_wait(&routine_allocated);
40 	return NULL;
41 }
42 
test_malloc_while_disabled(void)43 int test_malloc_while_disabled(void)
44 {
45 	int ret = 0;
46 	pthread_barrier_init(&routine_disabled, NULL, BARRIER_HEIGHT);
47 	pthread_barrier_init(&routine_allocated, NULL, BARRIER_HEIGHT);
48 	pthread_t thread_id;
49 	pthread_create(&thread_id, NULL, disable_routine, NULL);
50 	pthread_barrier_wait(&routine_disabled);
51 	time_t start = time(0);
52 	int *x = malloc(sizeof(int));
53 	time_t end = time(0);
54 	pthread_barrier_wait(&routine_allocated);
55 	size_t seconds = end - start;
56 	if (seconds < SLEEP_TIME_SECONDS) {
57 		ret = -1;
58 	}
59 	free(x);
60 	pthread_join(thread_id, NULL);
61 
62 	return ret;
63 }
64 
main()65 int main()
66 {
67 	int ret = 0;
68 
69 	ret = check_and_report("Testing malloc while disabled", test_malloc_while_disabled);
70 
71 	return ret;
72 }
73