@@ -57,13 +57,16 @@ __thread int _st_num_free_stacks = 0;
57
57
__thread int _st_randomize_stacks = 0 ;
58
58
59
59
static char * _st_new_stk_segment (int size );
60
+ static void _st_delete_stk_segment (char * vaddr , int size );
60
61
61
62
_st_stack_t * _st_stack_new (int stack_size )
62
63
{
63
64
_st_clist_t * qp ;
64
65
_st_stack_t * ts ;
65
66
int extra ;
66
-
67
+
68
+ /* If cache stack, we try to use stack from the cache list. */
69
+ #ifdef MD_CACHE_STACK
67
70
for (qp = _st_free_stacks .next ; qp != & _st_free_stacks ; qp = qp -> next ) {
68
71
ts = _ST_THREAD_STACK_PTR (qp );
69
72
if (ts -> stk_size >= stack_size ) {
@@ -75,11 +78,34 @@ _st_stack_t *_st_stack_new(int stack_size)
75
78
return ts ;
76
79
}
77
80
}
81
+ #endif
82
+
83
+ extra = _st_randomize_stacks ? _ST_PAGE_SIZE : 0 ;
84
+ /* If not cache stack, we will free all stack in the list, which contains the stack to be freed.
85
+ * Note that we should never directly free it at _st_stack_free, because it is still be used,
86
+ * and will cause crash. */
87
+ #ifndef MD_CACHE_STACK
88
+ for (qp = _st_free_stacks .next ; qp != & _st_free_stacks ;) {
89
+ ts = _ST_THREAD_STACK_PTR (qp );
90
+ /* Before qp is freed, move to next one, because the qp will be freed when free the ts. */
91
+ qp = qp -> next ;
92
+
93
+ ST_REMOVE_LINK (& ts -> links );
94
+ _st_num_free_stacks -- ;
95
+
96
+ #if defined(DEBUG ) && !defined(MD_NO_PROTECT )
97
+ mprotect (ts -> vaddr , REDZONE , PROT_READ | PROT_WRITE );
98
+ mprotect (ts -> stk_top + extra , REDZONE , PROT_READ | PROT_WRITE );
99
+ #endif
100
+
101
+ _st_delete_stk_segment (ts -> vaddr , ts -> vaddr_size );
102
+ free (ts );
103
+ }
104
+ #endif
78
105
79
106
/* Make a new thread stack object. */
80
107
if ((ts = (_st_stack_t * )calloc (1 , sizeof (_st_stack_t ))) == NULL )
81
108
return NULL ;
82
- extra = _st_randomize_stacks ? _ST_PAGE_SIZE : 0 ;
83
109
ts -> vaddr_size = stack_size + 2 * REDZONE + extra ;
84
110
ts -> vaddr = _st_new_stk_segment (ts -> vaddr_size );
85
111
if (!ts -> vaddr ) {
@@ -114,7 +140,7 @@ void _st_stack_free(_st_stack_t *ts)
114
140
{
115
141
if (!ts )
116
142
return ;
117
-
143
+
118
144
/* Put the stack on the free list */
119
145
ST_APPEND_LINK (& ts -> links , _st_free_stacks .prev );
120
146
_st_num_free_stacks ++ ;
@@ -152,8 +178,6 @@ static char *_st_new_stk_segment(int size)
152
178
}
153
179
154
180
155
- /* Not used */
156
- #if 0
157
181
void _st_delete_stk_segment (char * vaddr , int size )
158
182
{
159
183
#ifdef MALLOC_STACK
@@ -162,7 +186,6 @@ void _st_delete_stk_segment(char *vaddr, int size)
162
186
(void ) munmap (vaddr , size );
163
187
#endif
164
188
}
165
- #endif
166
189
167
190
int st_randomize_stacks (int on )
168
191
{
0 commit comments