10#include <CommonCrypto/CommonDigest.h>
20#include <mach-o/dyld.h>
27bool VuoFileUtilities::dylibLoaderInitialMatchCompleted =
false;
28string VuoFileUtilities::vuoFrameworkPath;
29string VuoFileUtilities::vuoRunnerFrameworkPath;
46 const char FILE_SEPARATOR =
'/';
48 size_t separatorIndex = path.rfind(FILE_SEPARATOR);
49 string fileAndExtension;
50 if (separatorIndex != string::npos)
52 dir = path.substr(0, separatorIndex + 1);
53 if (separatorIndex < path.length())
54 fileAndExtension = path.substr(separatorIndex + 1, path.length());
58 fileAndExtension = path;
61 size_t dotIndex = fileAndExtension.rfind(
".");
62 if (dotIndex != string::npos)
64 file = fileAndExtension.substr(0, dotIndex);
65 extension = fileAndExtension.substr(dotIndex + 1, fileAndExtension.length());
69 file = fileAndExtension;
80 for (
int i = 0; i < path.length(); ++i)
82 while (i+1 < path.length() && path[i+1] ==
'/')
87 path.erase(path.length()-1);
100 return path1 == path2;
111 char *cwd = getcwd(NULL, 0);
114 VUserLog(
"Couldn't get current working directory: %s", strerror(errno));
118 string absolutePath = string(cwd) +
"/" + path;
132 if (directory.empty())
134 if (directory.at(directory.length()-1) !=
'/')
136 string suffix = (extension.empty() ?
"" : (
"." + extension));
137 string pathTemplate = directory + file +
"-XXXXXX" + suffix;
138 char *path = (
char *)calloc(pathTemplate.length() + 1,
sizeof(char));
139 strncpy(path, pathTemplate.c_str(), pathTemplate.length());
140 int fd = mkstemps(path, suffix.length());
142 string pathStr(path);
158 string pathTemplate =
getTmpDir() +
"/" + prefix +
".XXXXXX";
159 char *path = (
char *)calloc(pathTemplate.length() + 1,
sizeof(char));
160 strncpy(path, pathTemplate.c_str(), pathTemplate.length());
162 string pathStr(path);
193 char *cwd = getcwd(NULL, 0);
195 VUserLog(
"Error in getcwd(): %s", strerror(errno));
197 if (cwd && strstr(cwd,
"/Library/Containers/"))
209 char userTempDir[PATH_MAX];
210 if (confstr(_CS_DARWIN_USER_TEMP_DIR, userTempDir, PATH_MAX) > 0)
212 string userTempDirS(userTempDir);
229 throw VuoException(
"Couldn't create directory with empty path");
234 const char FILE_SEPARATOR =
'/';
235 size_t lastNonSeparator = path.find_last_not_of(FILE_SEPARATOR);
236 if (lastNonSeparator != string::npos)
237 path.resize(lastNonSeparator + 1);
239 string parentDir, file, ext;
245 int ret = mkdir(path.c_str(), 0777);
246 int mkdirErrno = errno;
248 throw VuoException((
string(
"Couldn't create directory \"" + path +
"\": ") + strerror(mkdirErrno)).c_str());
256void VuoFileUtilities::dylibLoaded(
const struct mach_header *mh32, intptr_t vmaddr_slide)
258 if (dylibLoaderInitialMatchCompleted)
261 const struct mach_header_64 *mh =
reinterpret_cast<const mach_header_64 *
>(mh32);
264 if (mh->flags & MH_DYLIB_IN_CACHE)
268 Dl_info info{
"",
nullptr,
"",
nullptr};
269 dladdr((
void *)vmaddr_slide, &info);
273 auto getMatchingPath = [info](
string fragment) ->
string {
274 string qualifiedFragment =
"/" + fragment +
".framework/Versions/";
275 const char *found = strstr(info.dli_fname, qualifiedFragment.c_str());
278 char *pathC = strndup(info.dli_fname, found - info.dli_fname);
279 string path = string(pathC) +
"/" + fragment +
".framework";
281 if (access(path.c_str(), 0) == 0)
287 string possibleVuoFramework = getMatchingPath(
"Vuo");
288 if (!possibleVuoFramework.empty())
289 vuoFrameworkPath = possibleVuoFramework;
291 string possibleVuoRunnerFramework = getMatchingPath(
"VuoRunner");
292 if (!possibleVuoRunnerFramework.empty())
293 vuoRunnerFrameworkPath = possibleVuoRunnerFramework;
299void VuoFileUtilities::initializeVuoFrameworkPaths(
void)
301 static once_flag once;
302 call_once(once, []() {
304 _dyld_register_func_for_add_image(&dylibLoaded);
305 dylibLoaderInitialMatchCompleted =
true;
308 if (vuoRunnerFrameworkPath.empty() && !vuoFrameworkPath.empty())
311 string pathCandidate = vuoFrameworkPath +
"/../VuoRunner.framework";
313 vuoRunnerFrameworkPath = pathCandidate;
327 initializeVuoFrameworkPaths();
328 return vuoFrameworkPath;
338 initializeVuoFrameworkPaths();
339 return vuoRunnerFrameworkPath;
352 string compositionDir, compositionFile, ext;
356 string parentDir, compositionDirName;
357 splitPath(compositionDir, parentDir, compositionDirName, ext);
360 string compositionBaseDir = (compositionDirName ==
"Modules" ? parentDir : compositionDir);
362 string compositionModulesDir = compositionBaseDir +
"/Modules";
365 return compositionModulesDir;
378 const char *home = getenv(
"HOME");
382 return string(home) +
"/Library/Application Support/Vuo/Modules";
390 return "/Library/Application Support/Vuo/Modules";
403 const char *home = getenv(
"HOME");
407 return string(home) +
"/Library/Caches/org.vuo/" + VUO_VERSION_AND_BUILD_STRING;
420 string dir, file, ext;
445 string bomUtf8 =
"\xEF\xBB\xBF";
446 string bomUtf16Be =
"\xFE\xFF";
447 string bomUtf16Le =
"\xFF\xFE";
448 string boms[] = { bomUtf8, bomUtf16Be, bomUtf16Le };
449 for (
int i = 0; i < 3; ++i)
452 for (
int j = 0; j < boms[i].length(); ++j)
453 if (boms[i][j] != s[j])
457 return boms[i].length();
471 while (getline(cin, line))
486 ifstream in(path.c_str(), ios::in | ios::binary);
488 throw VuoException(
string(
"Couldn't read file: ") + strerror(errno) +
" — " + path);
491 in.seekg(0, ios::end);
492 contents.resize(in.tellg());
493 in.seekg(0, ios::beg);
494 in.read(&contents[0], contents.size());
508 FILE *f = fopen(file.c_str(),
"wb");
510 throw VuoException(
string(
"Couldn't open file for writing: ") + strerror(errno) +
" — " + file);
512 size_t numBytesWritten = fwrite(data,
sizeof(
char), numBytes, f);
513 if (numBytesWritten != numBytes)
516 throw VuoException(
string(
"Couldn't write all data: ") + strerror(errno) +
" — " + file);
544 string dir, file, ext;
546 string tmpPath =
makeTmpFile(
"." + file, ext, dir);
564 return access(path.c_str(), 0) == 0;
579 int status = stat(path.c_str(), &st_buf);
580 return (! status && S_ISDIR(st_buf.st_mode));
589 int status = lstat(path.c_str(), &st_buf);
590 return (! status && S_ISLNK(st_buf.st_mode));
604 return access(path.c_str(), R_OK) == 0;
618 FILE *f = fopen(path.c_str(),
"rb");
622 fseek(f, 0, SEEK_END);
631 fseek(f, 0, SEEK_SET);
633 size_t ret = fread(&z, 1, 1, f);
643 FILE *f = fopen(path.c_str(),
"a");
652 int ret = remove(path.c_str());
654 VUserLog(
"Couldn't delete file: %s — %s", strerror(errno), path.c_str());
665 DIR *d = opendir(path.c_str());
668 VUserLog(
"Couldn't read directory: %s — %s", strerror(errno), path.c_str());
673 while( (de=readdir(d)) )
675 string fileName = de->d_name;
676 string filePath = path +
"/" + fileName;
678 if (fileName ==
"." || fileName ==
"..")
699 int ret = rename(fromPath.c_str(), toPath.c_str());
701 throw VuoException(
string(
"Couldn't move file: ") + strerror(errno) +
" — " + toPath);
727 int i = open(fromPath.c_str(), O_RDONLY);
729 throw VuoException(
string(
"Couldn't open copy source: ") + strerror(errno) +
" — " + fromPath);
733 int o = open(toPath.c_str(), O_WRONLY | O_CREAT, s.st_mode & 0777);
737 throw VuoException(
string(
"Couldn't open copy destination: ") + strerror(errno) +
" — " + toPath);
740 int ret = fcopyfile(i, o, NULL, COPYFILE_DATA | (preserveMetadata ? COPYFILE_STAT : 0));
741 char *e = strerror(errno);
746 throw VuoException(
string(
"Couldn't copy ") + fromPath +
" to " + toPath +
": " + e);
748 VDebugLog(
"%s -> %s", fromPath.c_str(), toPath.c_str());
765 char linkDestination[PATH_MAX + 1];
766 ssize_t len = readlink(fromPath.c_str(), linkDestination, PATH_MAX);
767 linkDestination[len] = 0;
768 if (symlink(linkDestination, toPath.c_str()) == -1)
769 throw VuoException(
string(
"Couldn't copy symlink \"") + fromPath +
"\" to \"" + toPath +
"\": " + strerror(errno));
771 VDebugLog(
"%s -> %s (symlink)", fromPath.c_str(), toPath.c_str());
782 for (
auto file : files)
784 string sourceFile = fromPath +
"/" + file->getRelativePath();
785 string targetFile = toPath +
"/" + file->getRelativePath();
798 int fd = open(path.c_str(), O_RDONLY);
800 throw VuoException(
"Error: Couldn't open \"" + path +
"\": " + strerror(errno));
804 if (fstat(fd, &stat) != 0)
805 throw VuoException(
"Error: Couldn't fstat \"" + path +
"\": " + strerror(errno));
809 void *data = mmap(
nullptr, stat.st_size, PROT_READ, MAP_PRIVATE | MAP_NOCACHE, fd, 0);
810 if (data == MAP_FAILED)
811 throw VuoException(
"Error: Couldn't mmap \"" + path +
"\": " + strerror(errno));
812 VuoDefer(^{ munmap(data, stat.st_size); });
814 unsigned char hash[CC_SHA256_DIGEST_LENGTH];
815 if (!CC_SHA256(data, stat.st_size, hash))
816 throw VuoException(
"Error: CC_SHA256 failed on file \"" + path +
"\"");
819 oss << setfill(
'0') << hex;
820 for (
int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++i)
821 oss << setw(2) << (int)hash[i];
832 lstat(path.c_str(), &s);
833 return s.st_mtimespec.tv_sec;
842 lstat(path.c_str(), &s);
845 gettimeofday(&t, NULL);
847 return t.tv_sec - s.st_atimespec.tv_sec;
865 bool shouldSearchRecursively)
873 DIR *d = opendir(dirPath.c_str());
876 if (access(dirPath.c_str(), F_OK) != -1)
877 throw VuoException(
string(
"Couldn't read directory: ") + strerror(errno) +
" — " + dirPath);
882 while( (de=readdir(d)) )
884 string fileName = de->d_name;
885 string relativeFilePath = dirPath +
"/" + fileName;
887 if (fileName ==
"." || fileName ==
"..")
890 bool isArchive =
false;
891 for (set<string>::iterator archiveExtension = archiveExtensions.begin(); archiveExtension != archiveExtensions.end(); ++archiveExtension)
901 files.insert(fs.begin(), fs.end());
906 bool shouldSearchDir = shouldSearchRecursively
912 for (set<File *>::iterator i = filesInDir.begin(); i != filesInDir.end(); ++i)
915 f->dirPath = dirPath;
916 f->filePath = fileName +
"/" + f->filePath;
918 files.insert(filesInDir.begin(), filesInDir.end());
922 File *f =
new File(dirPath, fileName);
945 set<File *> matchingFiles;
947 for (set<File *>::iterator i = allFiles.begin(); i != allFiles.end(); ++i)
949 bool endsWithExtension =
false;
950 for (set<string>::iterator extension = extensions.begin(); extension != extensions.end(); ++extension)
952 endsWithExtension =
true;
955 matchingFiles.insert(*i);
960 return matchingFiles;
980 mz_uint numFiles = mz_zip_reader_get_num_files(archive->
zipArchive);
981 for (mz_uint i = 0; i < numFiles; ++i)
983 mz_zip_archive_file_stat file_stat;
984 bool success = mz_zip_reader_file_stat(archive->
zipArchive, i, &file_stat);
987 VUserLog(
"Error: Couldn't read file '%u' in zip archive '%s'.", i, archive->
path.c_str());
991 File *f =
new File(archive, file_stat.m_filename);
1013 set<File *> matchingFiles;
1015 for (set<File *>::iterator i = allFiles.begin(); i != allFiles.end(); ++i)
1019 string dir, file, ext;
1023 bool endsWithExtension =
false;
1024 for (set<string>::iterator extension = extensions.begin(); extension != extensions.end(); ++extension)
1026 endsWithExtension =
true;
1028 if (beginsWithDir && endsWithExtension)
1029 matchingFiles.insert(f);
1034 return matchingFiles;
1050 for (set<File *>::iterator i = archiveFiles.begin(); i != archiveFiles.end(); ++i)
1079 vector<string> processAndArgs{
1086 if (!entitlementsPath.empty())
1088 processAndArgs.push_back(
"--entitlements");
1089 processAndArgs.push_back(entitlementsPath);
1107 this->
zipArchive = (mz_zip_archive *)calloc(1,
sizeof(mz_zip_archive));
1109 bool success = mz_zip_reader_init_file(
zipArchive,
path.c_str(), 0);
1124 mz_zip_reader_end(zipArchive);
1145 this->fileDescriptor = -1;
1146 this->archive = NULL;
1158 this->fileDescriptor = -1;
1159 this->archive = archive;
1169 string newFilePath = basename() +
"." + extension;
1172 return File(archive, newFilePath);
1174 return File(dirPath, newFilePath);
1183 if (archive && --archive->referenceCount == 0)
1192 return (archive != NULL);
1202 return (archive ? archive->path :
"");
1221 throw VuoException(
"Can't return a simple absolute path for a file in an archive.");
1223 return dirPath +
"/" + filePath;
1234 throw VuoException(
"Can't return a simple absolute path for a file in an archive.");
1244 return filePath.substr(0, filePath.find_last_of(
'.'));
1252 return filePath.substr(filePath.find_last_of(
'.') + 1);
1261 return mz_zip_reader_locate_file(archive->zipArchive, filePath.c_str(),
nullptr, MZ_ZIP_FLAG_CASE_SENSITIVE) != -1;
1283 string fullPath = (dirPath.empty() ?
"" : (dirPath +
"/")) + filePath;
1285 FILE *pFile = fopen ( fullPath.c_str() ,
"rb" );
1287 throw VuoException(
string(
"Couldn't open file: ") + strerror(errno) +
" — " + fullPath);
1290 fseek (pFile , 0 , SEEK_END);
1291 size_t lSize = ftell (pFile);
1295 buffer = (
char*) malloc (
sizeof(
char)*lSize);
1298 numBytes = fread (buffer,1,lSize,pFile);
1300 if (numBytes != lSize)
1303 throw VuoException(
string(
"Couldn't read file: ") + strerror(errno) +
" — " + fullPath);
1308 buffer = (
char *)mz_zip_reader_extract_file_to_heap(archive->zipArchive, filePath.c_str(), &numBytes, 0);
1322 char *buffer = getContentsAsRawData(numBytes);
1323 string s(buffer, numBytes);
1339 if (fileDescriptor < 0)
1340 fileDescriptor = open((dirPath +
"/" + filePath).c_str(), O_RDONLY);
1341 int ret = flock(fileDescriptor, LOCK_SH | (nonBlocking ? LOCK_NB : 0));
1356 if (fileDescriptor < 0)
1357 fileDescriptor = open((dirPath +
"/" + filePath).c_str(), O_RDONLY);
1358 int ret = flock(fileDescriptor, LOCK_EX | (nonBlocking ? LOCK_NB : 0));
1368 flock(fileDescriptor, LOCK_UN);
1369 close(fileDescriptor);
1370 fileDescriptor = -1;
1393 string binaryDir, binaryFile, binaryExt;
1394 splitPath(processAndArgs[0], binaryDir, binaryFile, binaryExt);
1396 string errorPrefix =
"Couldn't execute " + binaryFile +
": ";
1400 int ret = pipe(outputPipe);
1402 throw VuoException(errorPrefix +
"couldn't open pipe: " + strerror(ret));
1403 int pipeRead = outputPipe[0];
1404 int pipeWrite = outputPipe[1];
1406 posix_spawn_file_actions_t fileActions;
1407 posix_spawn_file_actions_init(&fileActions);
1408 posix_spawn_file_actions_adddup2(&fileActions, pipeWrite, STDOUT_FILENO);
1409 posix_spawn_file_actions_adddup2(&fileActions, pipeWrite, STDERR_FILENO);
1410 posix_spawn_file_actions_addclose(&fileActions, pipeRead);
1414 char **processAndArgsZ = (
char **)malloc(
sizeof(
char *) * (processAndArgs.size() + 1));
1417 for (
auto arg : processAndArgs)
1419 processAndArgsZ[argCount++] = strdup(arg.c_str());
1422 commandLine +=
'"' + arg +
'"';
1424 processAndArgsZ[argCount] =
nullptr;
1429 char **environmentZ = (
char **)malloc(
sizeof(
char *) * (environment.size() + 1));
1430 int environmentVarCount = 0;
1431 for (
auto environmentVar : environment)
1433 environmentZ[environmentVarCount++] = strdup(environmentVar.c_str());
1434 commandLine = environmentVar +
" " + commandLine;
1436 environmentZ[environmentVarCount] =
nullptr;
1442 ret = posix_spawn(&pid, processAndArgs[0].c_str(), &fileActions, NULL, (
char *
const *)processAndArgsZ, (
char *
const *)environmentZ);
1444 posix_spawn_file_actions_destroy(&fileActions);
1445 for (
int i = 0; i < argCount; ++i)
1446 free(processAndArgsZ[i]);
1456 ret = waitpid(pid, &status, 0);
1457 if (ret == -1 && errno == EINTR)
1462 throw VuoException(errorPrefix +
"waitpid failed: " + strerror(errno));
1463 else if (status != 0)
1468 while (read(pipeRead, &buf, 255) > 0)
1488 return extension ==
"vuo";
1514 return extensions.find(extension) != extensions.end();
1525 e.insert(
"vuoshader");
1526 e.insert(
"vuoobjectfilter");
1527 return e.find(extension) != e.end();
1535 return string() +
"the cache of " + (generated ?
"generated" :
"installed") +
" modules at '" + moduleCachePath +
"'";
1543 string moduleCachePathCanonical = moduleCachePath;
1546 return moduleCachePathCanonical +
"/libVuoModuleCache-" + (generated ?
"generated" :
"installed") +
".txt";
1556 string moduleCachePathCanonical = moduleCachePath;
1559 string partialPath = moduleCachePathCanonical +
"/libVuoModuleCache-" + (generated ?
"generated" :
"installed");
1561 return partialPath +
".dylib";
1574 unsigned long &lastModified)
1592 string dir, file, ext;
1594 string fileName = file +
"." + ext;
1596 vector< pair<string, unsigned long> > existingRevisions;
1602 delete existingFile;
1605 if (existingRevisions.empty())
1611 auto latest = std::max_element(existingRevisions.begin(), existingRevisions.end(),
1612 [](pair<string, unsigned long> p1, pair<string, unsigned long> p2) { return p1.second < p2.second; });
1614 lastModified = latest->second;
1615 return latest->first;
1623 string moduleCachePath, file, ext;
1624 splitPath(dylibPath, moduleCachePath, file, ext);
1625 string dylibFileName = file +
"." + ext;
1641 string dir1, dir2, file1, file2, ext;
1642 splitPath(dylibPath1, dir1, file1, ext);
1643 splitPath(dylibPath2, dir2, file2, ext);
1650 if (parts1.size() == 3 && parts2.size() == 3 && parts1.back() != parts2.back())
1654 return parts1 == parts2;