2 Copyright (C) 2009 John Emmas
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program 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.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 extern "C" WINBASEAPI BOOL WINAPI
25 CreateHardLinkA( LPCSTR lpFileName,
26 LPCSTR lpExistingFileName,
27 LPSECURITY_ATTRIBUTES lpSecurityAttributes ); // Needs kernel32.lib on anything higher than Win2K
37 #include <pbd/error.h>
38 #include <ardourext/misc.h>
39 #include <ardourext/pthread.h> // Should ensure that we include the right
40 // version - but we'll check anyway, later
44 #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
48 int tz_minuteswest; /* minutes W of Greenwich */
49 int tz_dsttime; /* type of dst correction */
52 LIBPBD_API int PBD_APICALLTYPE
53 gettimeofday(struct timeval *__restrict tv, __timezone_ptr_t tz) // Does this need to be exported ?
56 unsigned __int64 tmpres = 0;
57 static int tzflag = 0;
61 GetSystemTimeAsFileTime(&ft);
63 tmpres |= ft.dwHighDateTime;
65 tmpres |= ft.dwLowDateTime;
67 /*converting file time to unix epoch*/
68 tmpres /= 10; /*convert into microseconds*/
69 tmpres -= DELTA_EPOCH_IN_MICROSECS;
70 tv->tv_sec = (long)(tmpres / 1000000UL);
71 tv->tv_usec = (long)(tmpres % 1000000UL);
76 struct timezone *ptz = static_cast<struct timezone*> (tz);
84 ptz->tz_minuteswest = _timezone / 60;
85 ptz->tz_dsttime = _daylight;
92 // Define the default comparison operators for Windows (ptw32) 'pthread_t' (not used
93 // by Ardour AFAIK but would be needed if an array of 'pthread_t' had to be sorted).
94 #ifndef PTHREAD_H // Defined by PTW32 (Linux and other versions define _PTHREAD_H)
95 #error "An incompatible version of 'pthread.h' is #included. Use only the Windows (ptw32) version!"
97 LIBPBD_API bool operator> (const pthread_t& lhs, const pthread_t& rhs)
99 return (std::greater<void*>()(lhs.p, rhs.p));
102 LIBPBD_API bool operator< (const pthread_t& lhs, const pthread_t& rhs)
104 return (std::less<void*>()(lhs.p, rhs.p));
107 LIBPBD_API bool operator!= (const pthread_t& lhs, const pthread_t& rhs)
109 return (std::not_equal_to<void*>()(lhs.p, rhs.p));
112 LIBPBD_API bool operator== (const pthread_t& lhs, const pthread_t& rhs)
114 return (!(lhs != rhs));
118 // Functions supplied (later) to std::transform
119 //***************************************************************
121 // invert_backslash()
123 // Examines a supplied ASCII character and (if the character is
124 // a backslash) converts it to a forward slash,
128 // The supplied character (converted, if it was a backslash)
130 char invert_backslash(char character)
132 if ('\\' == character)
138 //***************************************************************
140 // invert_forwardslash()
142 // Examines a supplied ASCII character and (if the character is
143 // a forward slash) converts it to a backslash,
147 // The supplied character (converted, if it was a fwd slash)
149 char invert_forwardslash(char character)
151 if ('/' == character)
158 //***************************************************************
162 // Emulates pread() using _lseek()/_read()/_lseek().
166 // On Success: The number of bytes read from the file
169 LIBPBD_API ssize_t PBD_APICALLTYPE
170 pread(int handle, void *buf, size_t nbytes, off_t offset)
175 off_t old_offset = _tell(handle);
181 _lseek(handle, offset, SEEK_SET);
182 ret = _read(handle, buf, nbytes);
185 _lseek(handle, old_offset, SEEK_SET);
193 //***************************************************************
197 // Emulates pwrite() using _lseek()/_write()/_lseek().
201 // On Success: The number of bytes written to the file
204 LIBPBD_API ssize_t PBD_APICALLTYPE
205 pwrite(int handle, const void *buf, size_t nbytes, off_t offset)
210 off_t old_offset = _lseek(handle, offset, SEEK_SET);
216 ret = _write(handle, buf, nbytes);
219 _lseek(handle, old_offset, SEEK_SET);
226 //***************************************************************
230 // Emulates round() using floor().
234 // On Success: The largest integer that is less than or
238 LIBPBD_API double PBD_APICALLTYPE
244 //***************************************************************
248 // Emulates trunc() using floor() and ceil().
252 // On Success: The largest integer whose magnitude is less
253 // than or equal to 'x' (regardless of sign).
256 LIBPBD_API double PBD_APICALLTYPE
265 //***************************************************************
269 // Emulates C99 log2() using log().
273 // On Success: The binary (base-2) logarithm of 'x'
274 // (e.g. log2(1024) == 10).
275 // On Failure: None, except that calling log(x) should generate
276 // an appropriate error for us (such as ERANGE etc).
278 LIBPBD_API double PBD_APICALLTYPE
281 return (log(x) / log((double)2.0));
286 //***************************************************************
288 // TestForMinimumSpecOS()
290 // Tests the user's OS to see if it is Win2K or later (could be
291 // expanded quite easily to accommodate other OS's)
295 // On Success: TRUE (if the user's OS matches the minimum spec)
296 // On Failure: FALSE otherwise
298 LIBPBD_API bool PBD_APICALLTYPE
299 TestForMinimumSpecOS(char *revision /* currently ignored */)
302 #ifdef PLATFORM_WINDOWS
304 HINSTANCE hKernelDll = (HINSTANCE)dlopen("kernel32.dll", RTLD_NOW);
308 // 'CreateHardLink()' is only available from Win2K onwards.
309 if (NULL != dlsym(hKernelDll, "CreateHardLinkA"))
315 // Other OS's could be accommodated here
321 //***************************************************************
325 // Emulates POSIX realpath() using Win32 _fullpath().
329 // On Success: A pointer to the resolved (absolute) path
332 LIBPBD_API char* PBD_APICALLTYPE
333 realpath (const char *original_path, char resolved_path[_MAX_PATH+1])
336 bool bIsSymLink = 0; // We'll probably need to test the incoming path
337 // to find out if it points to a Windows shortcut
338 // (or a hard link) and set this appropriately.
341 // At the moment I'm not sure if Windows '_fullpath()' is directly
342 // equivalent to POSIX 'realpath()' - in as much as the latter will
343 // resolve the supplied path if it happens to point to a symbolic
344 // link ('_fullpath()' probably DOESN'T do this but I'm not really
345 // sure if Ardour needs such functionality anyway). Therefore we'll
346 // possibly need to add that functionality here at a later date.
350 char temp[(MAX_PATH+1)*6]; // Allow for maximum length of a path in UTF8 characters
352 // POSIX 'realpath()' requires that the buffer size is at
353 // least PATH_MAX+1, so assume that the user knew this !!
354 pRet = _fullpath(temp, Glib::locale_from_utf8(original_path).c_str(), _MAX_PATH);
356 strcpy(resolved_path, Glib::locale_to_utf8(temp).c_str());
363 //***************************************************************
367 // Creates a pointer to a DIR structure, appropriately filled in
368 // and ready to begin a directory search iteration.
372 // On Success: Pointer to a (heap based) DIR structure
375 LIBPBD_API DIR* PBD_APICALLTYPE
376 opendir (const char *szPath)
378 wchar_t wpath[PATH_MAX+1];
387 if ((!errno) && ('\0' == szPath[0]))
390 // Determine if the given path really is a directory
393 if (0 == MultiByteToWideChar (CP_UTF8, 0, (LPCSTR)szPath, -1, (LPWSTR)wpath, sizeof(wpath)))
396 if ((!errno) && ((rc = GetFileAttributesW(wpath)) == -1))
399 if ((!errno) && (!(rc & FILE_ATTRIBUTE_DIRECTORY)))
400 // Error. Entry exists but not a directory. */
405 // Allocate enough memory to store DIR structure, plus
406 // the complete directory path originally supplied.
407 pDir = (DIR *)malloc(sizeof(DIR) + strlen(szPath) + strlen("\\") + strlen ("*"));
411 // Error - out of memory
418 // Create the search expression
419 strcpy(pDir->dd_name, szPath);
421 // Add a backslash if the path doesn't already end with one
422 if (pDir->dd_name[0] != '\0' &&
423 pDir->dd_name[strlen(pDir->dd_name) - 1] != '/' &&
424 pDir->dd_name[strlen(pDir->dd_name) - 1] != '\\')
426 strcat (pDir->dd_name, "\\");
429 // Add the search pattern
430 strcat(pDir->dd_name, "*");
432 // Initialize handle to -1 so that a premature closedir()
433 // doesn't try to call _findclose() on it.
434 pDir->dd_handle = (-1);
436 // Initialize the status
439 // Initialize the dirent structure. 'ino' and 'reclen' are invalid under Win32
440 // and 'name' simply points at the appropriate part of the findfirst_t struct.
441 pDir->dd_dir.d_ino = 0;
442 pDir->dd_dir.d_reclen = 0;
443 pDir->dd_dir.d_namlen = 0;
444 strcpy(pDir->dd_dir.d_name, pDir->dd_dta.name);
446 return (pDir); // Succeeded
451 return (DIR *) 0; // Failed
455 //***************************************************************
459 // Return a pointer to a dirent struct, filled with information
460 // about the next entry in the directory.
464 // On Success: A pointer to the supplied DIR's 'dirent' struct
467 LIBPBD_API struct dirent* PBD_APICALLTYPE
473 // Check for valid DIR struct
477 if ((strcmp(pDir->dd_dir.d_name, pDir->dd_dta.name)) && (!errno))
478 // The structure does not seem to be set up correctly
482 if (pDir->dd_stat < 0)
484 // We have already returned all files in this directory
485 // (or the structure has an invalid dd_stat).
486 return (struct dirent *)0;
488 else if (pDir->dd_stat == 0)
490 // We haven't started the search yet.
492 pDir->dd_handle = _findfirst (Glib::locale_from_utf8(pDir->dd_name).c_str(), &(pDir->dd_dta));
494 if (pDir->dd_handle == -1)
495 // The directory is empty
502 // Do not return ENOENT on last file in directory
505 // Get the next search entry
506 if (_findnext (pDir->dd_handle, &(pDir->dd_dta)))
508 // We are off the end or otherwise error
510 _findclose (pDir->dd_handle);
511 pDir->dd_handle = -1;
515 // Update to indicate the correct status number
519 if (pDir->dd_stat > 0)
521 // We successfully got an entry. Details about the file are
522 // already appropriately filled in except for the length of
524 strcpy(pDir->dd_dir.d_name, pDir->dd_dta.name);
525 pDir->dd_dir.d_namlen = strlen (pDir->dd_dir.d_name);
526 return (&pDir->dd_dir); // Succeeded
530 return (struct dirent *) 0; // Failed
534 //***************************************************************
538 // Frees the resources allocated by opendir().
545 LIBPBD_API int PBD_APICALLTYPE
556 if ((-1) != pDir->dd_handle)
557 rc = _findclose (pDir->dd_handle);
559 // Free the DIR structure
562 return rc; // Succeeded
565 return (-1); // Failed
568 //***************************************************************
572 // Emulates Linux mkstemp() using Win32 _mktemp() and _open() etc.
576 // On Success: A file descriptor for the opened file.
579 LIBPBD_API int PBD_APICALLTYPE
580 mkstemp (char *template_name)
584 char szTempPath[PATH_MAX+100]; // Just ensure we have plenty of buffer space
586 if (NULL != (szFileName = _mktemp(template_name)))
588 if (0 != ::GetTempPathA(sizeof(szTempPath), szTempPath))
590 strcat(szTempPath, szFileName);
591 ret = _open(szTempPath, (_O_CREAT|_O_BINARY|_O_TEMPORARY|_O_RDWR|_O_TRUNC), _S_IWRITE);
599 //***************************************************************
603 // Emulates Linux link() using Win32 CreateHardLink()(NTFS only).
607 // On Success: Non-zero.
608 // On Failure: Zero (call 'GetLastError()' to retrieve info)
610 LIBPBD_API int PBD_APICALLTYPE
611 ntfs_link (const char *existing_filepath, const char *link_filepath)
613 int ret = 1; // 'ERROR_INVALID_FUNCTION'
614 bool bValidPath = false;
616 // Make sure we've been sent a valid input string
617 if (existing_filepath && link_filepath)
619 std::string strRoot = existing_filepath;
621 if ((1 < strRoot.length()) && ('\\' == existing_filepath[0]) && ('\\' == existing_filepath[1]))
625 // We've been sent a network path. Convert backslashes to forward slashes temporarily.
626 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
628 // Now, if there are less than four slashes, add a fourth one or abort
629 std::string::iterator iter = strRoot.begin();
630 while ((slashcnt < 4) && (iter != strRoot.end()))
640 // If only 3 slashes were counted, add a trailing slash
644 // Now find the position of the fourth slash
645 iter = strRoot.begin();
647 for (slashcnt=0; slashcnt<4;)
654 if (++iter == strRoot.end())
658 strRoot.resize(charcnt);
664 // Assume a standard Windows style path
665 if (1 < strRoot.length() && (':' == existing_filepath[1]))
667 // Convert backslashes to forward slashes temporarily.
668 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
670 if (2 == strRoot.length())
673 if ('/' == strRoot[2])
683 char szFileSystemType[_MAX_PATH+1];
685 // Restore the original backslashes
686 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_forwardslash);
688 // Windows only supports hard links for the NTFS filing
689 // system, so let's make sure that's what we're using!!
690 if (::GetVolumeInformationA(strRoot.c_str(), NULL, 0, NULL, NULL, NULL, szFileSystemType, _MAX_PATH+1))
692 std::string strRootFileSystemType = szFileSystemType;
693 std::transform(strRootFileSystemType.begin(), strRootFileSystemType.end(), strRootFileSystemType.begin(), ::toupper);
694 #if (_WIN32_WINNT >= 0x0500)
695 if (0 == strRootFileSystemType.compare("NTFS"))
697 if (TestForMinimumSpecOS()) // Hard links were only available from Win2K onwards
698 if (0 == CreateHardLinkA(link_filepath, existing_filepath, NULL))
699 { // Note that the above API call cannot create a link to a directory, so
700 // should we also be checking that the supplied path was actually a file?
701 ret = GetLastError();
704 SetLastError(ret = 0); // 'NO_ERROR'
708 ret = 4300; // 'ERROR_INVALID_MEDIA'
714 ret = 123; // 'ERROR_INVALID_NAME'
717 ret = 161; // 'ERROR_BAD_PATHNAME'
729 //***************************************************************
733 // Emulates Linux unlink() using Win32 DeleteFile()(NTFS only).
737 // On Success: Non-zero.
738 // On Failure: Zero (call 'GetLastError()' to retrieve info)
740 LIBPBD_API int PBD_APICALLTYPE
741 ntfs_unlink (const char *link_filepath)
743 int ret = 1; // 'ERROR_INVALID_FUNCTION'
744 bool bValidPath = false;
746 // Make sure we've been sent a valid input string
749 std::string strRoot = link_filepath;
751 if ((1 < strRoot.length()) && ('\\' == link_filepath[0]) && ('\\' == link_filepath[1]))
755 // We've been sent a network path. Convert backslashes to forward slashes temporarily.
756 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
758 // Now, if there are less than four slashes, add a fourth one or abort
759 std::string::iterator iter = strRoot.begin();
760 while ((slashcnt < 4) && (iter != strRoot.end()))
770 // If only 3 slashes were counted, add a trailing slash
774 // Now find the position of the fourth slash
775 iter = strRoot.begin();
777 for (slashcnt=0; slashcnt<4;)
784 if (++iter == strRoot.end())
788 strRoot.resize(charcnt);
794 // Assume a standard Windows style path
795 if (1 < strRoot.length() && (':' == link_filepath[1]))
797 // Convert backslashes to forward slashes temporarily.
798 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
800 if (2 == strRoot.length())
803 if ('/' == strRoot[2])
813 char szFileSystemType[_MAX_PATH+1];
815 // Restore the original backslashes
816 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_forwardslash);
818 // Windows only supports hard links for the NTFS filing
819 // system, so let's make sure that's what we're using!!
820 if (::GetVolumeInformationA(strRoot.c_str(), NULL, 0, NULL, NULL, NULL, szFileSystemType, _MAX_PATH+1))
822 std::string strRootFileSystemType = szFileSystemType;
823 std::transform(strRootFileSystemType.begin(), strRootFileSystemType.end(), strRootFileSystemType.begin(), ::toupper);
824 #if (_WIN32_WINNT >= 0x0500)
825 if (0 == strRootFileSystemType.compare("NTFS"))
826 if (TestForMinimumSpecOS()) // Hard links were only available from Win2K onwards
827 if (0 == DeleteFileA(link_filepath))
828 ret = GetLastError();
830 ret = 0; // 'NO_ERROR'
835 ret = 123; // 'ERROR_INVALID_NAME'
838 ret = 161; // 'ERROR_BAD_PATHNAME'
852 //***************************************************************
856 // Emulates POSIX dlopen() using Win32 LoadLibrary().
860 // On Success: A handle to the opened DLL
863 LIBPBD_API void* PBD_APICALLTYPE
864 dlopen (const char *file_name, int mode)
866 // Note that 'mode' is ignored in Win32
867 return(::LoadLibraryA(Glib::locale_from_utf8(file_name).c_str()));
871 //***************************************************************
875 // Emulates POSIX dlclose() using Win32 FreeLibrary().
879 // On Success: A non-zero number
882 LIBPBD_API int PBD_APICALLTYPE
883 dlclose (void *handle)
885 return (::FreeLibrary((HMODULE)handle));
889 //***************************************************************
893 // Emulates POSIX dlsym() using Win32 GetProcAddress().
897 // On Success: A pointer to the found function or symbol
900 LIBPBD_API void* PBD_APICALLTYPE
901 dlsym (void *handle, const char *symbol_name)
903 // First test for RTLD_DEFAULT and RTLD_NEXT
904 if ((handle == 0/*RTLD_DEFAULT*/) || (handle == ((void *) -1L)/*RTLD_NEXT*/))
906 return 0; // Not yet supported for Win32
909 return (::GetProcAddress((HMODULE)handle, symbol_name));
912 #define LOCAL_ERROR_BUF_SIZE 1024
913 static char szLastWinError[LOCAL_ERROR_BUF_SIZE];
914 //***************************************************************
918 // Emulates POSIX dlerror() using Win32 GetLastError().
922 // On Success: The translated message corresponding to the
924 // On Failure: NULL (if the last error was ERROR_SUCCESS)
926 LIBPBD_API char* PBD_APICALLTYPE
929 DWORD dwLastErrorId = GetLastError();
930 if (ERROR_SUCCESS == dwLastErrorId)
934 if (0 == FormatMessage(
935 FORMAT_MESSAGE_FROM_SYSTEM,
940 LOCAL_ERROR_BUF_SIZE,
943 sprintf(szLastWinError, "Could not decipher the previous error message");
946 // POSIX dlerror() seems to reset the
947 // error system, so emulate that here
948 SetLastError(ERROR_SUCCESS);
951 return(szLastWinError);
954 #endif // COMPILER_MSVC