1// Copyright 2014 PDFium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6
7#include "../../include/fxcrt/fx_ext.h"
8#include "extension.h"
9#if _FXM_PLATFORM_ == _FXM_PLATFORM_WINDOWS_
10#include <wincrypt.h>
11#else
12#include <ctime>
13#endif
14FX_HFILE FX_File_Open(FX_BSTR fileName, FX_DWORD dwMode, IFX_Allocator* pAllocator)
15{
16    IFXCRT_FileAccess* pFA = FXCRT_FileAccess_Create(pAllocator);
17    if (pFA && !pFA->Open(fileName, dwMode)) {
18        pFA->Release(pAllocator);
19        return NULL;
20    }
21    return (FX_HFILE)pFA;
22}
23FX_HFILE FX_File_Open(FX_WSTR fileName, FX_DWORD dwMode, IFX_Allocator* pAllocator)
24{
25    IFXCRT_FileAccess* pFA = FXCRT_FileAccess_Create(pAllocator);
26    if (pFA && !pFA->Open(fileName, dwMode)) {
27        pFA->Release(pAllocator);
28        return NULL;
29    }
30    return (FX_HFILE)pFA;
31}
32void FX_File_Close(FX_HFILE hFile, IFX_Allocator* pAllocator)
33{
34    FXSYS_assert(hFile != NULL);
35    ((IFXCRT_FileAccess*)hFile)->Close();
36    ((IFXCRT_FileAccess*)hFile)->Release(pAllocator);
37}
38FX_FILESIZE FX_File_GetSize(FX_HFILE hFile)
39{
40    FXSYS_assert(hFile != NULL);
41    return ((IFXCRT_FileAccess*)hFile)->GetSize();
42}
43FX_FILESIZE FX_File_GetPosition(FX_HFILE hFile)
44{
45    FXSYS_assert(hFile != NULL);
46    return ((IFXCRT_FileAccess*)hFile)->GetPosition();
47}
48FX_FILESIZE FX_File_SetPosition(FX_HFILE hFile, FX_FILESIZE pos)
49{
50    FXSYS_assert(hFile != NULL);
51    return ((IFXCRT_FileAccess*)hFile)->SetPosition(pos);
52}
53size_t FX_File_Read(FX_HFILE hFile, void* pBuffer, size_t szBuffer)
54{
55    FXSYS_assert(hFile != NULL);
56    return ((IFXCRT_FileAccess*)hFile)->Read(pBuffer, szBuffer);
57}
58size_t FX_File_ReadPos(FX_HFILE hFile, void* pBuffer, size_t szBuffer, FX_FILESIZE pos)
59{
60    FXSYS_assert(hFile != NULL);
61    return ((IFXCRT_FileAccess*)hFile)->ReadPos(pBuffer, szBuffer, pos);
62}
63size_t FX_File_Write(FX_HFILE hFile, const void* pBuffer, size_t szBuffer)
64{
65    FXSYS_assert(hFile != NULL);
66    return ((IFXCRT_FileAccess*)hFile)->Write(pBuffer, szBuffer);
67}
68size_t FX_File_WritePos(FX_HFILE hFile, const void* pBuffer, size_t szBuffer, FX_FILESIZE pos)
69{
70    FXSYS_assert(hFile != NULL);
71    return ((IFXCRT_FileAccess*)hFile)->WritePos(pBuffer, szBuffer, pos);
72}
73FX_BOOL FX_File_Flush(FX_HFILE hFile)
74{
75    FXSYS_assert(hFile != NULL);
76    return ((IFXCRT_FileAccess*)hFile)->Flush();
77}
78FX_BOOL FX_File_Truncate(FX_HFILE hFile, FX_FILESIZE szFile)
79{
80    FXSYS_assert(hFile != NULL);
81    return ((IFXCRT_FileAccess*)hFile)->Truncate(szFile);
82}
83IFX_FileStream* FX_CreateFileStream(FX_LPCSTR filename, FX_DWORD dwModes, IFX_Allocator* pAllocator)
84{
85    IFXCRT_FileAccess* pFA = FXCRT_FileAccess_Create(pAllocator);
86    if (!pFA) {
87        return NULL;
88    }
89    if (!pFA->Open(filename, dwModes)) {
90        pFA->Release(pAllocator);
91        return NULL;
92    }
93    if (pAllocator) {
94        return FX_NewAtAllocator(pAllocator) CFX_CRTFileStream(pFA, pAllocator);
95    } else {
96        return FX_NEW CFX_CRTFileStream(pFA, pAllocator);
97    }
98}
99IFX_FileStream* FX_CreateFileStream(FX_LPCWSTR filename, FX_DWORD dwModes, IFX_Allocator* pAllocator)
100{
101    IFXCRT_FileAccess* pFA = FXCRT_FileAccess_Create(pAllocator);
102    if (!pFA) {
103        return NULL;
104    }
105    if (!pFA->Open(filename, dwModes)) {
106        pFA->Release(pAllocator);
107        return NULL;
108    }
109    if (pAllocator) {
110        return FX_NewAtAllocator(pAllocator) CFX_CRTFileStream(pFA, pAllocator);
111    } else {
112        return FX_NEW CFX_CRTFileStream(pFA, pAllocator);
113    }
114}
115IFX_FileWrite* FX_CreateFileWrite(FX_LPCSTR filename, IFX_Allocator* pAllocator)
116{
117    return FX_CreateFileStream(filename, FX_FILEMODE_Truncate, pAllocator);
118}
119IFX_FileWrite* FX_CreateFileWrite(FX_LPCWSTR filename, IFX_Allocator* pAllocator)
120{
121    return FX_CreateFileStream(filename, FX_FILEMODE_Truncate, pAllocator);
122}
123IFX_FileRead* FX_CreateFileRead(FX_LPCSTR filename, IFX_Allocator* pAllocator)
124{
125    return FX_CreateFileStream(filename, FX_FILEMODE_ReadOnly, pAllocator);
126}
127IFX_FileRead* FX_CreateFileRead(FX_LPCWSTR filename, IFX_Allocator* pAllocator)
128{
129    return FX_CreateFileStream(filename, FX_FILEMODE_ReadOnly, pAllocator);
130}
131IFX_MemoryStream* FX_CreateMemoryStream(FX_LPBYTE pBuffer, size_t dwSize, FX_BOOL bTakeOver, IFX_Allocator* pAllocator)
132{
133    if (pAllocator) {
134        return FX_NewAtAllocator(pAllocator)CFX_MemoryStream(pBuffer, dwSize, bTakeOver, pAllocator);
135    } else {
136        return FX_NEW CFX_MemoryStream(pBuffer, dwSize, bTakeOver, NULL);
137    }
138}
139IFX_MemoryStream* FX_CreateMemoryStream(FX_BOOL bConsecutive, IFX_Allocator* pAllocator)
140{
141    if (pAllocator) {
142        return FX_NewAtAllocator(pAllocator)CFX_MemoryStream(bConsecutive, pAllocator);
143    } else {
144        return FX_NEW CFX_MemoryStream(bConsecutive, NULL);
145    }
146}
147#ifdef __cplusplus
148extern "C" {
149#endif
150FX_FLOAT FXSYS_tan(FX_FLOAT a)
151{
152    return (FX_FLOAT)tan(a);
153}
154FX_FLOAT FXSYS_logb(FX_FLOAT b, FX_FLOAT x)
155{
156    return FXSYS_log(x) / FXSYS_log(b);
157}
158FX_FLOAT FXSYS_strtof(FX_LPCSTR pcsStr, FX_INT32 iLength, FX_INT32 *pUsedLen)
159{
160    FXSYS_assert(pcsStr != NULL);
161    if (iLength < 0) {
162        iLength = (FX_INT32)FXSYS_strlen(pcsStr);
163    }
164    CFX_WideString ws = CFX_WideString::FromLocal(pcsStr, iLength);
165    return FXSYS_wcstof((FX_LPCWSTR)ws, iLength, pUsedLen);
166}
167FX_FLOAT FXSYS_wcstof(FX_LPCWSTR pwsStr, FX_INT32 iLength, FX_INT32 *pUsedLen)
168{
169    FXSYS_assert(pwsStr != NULL);
170    if (iLength < 0) {
171        iLength = (FX_INT32)FXSYS_wcslen(pwsStr);
172    }
173    if (iLength == 0) {
174        return 0.0f;
175    }
176    FX_INT32 iUsedLen = 0;
177    FX_BOOL bNegtive = FALSE;
178    switch (pwsStr[iUsedLen]) {
179        case '-':
180            bNegtive = TRUE;
181        case '+':
182            iUsedLen++;
183            break;
184    }
185    FX_FLOAT fValue = 0.0f;
186    while (iUsedLen < iLength) {
187        FX_WCHAR wch = pwsStr[iUsedLen];
188        if (wch >= L'0' && wch <= L'9') {
189            fValue = fValue * 10.0f + (wch - L'0');
190        } else {
191            break;
192        }
193        iUsedLen++;
194    }
195    if (iUsedLen < iLength && pwsStr[iUsedLen] == L'.') {
196        FX_FLOAT fPrecise = 0.1f;
197        while (++iUsedLen < iLength) {
198            FX_WCHAR wch = pwsStr[iUsedLen];
199            if (wch >= L'0' && wch <= L'9') {
200                fValue += (wch - L'0') * fPrecise;
201                fPrecise *= 0.1f;
202            } else {
203                break;
204            }
205        }
206    }
207    if (pUsedLen) {
208        *pUsedLen = iUsedLen;
209    }
210    return bNegtive ? -fValue : fValue;
211}
212FX_LPWSTR FXSYS_wcsncpy(FX_LPWSTR dstStr, FX_LPCWSTR srcStr, size_t count)
213{
214    FXSYS_assert(dstStr != NULL && srcStr != NULL && count > 0);
215    for (size_t i = 0; i < count; ++i)
216        if ((dstStr[i] = srcStr[i]) == L'\0') {
217            break;
218        }
219    return dstStr;
220}
221FX_INT32 FXSYS_wcsnicmp(FX_LPCWSTR s1, FX_LPCWSTR s2, size_t count)
222{
223    FXSYS_assert(s1 != NULL && s2 != NULL && count > 0);
224    FX_WCHAR wch1 = 0, wch2 = 0;
225    while (count-- > 0) {
226        wch1 = (FX_WCHAR)FXSYS_tolower(*s1++);
227        wch2 = (FX_WCHAR)FXSYS_tolower(*s2++);
228        if (wch1 != wch2) {
229            break;
230        }
231    }
232    return wch1 - wch2;
233}
234FX_INT32 FXSYS_strnicmp(FX_LPCSTR s1, FX_LPCSTR s2, size_t count)
235{
236    FXSYS_assert(s1 != NULL && s2 != NULL && count > 0);
237    FX_CHAR ch1 = 0, ch2 = 0;
238    while (count-- > 0) {
239        ch1 = (FX_CHAR)FXSYS_tolower(*s1++);
240        ch2 = (FX_CHAR)FXSYS_tolower(*s2++);
241        if (ch1 != ch2) {
242            break;
243        }
244    }
245    return ch1 - ch2;
246}
247FX_DWORD FX_HashCode_String_GetA(FX_LPCSTR pStr, FX_INT32 iLength, FX_BOOL bIgnoreCase)
248{
249    FXSYS_assert(pStr != NULL);
250    if (iLength < 0) {
251        iLength = (FX_INT32)FXSYS_strlen(pStr);
252    }
253    FX_LPCSTR pStrEnd = pStr + iLength;
254    FX_DWORD dwHashCode = 0;
255    if (bIgnoreCase) {
256        while (pStr < pStrEnd) {
257            dwHashCode = 31 * dwHashCode + FXSYS_tolower(*pStr++);
258        }
259    } else {
260        while (pStr < pStrEnd) {
261            dwHashCode = 31 * dwHashCode + *pStr ++;
262        }
263    }
264    return dwHashCode;
265}
266FX_DWORD FX_HashCode_String_GetW(FX_LPCWSTR pStr, FX_INT32 iLength, FX_BOOL bIgnoreCase)
267{
268    FXSYS_assert(pStr != NULL);
269    if (iLength < 0) {
270        iLength = (FX_INT32)FXSYS_wcslen(pStr);
271    }
272    FX_LPCWSTR pStrEnd = pStr + iLength;
273    FX_DWORD dwHashCode = 0;
274    if (bIgnoreCase) {
275        while (pStr < pStrEnd) {
276            dwHashCode = 1313 * dwHashCode + FXSYS_tolower(*pStr++);
277        }
278    } else {
279        while (pStr < pStrEnd) {
280            dwHashCode = 1313 * dwHashCode + *pStr ++;
281        }
282    }
283    return dwHashCode;
284}
285#ifdef __cplusplus
286}
287#endif
288#ifdef __cplusplus
289extern "C" {
290#endif
291FX_LPVOID FX_Random_MT_Start(FX_DWORD dwSeed)
292{
293    FX_LPMTRANDOMCONTEXT pContext = FX_Alloc(FX_MTRANDOMCONTEXT, 1);
294    if (!pContext) {
295        return NULL;
296    }
297    pContext->mt[0] = dwSeed;
298    FX_DWORD &i = pContext->mti;
299    FX_LPDWORD pBuf = pContext->mt;
300    for (i = 1; i < MT_N; i ++) {
301        pBuf[i] = (1812433253UL * (pBuf[i - 1] ^ (pBuf[i - 1] >> 30)) + i);
302    }
303    pContext->bHaveSeed = TRUE;
304    return pContext;
305}
306FX_DWORD FX_Random_MT_Generate(FX_LPVOID pContext)
307{
308    FXSYS_assert(pContext != NULL);
309    FX_LPMTRANDOMCONTEXT pMTC = (FX_LPMTRANDOMCONTEXT)pContext;
310    FX_DWORD v;
311    static FX_DWORD mag[2] = {0, MT_Matrix_A};
312    FX_DWORD &mti = pMTC->mti;
313    FX_LPDWORD pBuf = pMTC->mt;
314    if ((int)mti < 0 || mti >= MT_N) {
315        if (mti > MT_N && !pMTC->bHaveSeed) {
316            return 0;
317        }
318        FX_DWORD kk;
319        for (kk = 0; kk < MT_N - MT_M; kk ++) {
320            v = (pBuf[kk] & MT_Upper_Mask) | (pBuf[kk + 1] & MT_Lower_Mask);
321            pBuf[kk] = pBuf[kk + MT_M] ^ (v >> 1) ^ mag[v & 1];
322        }
323        for (; kk < MT_N - 1; kk ++) {
324            v = (pBuf[kk] & MT_Upper_Mask) | (pBuf[kk + 1] & MT_Lower_Mask);
325            pBuf[kk] = pBuf[kk + (MT_M - MT_N)] ^ (v >> 1) ^ mag[v & 1];
326        }
327        v = (pBuf[MT_N - 1] & MT_Upper_Mask) | (pBuf[0] & MT_Lower_Mask);
328        pBuf[MT_N - 1] = pBuf[MT_M - 1] ^ (v >> 1) ^ mag[v & 1];
329        mti = 0;
330    }
331    v = pBuf[mti ++];
332    v ^= (v >> 11);
333    v ^= (v << 7) & 0x9d2c5680UL;
334    v ^= (v << 15) & 0xefc60000UL;
335    v ^= (v >> 18);
336    return v;
337}
338void FX_Random_MT_Close(FX_LPVOID pContext)
339{
340    FXSYS_assert(pContext != NULL);
341    FX_Free(pContext);
342}
343void FX_Random_GenerateMT(FX_LPDWORD pBuffer, FX_INT32 iCount)
344{
345    FX_DWORD dwSeed;
346#if _FXM_PLATFORM_ == _FXM_PLATFORM_WINDOWS_
347    if (!FX_GenerateCryptoRandom(&dwSeed, 1)) {
348        FX_Random_GenerateBase(&dwSeed, 1);
349    }
350#else
351    FX_Random_GenerateBase(&dwSeed, 1);
352#endif
353    FX_LPVOID pContext = FX_Random_MT_Start(dwSeed);
354    while (iCount -- > 0) {
355        *pBuffer ++ = FX_Random_MT_Generate(pContext);
356    }
357    FX_Random_MT_Close(pContext);
358}
359void FX_Random_GenerateBase(FX_LPDWORD pBuffer, FX_INT32 iCount)
360{
361#if _FXM_PLATFORM_ == _FXM_PLATFORM_WINDOWS_
362    SYSTEMTIME st1, st2;
363    ::GetSystemTime(&st1);
364    do {
365        ::GetSystemTime(&st2);
366    } while (FXSYS_memcmp32(&st1, &st2, sizeof(SYSTEMTIME)) == 0);
367    FX_DWORD dwHash1 = FX_HashCode_String_GetA((FX_LPCSTR)&st1, sizeof(st1), TRUE);
368    FX_DWORD dwHash2 = FX_HashCode_String_GetA((FX_LPCSTR)&st2, sizeof(st2), TRUE);
369    ::srand((dwHash1 << 16) | (FX_DWORD)dwHash2);
370#else
371    time_t tmLast = time(NULL), tmCur;
372    while ((tmCur = time(NULL)) == tmLast);
373    ::srand((tmCur << 16) | (tmLast & 0xFFFF));
374#endif
375    while (iCount -- > 0) {
376        *pBuffer ++ = (FX_DWORD)((::rand() << 16) | (::rand() & 0xFFFF));
377    }
378}
379#if _FXM_PLATFORM_ == _FXM_PLATFORM_WINDOWS_
380FX_BOOL FX_GenerateCryptoRandom(FX_LPDWORD pBuffer, FX_INT32 iCount)
381{
382    HCRYPTPROV hCP = NULL;
383    if (!::CryptAcquireContext(&hCP, NULL, NULL, PROV_RSA_FULL, 0) || hCP == NULL) {
384        return FALSE;
385    }
386    ::CryptGenRandom(hCP, iCount * sizeof(FX_DWORD), (FX_LPBYTE)pBuffer);
387    ::CryptReleaseContext(hCP, 0);
388    return TRUE;
389}
390#endif
391void FX_Random_GenerateCrypto(FX_LPDWORD pBuffer, FX_INT32 iCount)
392{
393#if _FXM_PLATFORM_ == _FXM_PLATFORM_WINDOWS_
394    FX_GenerateCryptoRandom(pBuffer, iCount);
395#else
396    FX_Random_GenerateBase(pBuffer, iCount);
397#endif
398}
399#ifdef __cplusplus
400}
401#endif
402