1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
CriticalSection::CriticalSection() noexcept
{
pthread_mutexattr_t atts;
pthread_mutexattr_init (&atts);
pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
#if ! JUCE_ANDROID
pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
#endif
pthread_mutex_init (&lock, &atts);
pthread_mutexattr_destroy (&atts);
}
CriticalSection::~CriticalSection() noexcept { pthread_mutex_destroy (&lock); }
void CriticalSection::enter() const noexcept { pthread_mutex_lock (&lock); }
bool CriticalSection::tryEnter() const noexcept { return pthread_mutex_trylock (&lock) == 0; }
void CriticalSection::exit() const noexcept { pthread_mutex_unlock (&lock); }
//==============================================================================
void JUCE_CALLTYPE Thread::sleep (int millisecs)
{
struct timespec time;
time.tv_sec = millisecs / 1000;
time.tv_nsec = (millisecs % 1000) * 1000000;
nanosleep (&time, nullptr);
}
void JUCE_CALLTYPE Process::terminate()
{
#if JUCE_ANDROID
_exit (EXIT_FAILURE);
#else
std::_Exit (EXIT_FAILURE);
#endif
}
#if JUCE_MAC || JUCE_LINUX || JUCE_BSD
bool Process::setMaxNumberOfFileHandles (int newMaxNumber) noexcept
{
rlimit lim;
if (getrlimit (RLIMIT_NOFILE, &lim) == 0)
{
if (newMaxNumber <= 0 && lim.rlim_cur == RLIM_INFINITY && lim.rlim_max == RLIM_INFINITY)
return true;
if (newMaxNumber > 0 && lim.rlim_cur >= (rlim_t) newMaxNumber)
return true;
}
lim.rlim_cur = lim.rlim_max = newMaxNumber <= 0 ? RLIM_INFINITY : (rlim_t) newMaxNumber;
return setrlimit (RLIMIT_NOFILE, &lim) == 0;
}
struct MaxNumFileHandlesInitialiser
{
MaxNumFileHandlesInitialiser() noexcept
{
#ifndef JUCE_PREFERRED_MAX_FILE_HANDLES
enum { JUCE_PREFERRED_MAX_FILE_HANDLES = 8192 };
#endif
// Try to give our app a decent number of file handles by default
if (! Process::setMaxNumberOfFileHandles (0))
{
for (int num = JUCE_PREFERRED_MAX_FILE_HANDLES; num > 256; num -= 1024)
if (Process::setMaxNumberOfFileHandles (num))
break;
}
}
};
static MaxNumFileHandlesInitialiser maxNumFileHandlesInitialiser;
#endif
//==============================================================================
#if JUCE_ALLOW_STATIC_NULL_VARIABLES
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
const juce_wchar File::separator = '/';
const StringRef File::separatorString ("/");
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
#endif
juce_wchar File::getSeparatorChar() { return '/'; }
StringRef File::getSeparatorString() { return "/"; }
//==============================================================================
File File::getCurrentWorkingDirectory()
{
HeapBlock<char> heapBuffer;
char localBuffer[1024];
auto cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
size_t bufferSize = 4096;
while (cwd == nullptr && errno == ERANGE)
{
heapBuffer.malloc (bufferSize);
cwd = getcwd (heapBuffer, bufferSize - 1);
bufferSize += 1024;
}
return File (CharPointer_UTF8 (cwd));
}
bool File::setAsCurrentWorkingDirectory() const
{
return chdir (getFullPathName().toUTF8()) == 0;
}
//==============================================================================
// The unix siginterrupt function is deprecated - this does the same job.
int juce_siginterrupt (int sig, int flag)
{
#if JUCE_WASM
ignoreUnused (sig, flag);
return 0;
#else
#if JUCE_ANDROID
using juce_sigactionflags_type = unsigned long;
#else
using juce_sigactionflags_type = int;
#endif
struct ::sigaction act;
(void) ::sigaction (sig, nullptr, &act);
if (flag != 0)
act.sa_flags &= static_cast<juce_sigactionflags_type> (~SA_RESTART);
else
act.sa_flags |= static_cast<juce_sigactionflags_type> (SA_RESTART);
return ::sigaction (sig, &act, nullptr);
#endif
}
//==============================================================================
namespace
{
#if JUCE_LINUX || (JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T) // (this iOS stuff is to avoid a simulator bug)
using juce_statStruct = struct stat64;
#define JUCE_STAT stat64
#else
using juce_statStruct = struct stat;
#define JUCE_STAT stat
#endif
bool juce_stat (const String& fileName, juce_statStruct& info)
{
return fileName.isNotEmpty()
&& JUCE_STAT (fileName.toUTF8(), &info) == 0;
}
#if ! JUCE_WASM
// if this file doesn't exist, find a parent of it that does..
bool juce_doStatFS (File f, struct statfs& result)
{
for (int i = 5; --i >= 0;)
{
if (f.exists())
break;
f = f.getParentDirectory();
}
return statfs (f.getFullPathName().toUTF8(), &result) == 0;
}
#if JUCE_MAC || JUCE_IOS
static int64 getCreationTime (const juce_statStruct& s) noexcept { return (int64) s.st_birthtime; }
#else
static int64 getCreationTime (const juce_statStruct& s) noexcept { return (int64) s.st_ctime; }
#endif
void updateStatInfoForFile (const String& path, bool* isDir, int64* fileSize,
Time* modTime, Time* creationTime, bool* isReadOnly)
{
if (isDir != nullptr || fileSize != nullptr || modTime != nullptr || creationTime != nullptr)
{
juce_statStruct info;
const bool statOk = juce_stat (path, info);
if (isDir != nullptr) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
if (fileSize != nullptr) *fileSize = statOk ? (int64) info.st_size : 0;
if (modTime != nullptr) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
if (creationTime != nullptr) *creationTime = Time (statOk ? getCreationTime (info) * 1000 : 0);
}
if (isReadOnly != nullptr)
*isReadOnly = access (path.toUTF8(), W_OK) != 0;
}
#endif
Result getResultForErrno()
{
return Result::fail (String (strerror (errno)));
}
Result getResultForReturnValue (int value)
{
return value == -1 ? getResultForErrno() : Result::ok();
}
int getFD (void* handle) noexcept { return (int) (pointer_sized_int) handle; }
void* fdToVoidPointer (int fd) noexcept { return (void*) (pointer_sized_int) fd; }
}
bool File::isDirectory() const
{
juce_statStruct info;
return fullPath.isNotEmpty()
&& (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
}
bool File::exists() const
{
return fullPath.isNotEmpty()
&& access (fullPath.toUTF8(), F_OK) == 0;
}
bool File::existsAsFile() const
{
return exists() && ! isDirectory();
}
int64 File::getSize() const
{
juce_statStruct info;
return juce_stat (fullPath, info) ? info.st_size : 0;
}
uint64 File::getFileIdentifier() const
{
juce_statStruct info;
return juce_stat (fullPath, info) ? (uint64) info.st_ino : 0;
}
static bool hasEffectiveRootFilePermissions()
{
#if JUCE_LINUX || JUCE_BSD
return geteuid() == 0;
#else
return false;
#endif
}
//==============================================================================
bool File::hasWriteAccess() const
{
if (exists())
return (hasEffectiveRootFilePermissions()
|| access (fullPath.toUTF8(), W_OK) == 0);
if ((! isDirectory()) && fullPath.containsChar (getSeparatorChar()))
return getParentDirectory().hasWriteAccess();
return false;
}
static bool setFileModeFlags (const String& fullPath, mode_t flags, bool shouldSet) noexcept
{
juce_statStruct info;
if (! juce_stat (fullPath, info))
return false;
info.st_mode &= 0777;
if (shouldSet)
info.st_mode |= flags;
else
info.st_mode &= ~flags;
return chmod (fullPath.toUTF8(), (mode_t) info.st_mode) == 0;
}
bool File::setFileReadOnlyInternal (bool shouldBeReadOnly) const
{
// Hmm.. should we give global write permission or just the current user?
return setFileModeFlags (fullPath, S_IWUSR | S_IWGRP | S_IWOTH, ! shouldBeReadOnly);
}
bool File::setFileExecutableInternal (bool shouldBeExecutable) const
{
return setFileModeFlags (fullPath, S_IXUSR | S_IXGRP | S_IXOTH, shouldBeExecutable);
}
void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
{
modificationTime = 0;
accessTime = 0;
creationTime = 0;
juce_statStruct info;
if (juce_stat (fullPath, info))
{
#if JUCE_MAC || (JUCE_IOS && __DARWIN_ONLY_64_BIT_INO_T)
modificationTime = (int64) info.st_mtimespec.tv_sec * 1000 + info.st_mtimespec.tv_nsec / 1000000;
accessTime = (int64) info.st_atimespec.tv_sec * 1000 + info.st_atimespec.tv_nsec / 1000000;
creationTime = (int64) info.st_birthtimespec.tv_sec * 1000 + info.st_birthtimespec.tv_nsec / 1000000;
#else
modificationTime = (int64) info.st_mtime * 1000;
accessTime = (int64) info.st_atime * 1000;
#if JUCE_IOS
creationTime = (int64) info.st_birthtime * 1000;
#else
creationTime = (int64) info.st_ctime * 1000;
#endif
#endif
}
}
bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
{
#if ! JUCE_WASM
juce_statStruct info;
if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
{
#if JUCE_MAC || (JUCE_IOS && __DARWIN_ONLY_64_BIT_INO_T)
struct timeval times[2];
bool setModificationTime = (modificationTime != 0);
bool setAccessTime = (accessTime != 0);
times[0].tv_sec = setAccessTime ? static_cast<__darwin_time_t> (accessTime / 1000)
: info.st_atimespec.tv_sec;
times[0].tv_usec = setAccessTime ? static_cast<__darwin_suseconds_t> ((accessTime % 1000) * 1000)
: static_cast<__darwin_suseconds_t> (info.st_atimespec.tv_nsec / 1000);
times[1].tv_sec = setModificationTime ? static_cast<__darwin_time_t> (modificationTime / 1000)
: info.st_mtimespec.tv_sec;
times[1].tv_usec = setModificationTime ? static_cast<__darwin_suseconds_t> ((modificationTime % 1000) * 1000)
: static_cast<__darwin_suseconds_t> (info.st_mtimespec.tv_nsec / 1000);
return utimes (fullPath.toUTF8(), times) == 0;
#else
struct utimbuf times;
times.actime = accessTime != 0 ? static_cast<time_t> (accessTime / 1000) : static_cast<time_t> (info.st_atime);
times.modtime = modificationTime != 0 ? static_cast<time_t> (modificationTime / 1000) : static_cast<time_t> (info.st_mtime);
return utime (fullPath.toUTF8(), ×) == 0;
#endif
}
#endif
return false;
}
bool File::deleteFile() const
{
if (! isSymbolicLink())
{
if (! exists())
return true;
if (isDirectory())
return rmdir (fullPath.toUTF8()) == 0;
}
return remove (fullPath.toUTF8()) == 0;
}
bool File::moveInternal (const File& dest) const
{
if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
return true;
if (hasWriteAccess() && copyInternal (dest))
{
if (deleteFile())
return true;
dest.deleteFile();
}
return false;
}
bool File::replaceInternal (const File& dest) const
{
return moveInternal (dest);
}
Result File::createDirectoryInternal (const String& fileName) const
{
return getResultForReturnValue (mkdir (fileName.toUTF8(), 0777));
}
//==============================================================================
int64 juce_fileSetPosition (void* handle, int64 pos)
{
if (handle != nullptr && lseek (getFD (handle), (off_t) pos, SEEK_SET) == pos)
return pos;
return -1;
}
void FileInputStream::openHandle()
{
auto f = open (file.getFullPathName().toUTF8(), O_RDONLY);
if (f != -1)
fileHandle = fdToVoidPointer (f);
else
status = getResultForErrno();
}
FileInputStream::~FileInputStream()
{
if (fileHandle != nullptr)
close (getFD (fileHandle));
}
size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
{
ssize_t result = 0;
if (fileHandle != nullptr)
{
result = ::read (getFD (fileHandle), buffer, numBytes);
if (result < 0)
{
status = getResultForErrno();
result = 0;
}
}
return (size_t) result;
}
//==============================================================================
void FileOutputStream::openHandle()
{
if (file.exists())
{
auto f = open (file.getFullPathName().toUTF8(), O_RDWR);
if (f != -1)
{
currentPosition = lseek (f, 0, SEEK_END);
if (currentPosition >= 0)
{
fileHandle = fdToVoidPointer (f);
}
else
{
status = getResultForErrno();
close (f);
}
}
else
{
status = getResultForErrno();
}
}
else
{
auto f = open (file.getFullPathName().toUTF8(), O_RDWR | O_CREAT, 00644);
if (f != -1)
fileHandle = fdToVoidPointer (f);
else
status = getResultForErrno();
}
}
void FileOutputStream::closeHandle()
{
if (fileHandle != nullptr)
{
close (getFD (fileHandle));
fileHandle = nullptr;
}
}
ssize_t FileOutputStream::writeInternal (const void* data, size_t numBytes)
{
if (fileHandle == nullptr)
return 0;
auto result = ::write (getFD (fileHandle), data, numBytes);
if (result == -1)
status = getResultForErrno();
return (ssize_t) result;
}
#ifndef JUCE_ANDROID
void FileOutputStream::flushInternal()
{
if (fileHandle != nullptr && fsync (getFD (fileHandle)) == -1)
status = getResultForErrno();
}
#endif
Result FileOutputStream::truncate()
{
if (fileHandle == nullptr)
return status;
flush();
return getResultForReturnValue (ftruncate (getFD (fileHandle), (off_t) currentPosition));
}
//==============================================================================
String SystemStats::getEnvironmentVariable (const String& name, const String& defaultValue)
{
if (auto s = ::getenv (name.toUTF8()))
return String::fromUTF8 (s);
return defaultValue;
}
//==============================================================================
#if ! JUCE_WASM
void MemoryMappedFile::openInternal (const File& file, AccessMode mode, bool exclusive)
{
jassert (mode == readOnly || mode == readWrite);
if (range.getStart() > 0)
{
auto pageSize = sysconf (_SC_PAGE_SIZE);
range.setStart (range.getStart() - (range.getStart() % pageSize));
}
auto filename = file.getFullPathName().toUTF8();
if (mode == readWrite)
fileHandle = open (filename, O_CREAT | O_RDWR, 00644);
else
fileHandle = open (filename, O_RDONLY);
if (fileHandle != -1)
{
auto m = mmap (nullptr, (size_t) range.getLength(),
mode == readWrite ? (PROT_READ | PROT_WRITE) : PROT_READ,
exclusive ? MAP_PRIVATE : MAP_SHARED, fileHandle,
(off_t) range.getStart());
if (m != MAP_FAILED)
{
address = m;
madvise (m, (size_t) range.getLength(), MADV_SEQUENTIAL);
}
else
{
range = Range<int64>();
}
close (fileHandle);
fileHandle = 0;
}
}
MemoryMappedFile::~MemoryMappedFile()
{
if (address != nullptr)
munmap (address, (size_t) range.getLength());
if (fileHandle != 0)
close (fileHandle);
}
//==============================================================================
File juce_getExecutableFile();
File juce_getExecutableFile()
{
struct DLAddrReader
{
static String getFilename()
{
Dl_info exeInfo;
auto localSymbol = (void*) juce_getExecutableFile;
dladdr (localSymbol, &exeInfo);
return CharPointer_UTF8 (exeInfo.dli_fname);
}
};
static String filename = DLAddrReader::getFilename();
return File::getCurrentWorkingDirectory().getChildFile (filename);
}
//==============================================================================
int64 File::getBytesFreeOnVolume() const
{
struct statfs buf;
if (juce_doStatFS (*this, buf))
return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
return 0;
}
int64 File::getVolumeTotalSize() const
{
struct statfs buf;
if (juce_doStatFS (*this, buf))
return (int64) buf.f_bsize * (int64) buf.f_blocks;
return 0;
}
String File::getVolumeLabel() const
{
#if JUCE_MAC
struct VolAttrBuf
{
u_int32_t length;
attrreference_t mountPointRef;
char mountPointSpace[MAXPATHLEN];
} attrBuf;
struct attrlist attrList;
zerostruct (attrList); // (can't use "= {}" on this object because it's a C struct)
attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
File f (*this);
for (;;)
{
if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
(int) attrBuf.mountPointRef.attr_length);
auto parent = f.getParentDirectory();
if (f == parent)
break;
f = parent;
}
#endif
return {};
}
int File::getVolumeSerialNumber() const
{
return 0;
}
#endif
//==============================================================================
#if ! JUCE_IOS
void juce_runSystemCommand (const String&);
void juce_runSystemCommand (const String& command)
{
int result = system (command.toUTF8());
ignoreUnused (result);
}
String juce_getOutputFromCommand (const String&);
String juce_getOutputFromCommand (const String& command)
{
// slight bodge here, as we just pipe the output into a temp file and read it...
auto tempFile = File::getSpecialLocation (File::tempDirectory)
.getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false);
juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
auto result = tempFile.loadFileAsString();
tempFile.deleteFile();
return result;
}
#endif
//==============================================================================
#if JUCE_IOS
class InterProcessLock::Pimpl
{
public:
Pimpl (const String&, int) {}
int handle = 1, refCount = 1; // On iOS just fake success..
};
#else
class InterProcessLock::Pimpl
{
public:
Pimpl (const String& lockName, int timeOutMillisecs)
{
#if JUCE_MAC
if (! createLockFile (File ("~/Library/Caches/com.juce.locks").getChildFile (lockName), timeOutMillisecs))
// Fallback if the user's home folder is on a network drive with no ability to lock..
createLockFile (File ("/tmp/com.juce.locks").getChildFile (lockName), timeOutMillisecs);
#else
File tempFolder ("/var/tmp");
if (! tempFolder.isDirectory())
tempFolder = "/tmp";
createLockFile (tempFolder.getChildFile (lockName), timeOutMillisecs);
#endif
}
~Pimpl()
{
closeFile();
}
bool createLockFile (const File& file, int timeOutMillisecs)
{
file.create();
handle = open (file.getFullPathName().toUTF8(), O_RDWR);
if (handle != 0)
{
struct flock fl;
zerostruct (fl);
fl.l_whence = SEEK_SET;
fl.l_type = F_WRLCK;
auto endTime = Time::currentTimeMillis() + timeOutMillisecs;
for (;;)
{
auto result = fcntl (handle, F_SETLK, &fl);
if (result >= 0)
return true;
auto error = errno;
if (error != EINTR)
{
if (error == EBADF || error == ENOTSUP)
return false;
if (timeOutMillisecs == 0
|| (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
break;
Thread::sleep (10);
}
}
}
closeFile();
return true; // only false if there's a file system error. Failure to lock still returns true.
}
void closeFile()
{
if (handle != 0)
{
struct flock fl;
zerostruct (fl);
fl.l_whence = SEEK_SET;
fl.l_type = F_UNLCK;
while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
{}
close (handle);
handle = 0;
}
}
int handle = 0, refCount = 1;
};
#endif
InterProcessLock::InterProcessLock (const String& nm) : name (nm)
{
}
InterProcessLock::~InterProcessLock()
{
}
bool InterProcessLock::enter (int timeOutMillisecs)
{
const ScopedLock sl (lock);
if (pimpl == nullptr)
{
pimpl.reset (new Pimpl (name, timeOutMillisecs));
if (pimpl->handle == 0)
pimpl.reset();
}
else
{
pimpl->refCount++;
}
return pimpl != nullptr;
}
void InterProcessLock::exit()
{
const ScopedLock sl (lock);
// Trying to release the lock too many times!
jassert (pimpl != nullptr);
if (pimpl != nullptr && --(pimpl->refCount) == 0)
pimpl.reset();
}
//==============================================================================
#if JUCE_ANDROID
extern JavaVM* androidJNIJavaVM;
#endif
static void* threadEntryProc (void* userData)
{
auto* myself = static_cast<Thread*> (userData);
JUCE_AUTORELEASEPOOL
{
juce_threadEntryPoint (myself);
}
#if JUCE_ANDROID
if (androidJNIJavaVM != nullptr)
{
void* env = nullptr;
androidJNIJavaVM->GetEnv(&env, JNI_VERSION_1_2);
// only detach if we have actually been attached
if (env != nullptr)
androidJNIJavaVM->DetachCurrentThread();
}
#endif
return nullptr;
}
#if JUCE_ANDROID && JUCE_MODULE_AVAILABLE_juce_audio_devices && (JUCE_USE_ANDROID_OPENSLES || JUCE_USE_ANDROID_OBOE)
#define JUCE_ANDROID_REALTIME_THREAD_AVAILABLE 1
#endif
#if JUCE_ANDROID_REALTIME_THREAD_AVAILABLE
extern pthread_t juce_createRealtimeAudioThread (void* (*entry) (void*), void* userPtr);
#endif
void Thread::launchThread()
{
#if JUCE_ANDROID
if (isAndroidRealtimeThread)
{
#if JUCE_ANDROID_REALTIME_THREAD_AVAILABLE
threadHandle = (void*) juce_createRealtimeAudioThread (threadEntryProc, this);
threadId = (ThreadID) threadHandle.get();
return;
#else
jassertfalse;
#endif
}
#endif
threadHandle = {};
pthread_t handle = {};
pthread_attr_t attr;
pthread_attr_t* attrPtr = nullptr;
if (pthread_attr_init (&attr) == 0)
{
attrPtr = &attr;
pthread_attr_setstacksize (attrPtr, threadStackSize);
}
if (pthread_create (&handle, attrPtr, threadEntryProc, this) == 0)
{
pthread_detach (handle);
threadHandle = (void*) handle;
threadId = (ThreadID) threadHandle.get();
}
if (attrPtr != nullptr)
pthread_attr_destroy (attrPtr);
}
void Thread::closeThreadHandle()
{
threadId = {};
threadHandle = {};
}
void Thread::killThread()
{
if (threadHandle.get() != nullptr)
{
#if JUCE_ANDROID
jassertfalse; // pthread_cancel not available!
#else
pthread_cancel ((pthread_t) threadHandle.get());
#endif
}
}
void JUCE_CALLTYPE Thread::setCurrentThreadName (const String& name)
{
#if JUCE_IOS || JUCE_MAC
JUCE_AUTORELEASEPOOL
{
[[NSThread currentThread] setName: juceStringToNS (name)];
}
#elif JUCE_LINUX || JUCE_BSD || JUCE_ANDROID
#if (JUCE_BSD \
|| (JUCE_LINUX && (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2012) \
|| (JUCE_ANDROID && __ANDROID_API__ >= 9))
pthread_setname_np (pthread_self(), name.toRawUTF8());
#else
prctl (PR_SET_NAME, name.toRawUTF8(), 0, 0, 0);
#endif
#endif
}
bool Thread::setThreadPriority (void* handle, int priority)
{
constexpr auto maxInputPriority = 10;
constexpr auto lowestRealtimePriority = 8;
struct sched_param param;
int policy;
if (handle == nullptr)
handle = (void*) pthread_self();
if (pthread_getschedparam ((pthread_t) handle, &policy, ¶m) != 0)
return false;
policy = priority < lowestRealtimePriority ? SCHED_OTHER : SCHED_RR;
const auto minPriority = sched_get_priority_min (policy);
const auto maxPriority = sched_get_priority_max (policy);
param.sched_priority = [&]
{
if (policy == SCHED_OTHER)
return 0;
return jmap (priority, lowestRealtimePriority, maxInputPriority, minPriority, maxPriority);
}();
return pthread_setschedparam ((pthread_t) handle, policy, ¶m) == 0;
}
Thread::ThreadID JUCE_CALLTYPE Thread::getCurrentThreadId()
{
return (ThreadID) pthread_self();
}
void JUCE_CALLTYPE Thread::yield()
{
sched_yield();
}
//==============================================================================
/* Remove this macro if you're having problems compiling the cpu affinity
calls (the API for these has changed about quite a bit in various Linux
versions, and a lot of distros seem to ship with obsolete versions)
*/
#if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
#define SUPPORT_AFFINITIES 1
#endif
void JUCE_CALLTYPE Thread::setCurrentThreadAffinityMask (uint32 affinityMask)
{
#if SUPPORT_AFFINITIES
cpu_set_t affinity;
CPU_ZERO (&affinity);
for (int i = 0; i < 32; ++i)
if ((affinityMask & (uint32) (1 << i)) != 0)
CPU_SET ((size_t) i, &affinity);
#if (! JUCE_ANDROID) && ((! (JUCE_LINUX || JUCE_BSD)) || ((__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2004))
pthread_setaffinity_np (pthread_self(), sizeof (cpu_set_t), &affinity);
#elif JUCE_ANDROID
sched_setaffinity (gettid(), sizeof (cpu_set_t), &affinity);
#else
// NB: this call isn't really correct because it sets the affinity of the process,
// (getpid) not the thread (not gettid). But it's included here as a fallback for
// people who are using ridiculously old versions of glibc
sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
#endif
sched_yield();
#else
// affinities aren't supported because either the appropriate header files weren't found,
// or the SUPPORT_AFFINITIES macro was turned off
jassertfalse;
ignoreUnused (affinityMask);
#endif
}
//==============================================================================
#if ! JUCE_WASM
bool DynamicLibrary::open (const String& name)
{
close();
handle = dlopen (name.isEmpty() ? nullptr : name.toUTF8().getAddress(), RTLD_LOCAL | RTLD_NOW);
return handle != nullptr;
}
void DynamicLibrary::close()
{
if (handle != nullptr)
{
dlclose (handle);
handle = nullptr;
}
}
void* DynamicLibrary::getFunction (const String& functionName) noexcept
{
return handle != nullptr ? dlsym (handle, functionName.toUTF8()) : nullptr;
}
//==============================================================================
#if JUCE_LINUX || JUCE_ANDROID
static String readPosixConfigFileValue (const char* file, const char* key)
{
StringArray lines;
File (file).readLines (lines);
for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
if (lines[i].upToFirstOccurrenceOf (":", false, false).trim().equalsIgnoreCase (key))
return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
return {};
}
#endif
//==============================================================================
class ChildProcess::ActiveProcess
{
public:
ActiveProcess (const StringArray& arguments, int streamFlags)
{
auto exe = arguments[0].unquoted();
// Looks like you're trying to launch a non-existent exe or a folder (perhaps on OSX
// you're trying to launch the .app folder rather than the actual binary inside it?)
jassert (File::getCurrentWorkingDirectory().getChildFile (exe).existsAsFile()
|| ! exe.containsChar (File::getSeparatorChar()));
int pipeHandles[2] = {};
if (pipe (pipeHandles) == 0)
{
auto result = fork();
if (result < 0)
{
close (pipeHandles[0]);
close (pipeHandles[1]);
}
else if (result == 0)
{
// we're the child process..
close (pipeHandles[0]); // close the read handle
if ((streamFlags & wantStdOut) != 0)
dup2 (pipeHandles[1], STDOUT_FILENO); // turns the pipe into stdout
else
dup2 (open ("/dev/null", O_WRONLY), STDOUT_FILENO);
if ((streamFlags & wantStdErr) != 0)
dup2 (pipeHandles[1], STDERR_FILENO);
else
dup2 (open ("/dev/null", O_WRONLY), STDERR_FILENO);
close (pipeHandles[1]);
Array<char*> argv;
for (auto& arg : arguments)
if (arg.isNotEmpty())
argv.add (const_cast<char*> (arg.toRawUTF8()));
argv.add (nullptr);
execvp (exe.toRawUTF8(), argv.getRawDataPointer());
_exit (-1);
}
else
{
// we're the parent process..
childPID = result;
pipeHandle = pipeHandles[0];
close (pipeHandles[1]); // close the write handle
}
}
}
~ActiveProcess()
{
if (readHandle != nullptr)
fclose (readHandle);
if (pipeHandle != 0)
close (pipeHandle);
}
bool isRunning() noexcept
{
if (childPID == 0)
return false;
int childState = 0;
auto pid = waitpid (childPID, &childState, WNOHANG);
if (pid == 0)
return true;
if (WIFEXITED (childState))
{
exitCode = WEXITSTATUS (childState);
return false;
}
return ! WIFSIGNALED (childState);
}
int read (void* dest, int numBytes) noexcept
{
jassert (dest != nullptr && numBytes > 0);
#ifdef fdopen
#error // some crazy 3rd party headers (e.g. zlib) define this function as NULL!
#endif
if (readHandle == nullptr && childPID != 0)
readHandle = fdopen (pipeHandle, "r");
if (readHandle != nullptr)
{
for (;;)
{
auto numBytesRead = (int) fread (dest, 1, (size_t) numBytes, readHandle);
if (numBytesRead > 0 || feof (readHandle))
return numBytesRead;
// signal occurred during fread() so try again
if (ferror (readHandle) && errno == EINTR)
continue;
break;
}
}
return 0;
}
bool killProcess() const noexcept
{
return ::kill (childPID, SIGKILL) == 0;
}
uint32 getExitCode() noexcept
{
if (exitCode >= 0)
return (uint32) exitCode;
if (childPID != 0)
{
int childState = 0;
auto pid = waitpid (childPID, &childState, WNOHANG);
if (pid >= 0 && WIFEXITED (childState))
{
exitCode = WEXITSTATUS (childState);
return (uint32) exitCode;
}
}
return 0;
}
int childPID = 0;
int pipeHandle = 0;
int exitCode = -1;
FILE* readHandle = {};
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ActiveProcess)
};
bool ChildProcess::start (const String& command, int streamFlags)
{
return start (StringArray::fromTokens (command, true), streamFlags);
}
bool ChildProcess::start (const StringArray& args, int streamFlags)
{
if (args.size() == 0)
return false;
activeProcess.reset (new ActiveProcess (args, streamFlags));
if (activeProcess->childPID == 0)
activeProcess.reset();
return activeProcess != nullptr;
}
#endif
//==============================================================================
struct HighResolutionTimer::Pimpl
{
explicit Pimpl (HighResolutionTimer& t)
: owner (t)
{}
~Pimpl()
{
jassert (periodMs == 0);
stop();
}
void start (int newPeriod)
{
if (periodMs == newPeriod)
return;
if (thread.get_id() == std::this_thread::get_id())
{
periodMs = newPeriod;
return;
}
stop();
periodMs = newPeriod;
thread = std::thread ([this, newPeriod]
{
setThisThreadToRealtime ((uint64) newPeriod);
auto lastPeriod = periodMs.load();
Clock clock (lastPeriod);
std::unique_lock<std::mutex> unique_lock (timerMutex);
while (periodMs != 0)
{
clock.next();
while (periodMs != 0 && clock.wait (stopCond, unique_lock));
if (periodMs == 0)
break;
owner.hiResTimerCallback();
auto nextPeriod = periodMs.load();
if (lastPeriod != nextPeriod)
{
lastPeriod = nextPeriod;
clock = Clock (lastPeriod);
}
}
periodMs = 0;
});
}
void stop()
{
periodMs = 0;
const auto thread_id = thread.get_id();
if (thread_id == std::thread::id() || thread_id == std::this_thread::get_id())
return;
{
std::unique_lock<std::mutex> unique_lock (timerMutex);
stopCond.notify_one();
}
thread.join();
}
HighResolutionTimer& owner;
std::atomic<int> periodMs { 0 };
private:
std::thread thread;
std::condition_variable stopCond;
std::mutex timerMutex;
class Clock
{
public:
explicit Clock (std::chrono::steady_clock::rep millis) noexcept
: time (std::chrono::steady_clock::now()),
delta (std::chrono::milliseconds (millis))
{}
bool wait (std::condition_variable& cond, std::unique_lock<std::mutex>& lock) noexcept
{
return cond.wait_until (lock, time) != std::cv_status::timeout;
}
void next() noexcept
{
time += delta;
}
private:
std::chrono::time_point<std::chrono::steady_clock> time;
std::chrono::steady_clock::duration delta;
};
static bool setThisThreadToRealtime (uint64 periodMs)
{
const auto thread = pthread_self();
#if JUCE_MAC || JUCE_IOS
mach_timebase_info_data_t timebase;
mach_timebase_info (&timebase);
const auto ticksPerMs = ((double) timebase.denom * 1000000.0) / (double) timebase.numer;
const auto periodTicks = (uint32_t) jmin ((double) std::numeric_limits<uint32_t>::max(), periodMs * ticksPerMs);
thread_time_constraint_policy_data_t policy;
policy.period = periodTicks;
policy.computation = jmin ((uint32_t) 50000, policy.period);
policy.constraint = policy.period;
policy.preemptible = true;
return thread_policy_set (pthread_mach_thread_np (thread),
THREAD_TIME_CONSTRAINT_POLICY,
(thread_policy_t) &policy,
THREAD_TIME_CONSTRAINT_POLICY_COUNT) == KERN_SUCCESS;
#else
ignoreUnused (periodMs);
struct sched_param param;
param.sched_priority = sched_get_priority_max (SCHED_RR);
return pthread_setschedparam (thread, SCHED_RR, ¶m) == 0;
#endif
}
JUCE_DECLARE_NON_COPYABLE (Pimpl)
};
} // namespace juce
|