1/*
2 * Copyright (C) 2005, 2008 Apple Inc. All rights reserved.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the NU
12 * Library General Public License for more details.
13 *
14 * You should have received a copy of the GNU Library General Public License
15 * along with this library; see the file COPYING.LIB.  If not, write to
16 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA
18 *
19 */
20
21#include "config.h"
22#include "JSLock.h"
23
24#include "Heap.h"
25#include "CallFrame.h"
26#include "JSObject.h"
27#include "ScopeChain.h"
28
29#if USE(PTHREADS)
30#include <pthread.h>
31#endif
32
33namespace JSC {
34
35// JSLock is only needed to support an obsolete execution model where JavaScriptCore
36// automatically protected against concurrent access from multiple threads.
37// So it's safe to disable it on non-mac platforms where we don't have native pthreads.
38#if ENABLE(JSC_MULTIPLE_THREADS) && (OS(DARWIN) || USE(PTHREADS))
39
40// Acquire this mutex before accessing lock-related data.
41static pthread_mutex_t JSMutex = PTHREAD_MUTEX_INITIALIZER;
42
43// Thread-specific key that tells whether a thread holds the JSMutex, and how many times it was taken recursively.
44pthread_key_t JSLockCount;
45
46static void createJSLockCount()
47{
48    pthread_key_create(&JSLockCount, 0);
49}
50
51pthread_once_t createJSLockCountOnce = PTHREAD_ONCE_INIT;
52
53// Lock nesting count.
54intptr_t JSLock::lockCount()
55{
56    pthread_once(&createJSLockCountOnce, createJSLockCount);
57
58    return reinterpret_cast<intptr_t>(pthread_getspecific(JSLockCount));
59}
60
61static void setLockCount(intptr_t count)
62{
63    ASSERT(count >= 0);
64    pthread_setspecific(JSLockCount, reinterpret_cast<void*>(count));
65}
66
67JSLock::JSLock(ExecState* exec)
68    : m_lockBehavior(exec->globalData().isSharedInstance() ? LockForReal : SilenceAssertionsOnly)
69{
70    lock(m_lockBehavior);
71}
72
73JSLock::JSLock(JSGlobalData* globalData)
74    : m_lockBehavior(globalData->isSharedInstance() ? LockForReal : SilenceAssertionsOnly)
75{
76    lock(m_lockBehavior);
77}
78
79void JSLock::lock(JSLockBehavior lockBehavior)
80{
81#ifdef NDEBUG
82    // Locking "not for real" is a debug-only feature.
83    if (lockBehavior == SilenceAssertionsOnly)
84        return;
85#endif
86
87    pthread_once(&createJSLockCountOnce, createJSLockCount);
88
89    intptr_t currentLockCount = lockCount();
90    if (!currentLockCount && lockBehavior == LockForReal) {
91        int result;
92        result = pthread_mutex_lock(&JSMutex);
93        ASSERT(!result);
94    }
95    setLockCount(currentLockCount + 1);
96}
97
98void JSLock::unlock(JSLockBehavior lockBehavior)
99{
100    ASSERT(lockCount());
101
102#ifdef NDEBUG
103    // Locking "not for real" is a debug-only feature.
104    if (lockBehavior == SilenceAssertionsOnly)
105        return;
106#endif
107
108    intptr_t newLockCount = lockCount() - 1;
109    setLockCount(newLockCount);
110    if (!newLockCount && lockBehavior == LockForReal) {
111        int result;
112        result = pthread_mutex_unlock(&JSMutex);
113        ASSERT(!result);
114    }
115}
116
117void JSLock::lock(ExecState* exec)
118{
119    lock(exec->globalData().isSharedInstance() ? LockForReal : SilenceAssertionsOnly);
120}
121
122void JSLock::unlock(ExecState* exec)
123{
124    unlock(exec->globalData().isSharedInstance() ? LockForReal : SilenceAssertionsOnly);
125}
126
127bool JSLock::currentThreadIsHoldingLock()
128{
129    pthread_once(&createJSLockCountOnce, createJSLockCount);
130    return !!pthread_getspecific(JSLockCount);
131}
132
133// This is fairly nasty.  We allow multiple threads to run on the same
134// context, and we do not require any locking semantics in doing so -
135// clients of the API may simply use the context from multiple threads
136// concurently, and assume this will work.  In order to make this work,
137// We lock the context when a thread enters, and unlock it when it leaves.
138// However we do not only unlock when the thread returns from its
139// entry point (evaluate script or call function), we also unlock the
140// context if the thread leaves JSC by making a call out to an external
141// function through a callback.
142//
143// All threads using the context share the same JS stack (the RegisterFile).
144// Whenever a thread calls into JSC it starts using the RegisterFile from the
145// previous 'high water mark' - the maximum point the stack has ever grown to
146// (returned by RegisterFile::end()).  So if a first thread calls out to a
147// callback, and a second thread enters JSC, then also exits by calling out
148// to a callback, we can be left with stackframes from both threads in the
149// RegisterFile.  As such, a problem may occur should the first thread's
150// callback complete first, and attempt to return to JSC.  Were we to allow
151// this to happen, and were its stack to grow further, then it may potentially
152// write over the second thread's call frames.
153//
154// In avoid JS stack corruption we enforce a policy of only ever allowing two
155// threads to use a JS context concurrently, and only allowing the second of
156// these threads to execute until it has completed and fully returned from its
157// outermost call into JSC.  We enforce this policy using 'lockDropDepth'.  The
158// first time a thread exits it will call DropAllLocks - which will do as expected
159// and drop locks allowing another thread to enter.  Should another thread, or the
160// same thread again, enter JSC (through evaluate script or call function), and exit
161// again through a callback, then the locks will not be dropped when DropAllLocks
162// is called (since lockDropDepth is non-zero).  Since this thread is still holding
163// the locks, only it will re able to re-enter JSC (either be returning from the
164// callback, or by re-entering through another call to evaulate script or call
165// function).
166//
167// This policy is slightly more restricive than it needs to be for correctness -
168// we could validly allow futher entries into JSC from other threads, we only
169// need ensure that callbacks return in the reverse chronological order of the
170// order in which they were made - though implementing the less restrictive policy
171// would likely increase complexity and overhead.
172//
173static unsigned lockDropDepth = 0;
174
175JSLock::DropAllLocks::DropAllLocks(ExecState* exec)
176    : m_lockBehavior(exec->globalData().isSharedInstance() ? LockForReal : SilenceAssertionsOnly)
177{
178    pthread_once(&createJSLockCountOnce, createJSLockCount);
179
180    if (lockDropDepth++) {
181        m_lockCount = 0;
182        return;
183    }
184
185    m_lockCount = JSLock::lockCount();
186    for (intptr_t i = 0; i < m_lockCount; i++)
187        JSLock::unlock(m_lockBehavior);
188}
189
190JSLock::DropAllLocks::DropAllLocks(JSLockBehavior JSLockBehavior)
191    : m_lockBehavior(JSLockBehavior)
192{
193    pthread_once(&createJSLockCountOnce, createJSLockCount);
194
195    if (lockDropDepth++) {
196        m_lockCount = 0;
197        return;
198    }
199
200    // It is necessary to drop even "unreal" locks, because having a non-zero lock count
201    // will prevent a real lock from being taken.
202
203    m_lockCount = JSLock::lockCount();
204    for (intptr_t i = 0; i < m_lockCount; i++)
205        JSLock::unlock(m_lockBehavior);
206}
207
208JSLock::DropAllLocks::~DropAllLocks()
209{
210    for (intptr_t i = 0; i < m_lockCount; i++)
211        JSLock::lock(m_lockBehavior);
212
213    --lockDropDepth;
214}
215
216#else // ENABLE(JSC_MULTIPLE_THREADS) && (OS(DARWIN) || USE(PTHREADS))
217
218JSLock::JSLock(ExecState*)
219    : m_lockBehavior(SilenceAssertionsOnly)
220{
221}
222
223// If threading support is off, set the lock count to a constant value of 1 so ssertions
224// that the lock is held don't fail
225intptr_t JSLock::lockCount()
226{
227    return 1;
228}
229
230bool JSLock::currentThreadIsHoldingLock()
231{
232    return true;
233}
234
235void JSLock::lock(JSLockBehavior)
236{
237}
238
239void JSLock::unlock(JSLockBehavior)
240{
241}
242
243void JSLock::lock(ExecState*)
244{
245}
246
247void JSLock::unlock(ExecState*)
248{
249}
250
251JSLock::DropAllLocks::DropAllLocks(ExecState*)
252{
253}
254
255JSLock::DropAllLocks::DropAllLocks(JSLockBehavior)
256{
257}
258
259JSLock::DropAllLocks::~DropAllLocks()
260{
261}
262
263#endif // ENABLE(JSC_MULTIPLE_THREADS) && (OS(DARWIN) || USE(PTHREADS))
264
265} // namespace JSC
266