The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

461 lines
12KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE 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
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. #include "linuxincludes.h"
  24. #include <dlfcn.h>
  25. #include <sys/file.h>
  26. #include "../../../src/juce_core/basics/juce_StandardHeader.h"
  27. BEGIN_JUCE_NAMESPACE
  28. #include "../../../src/juce_core/threads/juce_CriticalSection.h"
  29. #include "../../../src/juce_core/threads/juce_WaitableEvent.h"
  30. #include "../../../src/juce_core/threads/juce_InterProcessLock.h"
  31. #include "../../../src/juce_core/threads/juce_Thread.h"
  32. #include "../../../src/juce_core/threads/juce_Process.h"
  33. #include "../../../src/juce_core/io/files/juce_File.h"
  34. #include "../../../src/juce_core/basics/juce_SystemStats.h"
  35. #ifndef CPU_ISSET
  36. #undef SUPPORT_AFFINITIES
  37. #endif
  38. //==============================================================================
  39. void JUCE_API juce_threadEntryPoint (void*);
  40. void* threadEntryProc (void* value) throw()
  41. {
  42. // New threads start off as root when running suid
  43. Process::lowerPrivilege();
  44. juce_threadEntryPoint (value);
  45. return 0;
  46. }
  47. void* juce_createThread (void* userData) throw()
  48. {
  49. pthread_t handle = 0;
  50. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  51. {
  52. pthread_detach (handle);
  53. return (void*)handle;
  54. }
  55. return 0;
  56. }
  57. void juce_killThread (void* handle) throw()
  58. {
  59. if (handle != 0)
  60. pthread_cancel ((pthread_t)handle);
  61. }
  62. void juce_setCurrentThreadName (const String& /*name*/) throw()
  63. {
  64. }
  65. int Thread::getCurrentThreadId() throw()
  66. {
  67. return (int) pthread_self();
  68. }
  69. /*
  70. * This is all a bit non-ideal... the trouble is that on Linux you
  71. * need to call setpriority to affect the dynamic priority for
  72. * non-realtime processes, but this requires the pid, which is not
  73. * accessible from the pthread_t. We could get it by calling getpid
  74. * once each thread has started, but then we would need a list of
  75. * running threads etc etc.
  76. * Also there is no such thing as IDLE priority on Linux.
  77. * For the moment, map idle, low and normal process priorities to
  78. * SCHED_OTHER, with the thread priority ignored for these classes.
  79. * Map high priority processes to the lower half of the SCHED_RR
  80. * range, and realtime to the upper half
  81. */
  82. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  83. // priority of the current thread
  84. void juce_setThreadPriority (void* handle, int priority) throw()
  85. {
  86. struct sched_param param;
  87. int policy, maxp, minp, pri;
  88. if (handle == 0)
  89. handle = (void*) pthread_self();
  90. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  91. && policy != SCHED_OTHER)
  92. {
  93. minp = sched_get_priority_min(policy);
  94. maxp = sched_get_priority_max(policy);
  95. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  96. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  97. // Realtime process priority
  98. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  99. else
  100. // High process priority
  101. param.__sched_priority = minp + pri;
  102. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  103. pthread_setschedparam ((pthread_t) handle, policy, &param);
  104. }
  105. }
  106. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  107. {
  108. #if SUPPORT_AFFINITIES
  109. cpu_set_t affinity;
  110. CPU_ZERO (&affinity);
  111. for (int i = 0; i < 32; ++i)
  112. if ((affinityMask & (1 << i)) != 0)
  113. CPU_SET (i, &affinity);
  114. /*
  115. N.B. If this line causes a compile error, then you've probably not got the latest
  116. version of glibc installed.
  117. If you don't want to update your copy of glibc and don't care about cpu affinities,
  118. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  119. from the linuxincludes.h file.
  120. */
  121. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  122. sched_yield();
  123. #else
  124. /* affinities aren't supported because either the appropriate header files weren't found,
  125. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  126. */
  127. jassertfalse
  128. #endif
  129. }
  130. void Thread::yield() throw()
  131. {
  132. sched_yield();
  133. }
  134. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  135. {
  136. struct timespec time;
  137. time.tv_sec = millisecs / 1000;
  138. time.tv_nsec = (millisecs % 1000) * 1000000;
  139. nanosleep (&time, 0);
  140. }
  141. //==============================================================================
  142. CriticalSection::CriticalSection() throw()
  143. {
  144. pthread_mutexattr_t atts;
  145. pthread_mutexattr_init (&atts);
  146. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  147. pthread_mutex_init (&internal, &atts);
  148. }
  149. CriticalSection::~CriticalSection() throw()
  150. {
  151. pthread_mutex_destroy (&internal);
  152. }
  153. void CriticalSection::enter() const throw()
  154. {
  155. pthread_mutex_lock (&internal);
  156. }
  157. bool CriticalSection::tryEnter() const throw()
  158. {
  159. return pthread_mutex_trylock (&internal) == 0;
  160. }
  161. void CriticalSection::exit() const throw()
  162. {
  163. pthread_mutex_unlock (&internal);
  164. }
  165. //==============================================================================
  166. struct EventStruct
  167. {
  168. pthread_cond_t condition;
  169. pthread_mutex_t mutex;
  170. bool triggered;
  171. };
  172. WaitableEvent::WaitableEvent() throw()
  173. {
  174. EventStruct* const es = new EventStruct();
  175. es->triggered = false;
  176. pthread_cond_init (&es->condition, 0);
  177. pthread_mutex_init (&es->mutex, 0);
  178. internal = es;
  179. }
  180. WaitableEvent::~WaitableEvent() throw()
  181. {
  182. EventStruct* const es = (EventStruct*)internal;
  183. pthread_cond_destroy (&es->condition);
  184. pthread_mutex_destroy (&es->mutex);
  185. delete es;
  186. }
  187. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  188. {
  189. EventStruct* const es = (EventStruct*)internal;
  190. bool ok = true;
  191. pthread_mutex_lock (&es->mutex);
  192. if (! es->triggered)
  193. {
  194. if (timeOutMillisecs < 0)
  195. {
  196. pthread_cond_wait (&es->condition, &es->mutex);
  197. }
  198. else
  199. {
  200. struct timespec time;
  201. struct timeval t;
  202. int timeout = 0;
  203. gettimeofday (&t, 0);
  204. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  205. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  206. while (time.tv_nsec >= 1000000000)
  207. {
  208. time.tv_nsec -= 1000000000;
  209. time.tv_sec++;
  210. }
  211. while (! timeout)
  212. {
  213. timeout = pthread_cond_timedwait (&es->condition, &es->mutex, &time);
  214. if (! timeout)
  215. // Success
  216. break;
  217. if (timeout == EINTR)
  218. // Go round again
  219. timeout = 0;
  220. }
  221. }
  222. ok = es->triggered;
  223. }
  224. es->triggered = false;
  225. pthread_mutex_unlock (&es->mutex);
  226. return ok;
  227. }
  228. void WaitableEvent::signal() const throw()
  229. {
  230. EventStruct* const es = (EventStruct*)internal;
  231. pthread_mutex_lock (&es->mutex);
  232. es->triggered = true;
  233. pthread_cond_signal (&es->condition);
  234. pthread_mutex_unlock (&es->mutex);
  235. }
  236. void WaitableEvent::reset() const throw()
  237. {
  238. EventStruct* const es = (EventStruct*)internal;
  239. pthread_mutex_lock (&es->mutex);
  240. es->triggered = false;
  241. pthread_mutex_unlock (&es->mutex);
  242. }
  243. //==============================================================================
  244. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  245. void Process::setPriority (ProcessPriority prior)
  246. {
  247. struct sched_param param;
  248. int policy, maxp, minp;
  249. const int p = (int) prior;
  250. if (p <= 1)
  251. policy = SCHED_OTHER;
  252. else
  253. policy = SCHED_RR;
  254. minp = sched_get_priority_min (policy);
  255. maxp = sched_get_priority_max (policy);
  256. if (p < 2)
  257. param.__sched_priority = 0;
  258. else if (p == 2 )
  259. // Set to middle of lower realtime priority range
  260. param.__sched_priority = minp + (maxp - minp) / 4;
  261. else
  262. // Set to middle of higher realtime priority range
  263. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  264. pthread_setschedparam (pthread_self(), policy, &param);
  265. }
  266. void Process::terminate()
  267. {
  268. exit (0);
  269. }
  270. void Process::raisePrivilege()
  271. {
  272. // If running suid root, change effective user
  273. // to root
  274. if (geteuid() != 0 && getuid() == 0)
  275. {
  276. setreuid (geteuid(), getuid());
  277. setregid (getegid(), getgid());
  278. }
  279. }
  280. void Process::lowerPrivilege()
  281. {
  282. // If runing suid root, change effective user
  283. // back to real user
  284. if (geteuid() == 0 && getuid() != 0)
  285. {
  286. setreuid (geteuid(), getuid());
  287. setregid (getegid(), getgid());
  288. }
  289. }
  290. #if JUCE_BUILD_GUI_CLASSES
  291. void* Process::loadDynamicLibrary (const String& name)
  292. {
  293. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  294. }
  295. void Process::freeDynamicLibrary (void* handle)
  296. {
  297. dlclose(handle);
  298. }
  299. void* Process::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  300. {
  301. return dlsym (libraryHandle, (const char*) procedureName);
  302. }
  303. #endif
  304. //==============================================================================
  305. InterProcessLock::InterProcessLock (const String& name_) throw()
  306. : internal (0),
  307. name (name_),
  308. reentrancyLevel (0)
  309. {
  310. const File tempDir (File::getSpecialLocation (File::tempDirectory));
  311. const File temp (tempDir.getChildFile (name));
  312. temp.create();
  313. internal = (void*) open (temp.getFullPathName().toUTF8(), 'a');
  314. }
  315. InterProcessLock::~InterProcessLock() throw()
  316. {
  317. while (reentrancyLevel > 0)
  318. this->exit();
  319. #if JUCE_64BIT
  320. close ((long long) internal);
  321. #else
  322. close ((int) internal);
  323. #endif
  324. }
  325. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  326. {
  327. if (internal == 0)
  328. return false;
  329. if (reentrancyLevel != 0)
  330. return true;
  331. if (timeOutMillisecs <= 0)
  332. {
  333. if (flock ((long) internal,
  334. timeOutMillisecs < 0 ? LOCK_EX
  335. : (LOCK_EX | LOCK_NB)) == 0)
  336. {
  337. ++reentrancyLevel;
  338. return true;
  339. }
  340. }
  341. else
  342. {
  343. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  344. for (;;)
  345. {
  346. if (flock ((long) internal, LOCK_EX | LOCK_NB) == 0)
  347. {
  348. ++reentrancyLevel;
  349. return true;
  350. }
  351. if (Time::currentTimeMillis() >= endTime)
  352. break;
  353. Thread::sleep (10);
  354. }
  355. }
  356. return false;
  357. }
  358. void InterProcessLock::exit() throw()
  359. {
  360. if (reentrancyLevel > 0 && internal != 0)
  361. {
  362. --reentrancyLevel;
  363. const int result = flock ((long) internal, LOCK_UN);
  364. (void) result;
  365. jassert (result == 0);
  366. }
  367. }
  368. END_JUCE_NAMESPACE