-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOVR_CAPIShim_windows.c
1914 lines (1595 loc) · 73.1 KB
/
OVR_CAPIShim_windows.c
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
/************************************************************************************
Filename : OVR_CAPIShim.c
Content : CAPI DLL user library
Created : November 20, 2014
Copyright : Copyright 2014-2016 Oculus VR, LLC All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.3
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#include "OVR_CAPI.h"
#include "OVR_Version.h"
#include "OVR_ErrorCode.h"
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#if defined(_WIN32)
#if defined(_MSC_VER)
#pragma warning(push, 0)
#endif
#include <Windows.h>
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#include "OVR_CAPI_D3D.h"
#else
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#include <sys/syslimits.h>
#include <libgen.h>
#include <pwd.h>
#include <unistd.h>
#endif
#include <dlfcn.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include "OVR_CAPI_GL.h"
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable: 4996) // 'getenv': This function or variable may be unsafe.
#endif
static const uint8_t OculusSDKUniqueIdentifier[] =
{
0x9E, 0xB2, 0x0B, 0x1A, 0xB7, 0x97, 0x09, 0x20, 0xE0, 0xFB, 0x83, 0xED, 0xF8, 0x33, 0x5A, 0xEB,
0x80, 0x4D, 0x8E, 0x92, 0x20, 0x69, 0x13, 0x56, 0xB4, 0xBB, 0xC4, 0x85, 0xA7, 0x9E, 0xA4, 0xFE,
OVR_MAJOR_VERSION, OVR_MINOR_VERSION, OVR_PATCH_VERSION
};
static const uint8_t OculusSDKUniqueIdentifierXORResult = 0xcb;
// -----------------------------------------------------------------------------------
// ***** OVR_ENABLE_DEVELOPER_SEARCH
//
// If defined then our shared library loading code searches for developer build
// directories.
//
#if !defined(OVR_ENABLE_DEVELOPER_SEARCH)
#endif
// -----------------------------------------------------------------------------------
// ***** OVR_BUILD_DEBUG
//
// Defines OVR_BUILD_DEBUG when the compiler default debug preprocessor is set.
//
// If you want to control the behavior of these flags, then explicitly define
// either -DOVR_BUILD_RELEASE or -DOVR_BUILD_DEBUG in the compiler arguments.
#if !defined(OVR_BUILD_DEBUG) && !defined(OVR_BUILD_RELEASE)
#if defined(_MSC_VER)
#if defined(_DEBUG)
#define OVR_BUILD_DEBUG
#endif
#else
#if defined(DEBUG)
#define OVR_BUILD_DEBUG
#endif
#endif
#endif
//-----------------------------------------------------------------------------------
// ***** FilePathCharType, ModuleHandleType, ModuleFunctionType
//
#if defined(_WIN32) // We need to use wchar_t on Microsoft platforms, as that's the native file system character type.
#define FilePathCharType wchar_t // #define instead of typedef because debuggers (VC++, XCode) don't recognize typedef'd types as a string type.
typedef HMODULE ModuleHandleType;
typedef FARPROC ModuleFunctionType;
#else
#define FilePathCharType char
typedef void* ModuleHandleType;
typedef void* ModuleFunctionType;
#endif
#define ModuleHandleTypeNull ((ModuleHandleType)NULL)
#define ModuleFunctionTypeNull ((ModuleFunctionType)NULL)
//-----------------------------------------------------------------------------------
// ***** OVR_MAX_PATH
//
#if !defined(OVR_MAX_PATH)
#if defined(_WIN32)
#define OVR_MAX_PATH _MAX_PATH
#elif defined(__APPLE__)
#define OVR_MAX_PATH PATH_MAX
#else
#define OVR_MAX_PATH 1024
#endif
#endif
//-----------------------------------------------------------------------------------
// ***** OVR_DECLARE_IMPORT
//
// Creates typedef and pointer declaration for a function of a given signature.
// The typedef is <FunctionName>Type, and the pointer is <FunctionName>Ptr.
//
// Example usage:
// int MultiplyValues(float x, float y); // Assume this function exists in an external shared library. We don't actually need to redeclare it.
// OVR_DECLARE_IMPORT(int, MultiplyValues, (float x, float y)) // This creates a local typedef and pointer for it.
#define OVR_DECLARE_IMPORT(ReturnValue, FunctionName, Arguments) \
typedef ReturnValue (OVR_CDECL *FunctionName##Type)Arguments; \
FunctionName##Type FunctionName##Ptr = NULL;
//-----------------------------------------------------------------------------------
// ***** OVR_GETFUNCTION
//
// Loads <FunctionName>Ptr from hLibOVR if not already loaded.
// Assumes a variable named <FunctionName>Ptr of type <FunctionName>Type exists which is called <FunctionName> in LibOVR.
//
// Example usage:
// OVR_GETFUNCTION(MultiplyValues) // Normally this would be done on library init and not before every usage.
// int result = MultiplyValuesPtr(3.f, 4.f);
#if !defined(OVR_DLSYM)
#if defined(_WIN32)
#define OVR_DLSYM(dlImage, name) GetProcAddress(dlImage, name)
#else
#define OVR_DLSYM(dlImage, name) dlsym(dlImage, name)
#endif
#endif
#define OVR_GETFUNCTION(f) \
if(!f##Ptr) \
{ \
union \
{ \
f##Type p1; \
ModuleFunctionType p2; \
} u; \
u.p2 = OVR_DLSYM(hLibOVR, #f); \
f##Ptr = u.p1; \
}
static size_t OVR_strlcpy(char* dest, const char* src, size_t destsize)
{
const char* s = src;
size_t n = destsize;
if(n && --n)
{
do{
if((*dest++ = *s++) == 0)
break;
} while(--n);
}
if(!n)
{
if(destsize)
*dest = 0;
while(*s++)
{ }
}
return (size_t)((s - src) - 1);
}
static size_t OVR_strlcat(char* dest, const char* src, size_t destsize)
{
const size_t d = destsize ? strlen(dest) : 0;
const size_t s = strlen(src);
const size_t t = s + d;
if(t < destsize)
memcpy(dest + d, src, (s + 1) * sizeof(*src));
else
{
if(destsize)
{
memcpy(dest + d, src, ((destsize - d) - 1) * sizeof(*src));
dest[destsize - 1] = 0;
}
}
return t;
}
#if defined(__APPLE__)
static ovrBool OVR_strend(const char* pStr, const char* pFind, size_t strLength, size_t findLength)
{
if(strLength == (size_t)-1)
strLength = strlen(pStr);
if(findLength == (size_t)-1)
findLength = strlen(pFind);
if(strLength >= findLength)
return (strcmp(pStr + strLength - findLength, pFind) == 0);
return ovrFalse;
}
static ovrBool OVR_isBundleFolder(const char* filePath)
{
static const char* extensionArray[] = { ".app", ".bundle", ".framework", ".plugin", ".kext" };
size_t i;
for(i = 0; i < sizeof(extensionArray)/sizeof(extensionArray[0]); i++)
{
if(OVR_strend(filePath, extensionArray[i], (size_t)-1, (size_t)-1))
return ovrTrue;
}
return ovrFalse;
}
#endif
#if defined(OVR_ENABLE_DEVELOPER_SEARCH)
// Returns true if the path begins with the given prefix.
// Doesn't support non-ASCII paths, else the return value may be incorrect.
static int OVR_PathStartsWith(const FilePathCharType* path, const char* prefix)
{
while(*prefix)
{
if(tolower((unsigned char)*path++) != tolower((unsigned char)*prefix++))
return ovrFalse;
}
return ovrTrue;
}
#endif
static ovrBool OVR_GetCurrentWorkingDirectory(FilePathCharType* directoryPath, size_t directoryPathCapacity)
{
#if defined(_WIN32)
DWORD dwSize = GetCurrentDirectoryW((DWORD)directoryPathCapacity, directoryPath);
if((dwSize > 0) && (directoryPathCapacity > 1)) // Test > 1 so we have room to possibly append a \ char.
{
size_t length = wcslen(directoryPath);
if((length == 0) || ((directoryPath[length - 1] != L'\\') && (directoryPath[length - 1] != L'/')))
{
directoryPath[length++] = L'\\';
directoryPath[length] = L'\0';
}
return ovrTrue;
}
#else
char* cwd = getcwd(directoryPath, directoryPathCapacity);
if(cwd && directoryPath[0] && (directoryPathCapacity > 1)) // Test > 1 so we have room to possibly append a / char.
{
size_t length = strlen(directoryPath);
if((length == 0) || (directoryPath[length - 1] != '/'))
{
directoryPath[length++] = '/';
directoryPath[length] = '\0';
}
return ovrTrue;
}
#endif
if(directoryPathCapacity > 0)
directoryPath[0] = '\0';
return ovrFalse;
}
// The appContainer argument is specific currently to only Macintosh. If true and the application is a .app bundle then it returns the
// location of the bundle and not the path to the executable within the bundle. Else return the path to the executable binary itself.
// The moduleHandle refers to the relevant dynamic (a.k.a. shared) library. The main executable is the main module, and each of the shared
// libraries is a module. This way you can specify that you want to know the directory of the given shared library, which may be different
// from the main executable. If the moduleHandle is NULL then the current application module is used.
static ovrBool OVR_GetCurrentApplicationDirectory(FilePathCharType* directoryPath, size_t directoryPathCapacity, ovrBool appContainer, ModuleHandleType moduleHandle)
{
#if defined(_WIN32)
DWORD length = GetModuleFileNameW(moduleHandle, directoryPath, (DWORD)directoryPathCapacity);
DWORD pos;
if((length != 0) && (length < (DWORD)directoryPathCapacity)) // If there wasn't an error and there was enough capacity...
{
for(pos = length; (pos > 0) && (directoryPath[pos] != '\\') && (directoryPath[pos] != '/'); --pos)
{
if((directoryPath[pos - 1] != '\\') && (directoryPath[pos - 1] != '/'))
directoryPath[pos - 1] = 0;
}
return ovrTrue;
}
(void)appContainer; // Not used on this platform.
#elif defined(__APPLE__)
uint32_t directoryPathCapacity32 = (uint32_t)directoryPathCapacity;
int result = _NSGetExecutablePath(directoryPath, &directoryPathCapacity32);
if(result == 0) // If success...
{
char realPath[OVR_MAX_PATH];
if(realpath(directoryPath, realPath)) // realpath returns the canonicalized absolute file path.
{
size_t length = 0;
if(appContainer) // If the caller wants the path to the containing bundle...
{
char containerPath[OVR_MAX_PATH];
ovrBool pathIsContainer;
OVR_strlcpy(containerPath, realPath, sizeof(containerPath));
pathIsContainer = OVR_isBundleFolder(containerPath);
while(!pathIsContainer && strncmp(containerPath, ".", OVR_MAX_PATH) && strncmp(containerPath, "/", OVR_MAX_PATH)) // While the container we're looking for is not found and while the path doesn't start with a . or /
{
OVR_strlcpy(containerPath, dirname(containerPath), sizeof(containerPath));
pathIsContainer = OVR_isBundleFolder(containerPath);
}
if(pathIsContainer)
length = OVR_strlcpy(directoryPath, containerPath, directoryPathCapacity);
}
if(length == 0) // If not set above in the appContainer block...
length = OVR_strlcpy(directoryPath, realPath, directoryPathCapacity);
while(length-- && (directoryPath[length] != '/'))
directoryPath[length] = '\0'; // Strip the file name from the file path, leaving a trailing / char.
return ovrTrue;
}
}
(void)moduleHandle; // Not used on this platform.
#else
ssize_t length = readlink("/proc/self/exe", directoryPath, directoryPathCapacity);
ssize_t pos;
if(length > 0)
{
for(pos = length; (pos > 0) && (directoryPath[pos] != '/'); --pos)
{
if(directoryPath[pos - 1] != '/')
directoryPath[pos - 1] = '\0';
}
return ovrTrue;
}
(void)appContainer; // Not used on this platform.
(void)moduleHandle;
#endif
if(directoryPathCapacity > 0)
directoryPath[0] = '\0';
return ovrFalse;
}
#if defined(_WIN32) || defined(OVR_ENABLE_DEVELOPER_SEARCH) // Used only in these cases
// Get the file path to the current module's (DLL or EXE) directory within the current process.
// Will be different from the process module handle if the current module is a DLL and is in a different directory than the EXE module.
// If successful then directoryPath will be valid and ovrTrue is returned, else directoryPath will be empty and ovrFalse is returned.
static ovrBool OVR_GetCurrentModuleDirectory(FilePathCharType* directoryPath, size_t directoryPathCapacity, ovrBool appContainer)
{
#if defined(_WIN32)
HMODULE hModule;
BOOL result = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)(uintptr_t)OVR_GetCurrentModuleDirectory, &hModule);
if(result)
OVR_GetCurrentApplicationDirectory(directoryPath, directoryPathCapacity, ovrTrue, hModule);
else
directoryPath[0] = 0;
(void)appContainer;
return directoryPath[0] ? ovrTrue : ovrFalse;
#else
return OVR_GetCurrentApplicationDirectory(directoryPath, directoryPathCapacity, appContainer, NULL);
#endif
}
#endif
#if defined(_WIN32)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4201)
#endif
#include <Softpub.h>
#include <Wincrypt.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// Expected certificates:
#define ExpectedNumCertificates 3
typedef struct CertificateEntry_t {
const wchar_t* Issuer;
const wchar_t* Subject;
} CertificateEntry;
CertificateEntry NewCertificateChain[ExpectedNumCertificates] = {
{ L"DigiCert SHA2 Assured ID Code Signing CA", L"Oculus VR, LLC" },
{ L"DigiCert Assured ID Root CA", L"DigiCert SHA2 Assured ID Code Signing CA" },
{ L"DigiCert Assured ID Root CA", L"DigiCert Assured ID Root CA" },
};
#define CertificateChainCount 1
CertificateEntry* AllowedCertificateChains[CertificateChainCount] = {
NewCertificateChain
};
typedef WINCRYPT32API
DWORD
(WINAPI *PtrCertGetNameStringW)(
PCCERT_CONTEXT pCertContext,
DWORD dwType,
DWORD dwFlags,
void *pvTypePara,
LPWSTR pszNameString,
DWORD cchNameString
);
typedef LONG (WINAPI *PtrWinVerifyTrust)(HWND hwnd, GUID *pgActionID,
LPVOID pWVTData);
typedef CRYPT_PROVIDER_DATA * (WINAPI *PtrWTHelperProvDataFromStateData)(HANDLE hStateData);
typedef CRYPT_PROVIDER_SGNR * (WINAPI *PtrWTHelperGetProvSignerFromChain)(
CRYPT_PROVIDER_DATA *pProvData, DWORD idxSigner, BOOL fCounterSigner, DWORD idxCounterSigner);
PtrCertGetNameStringW m_PtrCertGetNameStringW = 0;
PtrWinVerifyTrust m_PtrWinVerifyTrust = 0;
PtrWTHelperProvDataFromStateData m_PtrWTHelperProvDataFromStateData = 0;
PtrWTHelperGetProvSignerFromChain m_PtrWTHelperGetProvSignerFromChain = 0;
typedef enum ValidateCertificateContentsResult_
{
VCCRSuccess = 0,
VCCRErrorCertCount = -1,
VCCRErrorTrust = -2,
VCCRErrorValidation = -3
} ValidateCertificateContentsResult;
static ValidateCertificateContentsResult ValidateCertificateContents(CertificateEntry* chain, CRYPT_PROVIDER_SGNR* cps)
{
int certIndex;
if (!cps ||
!cps->pasCertChain ||
cps->csCertChain != ExpectedNumCertificates)
{
return VCCRErrorCertCount;
}
for (certIndex = 0; certIndex < ExpectedNumCertificates; ++certIndex)
{
CRYPT_PROVIDER_CERT* pCertData = &cps->pasCertChain[certIndex];
wchar_t subjectStr[400] = { 0 };
wchar_t issuerStr[400] = { 0 };
if ((pCertData->fSelfSigned && !pCertData->fTrustedRoot) ||
pCertData->fTestCert)
{
return VCCRErrorTrust;
}
m_PtrCertGetNameStringW(
pCertData->pCert,
CERT_NAME_ATTR_TYPE,
0,
szOID_COMMON_NAME,
subjectStr,
ARRAYSIZE(subjectStr));
m_PtrCertGetNameStringW(
pCertData->pCert,
CERT_NAME_ATTR_TYPE,
CERT_NAME_ISSUER_FLAG,
0,
issuerStr,
ARRAYSIZE(issuerStr));
if (wcscmp(subjectStr, chain[certIndex].Subject) != 0 ||
wcscmp(issuerStr, chain[certIndex].Issuer) != 0)
{
return VCCRErrorValidation;
}
}
return VCCRSuccess;
}
#define OVR_SIGNING_CONVERT_PTR(ftype, fptr, procaddr) { \
union { ftype p1; ModuleFunctionType p2; } u; \
u.p2 = procaddr; \
fptr = u.p1; }
static HANDLE OVR_Win32_SignCheck(FilePathCharType* fullPath)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
WINTRUST_FILE_INFO fileData;
WINTRUST_DATA wintrustData;
GUID actionGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
LONG resultStatus;
int verified = 0;
HMODULE libWinTrust = LoadLibraryW(L"wintrust");
HMODULE libCrypt32 = LoadLibraryW(L"crypt32");
if (libWinTrust == NULL || libCrypt32 == NULL)
{
return INVALID_HANDLE_VALUE;
}
OVR_SIGNING_CONVERT_PTR(PtrCertGetNameStringW, m_PtrCertGetNameStringW, GetProcAddress(libCrypt32, "CertGetNameStringW"));
OVR_SIGNING_CONVERT_PTR(PtrWinVerifyTrust, m_PtrWinVerifyTrust, GetProcAddress(libWinTrust, "WinVerifyTrust"));
OVR_SIGNING_CONVERT_PTR(PtrWTHelperProvDataFromStateData, m_PtrWTHelperProvDataFromStateData, GetProcAddress(libWinTrust, "WTHelperProvDataFromStateData"));
OVR_SIGNING_CONVERT_PTR(PtrWTHelperGetProvSignerFromChain, m_PtrWTHelperGetProvSignerFromChain, GetProcAddress(libWinTrust, "WTHelperGetProvSignerFromChain"));
if (m_PtrCertGetNameStringW == NULL || m_PtrWinVerifyTrust == NULL ||
m_PtrWTHelperProvDataFromStateData == NULL || m_PtrWTHelperGetProvSignerFromChain == NULL)
{
return INVALID_HANDLE_VALUE;
}
if (!fullPath)
{
return INVALID_HANDLE_VALUE;
}
hFile = CreateFileW(fullPath, GENERIC_READ, FILE_SHARE_READ,
0, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, 0);
if (hFile == INVALID_HANDLE_VALUE)
{
return INVALID_HANDLE_VALUE;
}
ZeroMemory(&fileData, sizeof(fileData));
fileData.cbStruct = sizeof(fileData);
fileData.pcwszFilePath = fullPath;
fileData.hFile = hFile;
ZeroMemory(&wintrustData, sizeof(wintrustData));
wintrustData.cbStruct = sizeof(wintrustData);
wintrustData.pFile = &fileData;
wintrustData.dwUnionChoice = WTD_CHOICE_FILE; // Specify WINTRUST_FILE_INFO.
wintrustData.dwUIChoice = WTD_UI_NONE; // Do not display any UI.
wintrustData.dwUIContext = WTD_UICONTEXT_EXECUTE; // Hint that this is about app execution.
wintrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
wintrustData.dwProvFlags = WTD_REVOCATION_CHECK_NONE;
wintrustData.dwStateAction = WTD_STATEACTION_VERIFY;
wintrustData.hWVTStateData = 0;
resultStatus = m_PtrWinVerifyTrust(
(HWND)INVALID_HANDLE_VALUE, // Do not display any UI.
&actionGUID, // V2 verification
&wintrustData);
if (resultStatus == ERROR_SUCCESS &&
wintrustData.hWVTStateData != 0 &&
wintrustData.hWVTStateData != INVALID_HANDLE_VALUE)
{
CRYPT_PROVIDER_DATA* cpd = m_PtrWTHelperProvDataFromStateData(wintrustData.hWVTStateData);
if (cpd && cpd->csSigners == 1)
{
CRYPT_PROVIDER_SGNR* cps = m_PtrWTHelperGetProvSignerFromChain(cpd, 0, FALSE, 0);
int chainIndex;
for (chainIndex = 0; chainIndex < CertificateChainCount; ++chainIndex)
{
CertificateEntry* chain = AllowedCertificateChains[chainIndex];
if (0 == ValidateCertificateContents(chain, cps))
{
verified = 1;
break;
}
}
}
}
wintrustData.dwStateAction = WTD_STATEACTION_CLOSE;
m_PtrWinVerifyTrust(
(HWND)INVALID_HANDLE_VALUE, // Do not display any UI.
&actionGUID, // V2 verification
&wintrustData);
if (verified != 1)
{
CloseHandle(hFile);
return INVALID_HANDLE_VALUE;
}
return hFile;
}
#endif // #if defined(_WIN32)
static ModuleHandleType OVR_OpenLibrary(const FilePathCharType* libraryPath)
{
#if defined(_WIN32)
DWORD fullPathNameLen = 0;
FilePathCharType fullPath[MAX_PATH] = { 0 };
HANDLE hFilePinned = INVALID_HANDLE_VALUE;
ModuleHandleType hModule = 0;
fullPathNameLen = GetFullPathNameW(libraryPath, MAX_PATH, fullPath, 0);
if (fullPathNameLen <= 0 || fullPathNameLen >= MAX_PATH)
{
return 0;
}
fullPath[MAX_PATH - 1] = 0;
hFilePinned = OVR_Win32_SignCheck(fullPath);
if (hFilePinned == INVALID_HANDLE_VALUE)
{
return 0;
}
hModule = LoadLibraryW(fullPath);
if (hFilePinned != INVALID_HANDLE_VALUE)
{
CloseHandle(hFilePinned);
}
return hModule;
#else
// Don't bother trying to dlopen() a file that is not even there.
if (access(libraryPath, X_OK | R_OK ) != 0)
{
return NULL;
}
dlerror(); // Clear any previous dlopen() errors
// Use RTLD_NOW because we don't want unexpected stalls at runtime, and the library isn't very large.
// Use RTLD_LOCAL to avoid unilaterally exporting resolved symbols to the rest of this process.
void *lib = dlopen(libraryPath, RTLD_NOW | RTLD_LOCAL);
if (!lib)
{
#if defined(__APPLE__)
// TODO: Output the error in whatever logging system OSX uses (jhughes)
#else // __APPLE__
fprintf(stderr, "ERROR: Can't load '%s':\n%s\n", libraryPath, dlerror());
#endif // __APPLE__
}
return lib;
#endif
}
static void OVR_CloseLibrary(ModuleHandleType hLibrary)
{
if (hLibrary)
{
#if defined(_WIN32)
// We may need to consider what to do in the case that the library is in an exception state.
// In a Windows C++ DLL, all global objects (including static members of classes) will be constructed just
// before the calling of the DllMain with DLL_PROCESS_ATTACH and they will be destroyed just after
// the call of the DllMain with DLL_PROCESS_DETACH. We may need to intercept DLL_PROCESS_DETACH and
// have special handling for the case that the DLL is broken.
FreeLibrary(hLibrary);
#else
dlclose(hLibrary);
#endif
}
}
// Returns a valid ModuleHandleType (e.g. Windows HMODULE) or returns ModuleHandleTypeNull (e.g. NULL).
// The caller is required to eventually call OVR_CloseLibrary on a valid return handle.
//
static ModuleHandleType OVR_FindLibraryPath(int requestedProductVersion, int requestedMajorVersion,
FilePathCharType* libraryPath, size_t libraryPathCapacity)
{
ModuleHandleType moduleHandle;
int printfResult;
FilePathCharType developerDir[OVR_MAX_PATH] = { '\0' };
#if defined(_MSC_VER)
#if defined(_WIN64)
const char* pBitDepth = "64";
#else
const char* pBitDepth = "32";
#endif
#elif defined(__APPLE__)
// For Apple platforms we are using a Universal Binary LibOVRRT dylib which has both 32 and 64 in it.
#else // Other Unix.
#if defined(__x86_64__)
const char* pBitDepth = "64";
#else
const char* pBitDepth = "32";
#endif
#endif
(void)requestedProductVersion;
moduleHandle = ModuleHandleTypeNull;
if(libraryPathCapacity)
libraryPath[0] = '\0';
// Note: OVR_ENABLE_DEVELOPER_SEARCH is deprecated in favor of the simpler LIBOVR_DLL_DIR, as the edge
// case uses of the former created some complications that may be best solved by simply using a LIBOVR_DLL_DIR
// environment variable which the user can set in their debugger or system environment variables.
#if (defined(_MSC_VER) || defined(_WIN32)) && !defined(OVR_FILE_PATH_SEPARATOR)
#define OVR_FILE_PATH_SEPARATOR "\\"
#else
#define OVR_FILE_PATH_SEPARATOR "/"
#endif
{
const char* pLibOvrDllDir = getenv("LIBOVR_DLL_DIR"); // Example value: /dev/OculusSDK/Main/LibOVR/Mac/Debug/
if(pLibOvrDllDir)
{
char developerDir8[OVR_MAX_PATH];
size_t length = OVR_strlcpy(developerDir8, pLibOvrDllDir, sizeof(developerDir8)); // If missing a trailing path separator then append one.
if((length > 0) && (length < sizeof(developerDir8)) && (developerDir8[length - 1] != OVR_FILE_PATH_SEPARATOR[0]))
{
length = OVR_strlcat(developerDir8, OVR_FILE_PATH_SEPARATOR, sizeof(developerDir8));
if(length < sizeof(developerDir8))
{
#if defined(_WIN32)
size_t i;
for(i = 0; i <= length; ++i) // ASCII conversion of 8 to 16 bit text.
developerDir[i] = (FilePathCharType)(uint8_t)developerDir8[i];
#else
OVR_strlcpy(developerDir, developerDir8, sizeof(developerDir));
#endif
}
}
}
}
// Support checking for a developer library location override via the OVR_SDK_ROOT environment variable.
// This pathway is deprecated in favor of using LIBOVR_DLL_DIR instead.
#if defined(OVR_ENABLE_DEVELOPER_SEARCH)
if (!developerDir[0]) // If not already set by LIBOVR_DLL_PATH...
{
// __FILE__ maps to <sdkRoot>/LibOVR/Src/OVR_CAPIShim.c
char sdkRoot[OVR_MAX_PATH];
char* pLibOVR;
size_t i;
// We assume that __FILE__ returns a full path, which isn't the case for some compilers.
// Need to compile with /FC under VC++ for __FILE__ to expand to the full file path.
// clang expands __FILE__ to a full path by default.
OVR_strlcpy(sdkRoot, __FILE__, sizeof(sdkRoot));
for(i = 0; sdkRoot[i]; ++i)
sdkRoot[i] = (char)tolower(sdkRoot[i]); // Microsoft doesn't maintain case.
pLibOVR = strstr(sdkRoot, "libovr");
if(pLibOVR && (pLibOVR > sdkRoot))
pLibOVR[-1] = '\0';
else
sdkRoot[0] = '\0';
if(sdkRoot[0])
{
// We want to use a developer version of the library only if the application is also being executed from
// a developer location. Ideally we would do this by checking that the relative path from the executable to
// the shared library is the same at runtime as it was when the executable was first built, but we don't have
// an easy way to do that from here and it would require some runtime help from the application code.
// Instead we verify that the application is simply in the same developer tree that was was when built.
// We could put in some additional logic to make it very likely to know if the EXE is in its original location.
FilePathCharType modulePath[OVR_MAX_PATH];
const ovrBool pathMatch = OVR_GetCurrentModuleDirectory(modulePath, OVR_MAX_PATH, ovrTrue) &&
(OVR_PathStartsWith(modulePath, sdkRoot) == ovrTrue);
if(pathMatch == ovrFalse)
{
sdkRoot[0] = '\0'; // The application module is not in the developer tree, so don't try to use the developer shared library.
}
}
if(sdkRoot[0])
{
#if defined(OVR_BUILD_DEBUG)
const char* pConfigDirName = "Debug";
#else
const char* pConfigDirName = "Release";
#endif
#if defined(_MSC_VER)
#if defined(_WIN64)
const char* pArchDirName = "x64";
#else
const char* pArchDirName = "Win32";
#endif
#else
#if defined(__x86_64__)
const char* pArchDirName = "x86_64";
#else
const char* pArchDirName = "i386";
#endif
#endif
#if defined(_MSC_VER) && (_MSC_VER == 1600)
const char* pCompilerVersion = "VS2010";
#elif defined(_MSC_VER) && (_MSC_VER == 1700)
const char* pCompilerVersion = "VS2012";
#elif defined(_MSC_VER) && (_MSC_VER == 1800)
const char* pCompilerVersion = "VS2013";
#elif defined(_MSC_VER) && (_MSC_VER == 1900)
const char* pCompilerVersion = "VS2014";
#endif
#if defined(_WIN32)
int count = swprintf_s(developerDir, OVR_MAX_PATH, L"%hs\\LibOVR\\Lib\\Windows\\%hs\\%hs\\%hs\\",
sdkRoot, pArchDirName, pConfigDirName, pCompilerVersion);
#elif defined(__APPLE__)
// Apple/XCode doesn't let you specify an arch in build paths, which is OK if we build a universal binary.
(void)pArchDirName;
int count = snprintf(developerDir, OVR_MAX_PATH, "%s/LibOVR/Lib/Mac/%s/",
sdkRoot, pConfigDirName);
#else
int count = snprintf(developerDir, OVR_MAX_PATH, "%s/LibOVR/Lib/Linux/%s/%s/",
sdkRoot, pArchDirName, pConfigDirName);
#endif
if((count < 0) || (count >= (int)OVR_MAX_PATH)) // If there was an error or capacity overflow... clear the string.
{
developerDir[0] = '\0';
}
}
}
#endif // OVR_ENABLE_DEVELOPER_SEARCH
{
#if !defined(_WIN32)
FilePathCharType cwDir[OVR_MAX_PATH]; // Will be filled in below.
FilePathCharType appDir[OVR_MAX_PATH];
#endif
size_t i;
#if defined(_WIN32)
// On Windows, only search the developer directory and the usual path
const FilePathCharType* directoryArray[2];
directoryArray[0] = developerDir; // Developer directory.
directoryArray[1] = L""; // No directory, which causes Windows to use the standard search strategy to find the DLL.
#elif defined(__APPLE__)
// https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/dyld.1.html
FilePathCharType homeDir[OVR_MAX_PATH];
FilePathCharType homeFrameworkDir[OVR_MAX_PATH];
const FilePathCharType* directoryArray[5];
size_t homeDirLength = 0;
const char* pHome = getenv("HOME"); // Try getting the HOME environment variable.
if (pHome)
{
homeDirLength = OVR_strlcpy(homeDir, pHome, sizeof(homeDir));
}
else
{
// https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/getpwuid_r.3.html
const long pwBufferSize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (pwBufferSize != -1)
{
char pwBuffer[pwBufferSize];
struct passwd pw;
struct passwd* pwResult = NULL;
if ((getpwuid_r(getuid(), &pw, pwBuffer, pwBufferSize, &pwResult) == 0) && pwResult)
homeDirLength = OVR_strlcpy(homeDir, pw.pw_dir, sizeof(homeDir));
}
}
if (homeDirLength)
{
if (homeDir[homeDirLength - 1] == '/')
homeDir[homeDirLength - 1] = '\0';
OVR_strlcpy(homeFrameworkDir, homeDir, sizeof(homeFrameworkDir));
OVR_strlcat(homeFrameworkDir, "/Library/Frameworks/", sizeof(homeFrameworkDir));
}
else
{
homeFrameworkDir[0] = '\0';
}
directoryArray[0] = cwDir;
directoryArray[1] = appDir;
directoryArray[2] = homeFrameworkDir; // ~/Library/Frameworks/
directoryArray[3] = "/Library/Frameworks/"; // DYLD_FALLBACK_FRAMEWORK_PATH
directoryArray[4] = developerDir; // Developer directory.
#else
#define STR1(x) #x
#define STR(x) STR1(x)
#ifdef LIBDIR
#define TEST_LIB_DIR STR(LIBDIR) "/"
#else
#define TEST_LIB_DIR appDir
#endif
const FilePathCharType* directoryArray[5];
directoryArray[0] = cwDir;
directoryArray[1] = TEST_LIB_DIR; // Directory specified by LIBDIR if defined.
directoryArray[2] = developerDir; // Developer directory.
directoryArray[3] = "/usr/local/lib/";
directoryArray[4] = "/usr/lib/";
#endif
#if !defined(_WIN32)
OVR_GetCurrentWorkingDirectory(cwDir, sizeof(cwDir) / sizeof(cwDir[0]));
OVR_GetCurrentApplicationDirectory(appDir, sizeof(appDir) / sizeof(appDir[0]), ovrTrue, NULL);
#endif
// Versioned file expectations.
// Windows: LibOVRRT<BIT_DEPTH>_<PRODUCT_VERSION>_<MAJOR_VERSION>.dll // Example: LibOVRRT64_1_1.dll -- LibOVRRT 64 bit, product 1, major version 1, minor/patch/build numbers unspecified in the name.
// Mac: LibOVRRT_<PRODUCT_VERSION>.framework/Versions/<MAJOR_VERSION>/LibOVRRT_<PRODUCT_VERSION> // We are not presently using the .framework bundle's Current directory to hold the version number. This may change.
// Linux: libOVRRT<BIT_DEPTH>_<PRODUCT_VERSION>.so.<MAJOR_VERSION> // The file on disk may contain a minor version number, but a symlink is used to map this major-only version to it.
// Since we are manually loading the LibOVR dynamic library, we need to look in various locations for a file
// that matches our requirements. The functionality required is somewhat similar to the operating system's
// dynamic loader functionality. Each OS has some differences in how this is handled.
// Future versions of this may iterate over all libOVRRT.so.* files in the directory and use the one that matches our requirements.
//
// We need to look for a library that matches the product version and major version of the caller's request,
// and that library needs to support a minor version that is >= the requested minor version. Currently we
// don't test the minor version here, as the library is named based only on the product and major version.
// Currently the minor version test is handled via the initialization of the library and the initialization
// fails if minor version cannot be supported by the library. The reason this is done during initialization
// is that the library can at runtime support multiple minor versions based on the user's request. To the
// external user, all that matters it that they call ovr_Initialize with a requested version and it succeeds
// or fails.
//
// The product version is something that is at a higher level than the major version, and is not something that's
// always seen in libraries (an example is the well-known LibXml2 library, in which the 2 is essentially the product version).
for(i = 0; i < sizeof(directoryArray)/sizeof(directoryArray[0]); ++i)
{
#if defined(_WIN32)
printfResult = swprintf(libraryPath, libraryPathCapacity, L"%lsLibOVRRT%hs_%d.dll", directoryArray[i], pBitDepth, requestedMajorVersion);
if (*directoryArray[i] == 0)
{
int k;
FilePathCharType foundPath[MAX_PATH] = { 0 };
DWORD searchResult = SearchPathW(NULL, libraryPath, NULL, MAX_PATH, foundPath, NULL);
if (searchResult <= 0 || searchResult >= libraryPathCapacity)
{