FileIOHelper.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // FileIOHelper.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. // //
  9. ///////////////////////////////////////////////////////////////////////////////
  10. #include "dxc/Support/Global.h"
  11. #include "dxc/Support/WinIncludes.h"
  12. #include "dxc/Support/microcom.h"
  13. #include "dxc/Support/Unicode.h"
  14. #include "dxc/Support/FileIOHelper.h"
  15. #include "dxc/dxcapi.h"
  16. #include <algorithm>
  17. #include <memory>
  18. #include <intsafe.h>
  19. #define CP_UTF16 1200
  20. namespace hlsl {
  21. _Use_decl_annotations_
  22. void ReadBinaryFile(LPCWSTR pFileName, void **ppData, DWORD *pDataSize) {
  23. HANDLE hFile = CreateFileW(pFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  24. if(hFile == INVALID_HANDLE_VALUE) {
  25. IFT(HRESULT_FROM_WIN32(GetLastError()));
  26. }
  27. CHandle h(hFile);
  28. LARGE_INTEGER FileSize;
  29. if(!GetFileSizeEx(hFile, &FileSize)) {
  30. IFT(HRESULT_FROM_WIN32(GetLastError()));
  31. }
  32. if(FileSize.HighPart != 0) {
  33. throw(hlsl::Exception(DXC_E_INPUT_FILE_TOO_LARGE, "input file is too large"));
  34. }
  35. CComHeapPtr<char> pData;
  36. if (!pData.AllocateBytes(FileSize.LowPart)) {
  37. throw std::bad_alloc();
  38. }
  39. DWORD BytesRead;
  40. if(!ReadFile(hFile, pData.m_pData, FileSize.LowPart, &BytesRead, nullptr)) {
  41. IFT(HRESULT_FROM_WIN32(GetLastError()));
  42. }
  43. DXASSERT(FileSize.LowPart == BytesRead, "ReadFile operation failed");
  44. *ppData = pData.Detach();
  45. *pDataSize = FileSize.LowPart;
  46. }
  47. _Use_decl_annotations_
  48. void WriteBinaryFile(LPCWSTR pFileName, const void *pData, DWORD DataSize) {
  49. HANDLE hFile = CreateFileW(pFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
  50. if(hFile == INVALID_HANDLE_VALUE) {
  51. IFT(HRESULT_FROM_WIN32(GetLastError()));
  52. }
  53. CHandle h(hFile);
  54. DWORD BytesWritten;
  55. if(!WriteFile(hFile, pData, DataSize, &BytesWritten, nullptr)) {
  56. IFT(HRESULT_FROM_WIN32(GetLastError()));
  57. }
  58. DXASSERT(DataSize == BytesWritten, "WriteFile operation failed");
  59. }
  60. _Use_decl_annotations_
  61. UINT32 DxcCodePageFromBytes(const char *bytes, size_t byteLen) {
  62. UINT32 codePage;
  63. if (byteLen >= 4) {
  64. // Now try to use the BOM to check for Unicode encodings
  65. char bom[4] = { bytes[0], bytes[1], bytes[2], bytes[3] };
  66. if (strncmp(bom, "\xef\xbb\xbf", 3) == 0) {
  67. codePage = CP_UTF8;
  68. }
  69. else if (strncmp(bom, "\xff\xfe**", 2) == 0) {
  70. codePage = 1200; //UTF-16 LE
  71. }
  72. else if (strncmp(bom, "\xfe\xff**", 2) == 0) {
  73. codePage = 1201; //UTF-16 BE
  74. }
  75. else if (strncmp(bom, "\xff\xfe\x00\x00", 4) == 0) {
  76. codePage = 12000; //UTF-32 LE
  77. }
  78. else if (strncmp(bom, "\x00\x00\xfe\xff", 4) == 0) {
  79. codePage = 12001; //UTF-32 BE
  80. }
  81. else {
  82. codePage = CP_ACP;
  83. }
  84. }
  85. else {
  86. codePage = CP_ACP;
  87. }
  88. return codePage;
  89. }
  90. class InternalDxcBlobEncoding : public IDxcBlobEncoding {
  91. private:
  92. DXC_MICROCOM_REF_FIELD(m_dwRef)
  93. LPCVOID m_Buffer = nullptr;
  94. IUnknown* m_Owner = nullptr; // IMalloc when MallocFree is true
  95. SIZE_T m_BufferSize;
  96. unsigned m_HeapFree : 1;
  97. unsigned m_EncodingKnown : 1;
  98. unsigned m_MallocFree : 1;
  99. UINT32 m_CodePage;
  100. public:
  101. DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef)
  102. InternalDxcBlobEncoding() : m_dwRef(0) {
  103. }
  104. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) {
  105. return DoBasicQueryInterface2<IDxcBlob, IDxcBlobEncoding>(this, iid, ppvObject);
  106. }
  107. ~InternalDxcBlobEncoding() {
  108. if (m_MallocFree) {
  109. ((IMalloc *)m_Owner)->Free((void *)m_Buffer);
  110. }
  111. if (m_Owner != nullptr) {
  112. m_Owner->Release();
  113. }
  114. if (m_HeapFree) {
  115. CoTaskMemFree((LPVOID)m_Buffer);
  116. }
  117. }
  118. static HRESULT
  119. CreateFromHeap(LPCVOID buffer, SIZE_T bufferSize, bool encodingKnown,
  120. UINT32 codePage,
  121. _COM_Outptr_ InternalDxcBlobEncoding **pEncoding) {
  122. *pEncoding = new (std::nothrow) InternalDxcBlobEncoding();
  123. if (*pEncoding == nullptr) {
  124. return E_OUTOFMEMORY;
  125. }
  126. (*pEncoding)->m_Buffer = buffer;
  127. (*pEncoding)->m_BufferSize = bufferSize;
  128. (*pEncoding)->m_HeapFree = 1;
  129. (*pEncoding)->m_EncodingKnown = encodingKnown;
  130. (*pEncoding)->m_MallocFree = 0;
  131. (*pEncoding)->m_CodePage = codePage;
  132. (*pEncoding)->AddRef();
  133. return S_OK;
  134. }
  135. static HRESULT
  136. CreateFromBlob(_In_ IDxcBlob *pBlob, bool encodingKnown, UINT32 codePage,
  137. _COM_Outptr_ InternalDxcBlobEncoding **pEncoding) {
  138. *pEncoding = new (std::nothrow) InternalDxcBlobEncoding();
  139. if (*pEncoding == nullptr) {
  140. return E_OUTOFMEMORY;
  141. }
  142. pBlob->AddRef();
  143. (*pEncoding)->m_Owner = pBlob;
  144. (*pEncoding)->m_Buffer = pBlob->GetBufferPointer();
  145. (*pEncoding)->m_BufferSize = pBlob->GetBufferSize();
  146. (*pEncoding)->m_HeapFree = 0;
  147. (*pEncoding)->m_EncodingKnown = encodingKnown;
  148. (*pEncoding)->m_MallocFree = 0;
  149. (*pEncoding)->m_CodePage = codePage;
  150. (*pEncoding)->AddRef();
  151. return S_OK;
  152. }
  153. static HRESULT
  154. CreateFromMalloc(LPCVOID buffer, IMalloc *pIMalloc, SIZE_T bufferSize, bool encodingKnown,
  155. UINT32 codePage, _COM_Outptr_ InternalDxcBlobEncoding **pEncoding) {
  156. *pEncoding = new (std::nothrow) InternalDxcBlobEncoding();
  157. if (*pEncoding == nullptr) {
  158. return E_OUTOFMEMORY;
  159. }
  160. pIMalloc->AddRef();
  161. (*pEncoding)->m_Owner = pIMalloc;
  162. (*pEncoding)->m_Buffer = buffer;
  163. (*pEncoding)->m_BufferSize = bufferSize;
  164. (*pEncoding)->m_HeapFree = 0;
  165. (*pEncoding)->m_EncodingKnown = encodingKnown;
  166. (*pEncoding)->m_MallocFree = 1;
  167. (*pEncoding)->m_CodePage = codePage;
  168. (*pEncoding)->AddRef();
  169. return S_OK;
  170. }
  171. void AdjustPtrAndSize(unsigned offset, unsigned size) {
  172. DXASSERT(offset < m_BufferSize, "else caller will overflow");
  173. DXASSERT(offset + size <= m_BufferSize, "else caller will overflow");
  174. m_Buffer = (const uint8_t*)m_Buffer + offset;
  175. m_BufferSize = size;
  176. }
  177. virtual LPVOID STDMETHODCALLTYPE GetBufferPointer(void) override {
  178. return (LPVOID)m_Buffer;
  179. }
  180. virtual SIZE_T STDMETHODCALLTYPE GetBufferSize(void) override {
  181. return m_BufferSize;
  182. }
  183. virtual HRESULT STDMETHODCALLTYPE GetEncoding(_Out_ BOOL *pKnown, _Out_ UINT32 *pCodePage) {
  184. *pKnown = m_EncodingKnown ? TRUE : FALSE;
  185. *pCodePage = m_CodePage;
  186. return S_OK;
  187. }
  188. // Relatively dangerous API. This means the buffer should be pinned for as
  189. // long as this object is alive.
  190. void ClearFreeFlag() { m_HeapFree = 0; }
  191. };
  192. static HRESULT CodePageBufferToUtf16(UINT32 codePage, LPCVOID bufferPointer,
  193. SIZE_T bufferSize,
  194. CComHeapPtr<WCHAR> &utf16NewCopy,
  195. _Out_ UINT32 *pConvertedCharCount) {
  196. *pConvertedCharCount = 0;
  197. // If the buffer is empty, don't dereference bufferPointer at all.
  198. // Keep the null terminator post-condition.
  199. if (bufferSize == 0) {
  200. if (!utf16NewCopy.Allocate(1))
  201. return E_OUTOFMEMORY;
  202. utf16NewCopy.m_pData[0] = L'\0';
  203. DXASSERT(*pConvertedCharCount == 0, "else didn't init properly");
  204. return S_OK;
  205. }
  206. // Calculate the length of the buffer in wchar_t elements.
  207. int numToConvertUTF16 =
  208. MultiByteToWideChar(codePage, MB_ERR_INVALID_CHARS, (char *)bufferPointer,
  209. bufferSize, nullptr, 0);
  210. if (numToConvertUTF16 == 0)
  211. return HRESULT_FROM_WIN32(GetLastError());
  212. // Add an extra character to make this more developer-friendly.
  213. unsigned buffSizeUTF16;
  214. IFR(Int32ToUInt32(numToConvertUTF16, &buffSizeUTF16));
  215. IFR(UInt32Add(buffSizeUTF16, 1, &buffSizeUTF16));
  216. IFR(UInt32Mult(buffSizeUTF16, sizeof(WCHAR), &buffSizeUTF16));
  217. utf16NewCopy.AllocateBytes(buffSizeUTF16);
  218. IFROOM(utf16NewCopy.m_pData);
  219. int numActuallyConvertedUTF16 =
  220. MultiByteToWideChar(codePage, MB_ERR_INVALID_CHARS, (char *)bufferPointer,
  221. bufferSize, utf16NewCopy, buffSizeUTF16);
  222. if (numActuallyConvertedUTF16 == 0)
  223. return HRESULT_FROM_WIN32(GetLastError());
  224. ((LPWSTR)utf16NewCopy)[numActuallyConvertedUTF16] = L'\0';
  225. *pConvertedCharCount = numActuallyConvertedUTF16;
  226. return S_OK;
  227. }
  228. _Use_decl_annotations_
  229. HRESULT DxcCreateBlobFromBlob(
  230. IDxcBlob *pBlob, UINT32 offset, UINT32 length, IDxcBlob **ppResult) {
  231. if (pBlob == nullptr || ppResult == nullptr) {
  232. return E_POINTER;
  233. }
  234. *ppResult = nullptr;
  235. SIZE_T blobSize = pBlob->GetBufferSize();
  236. if (offset > blobSize)
  237. return E_INVALIDARG;
  238. UINT32 end;
  239. IFR(UInt32Add(offset, length, &end));
  240. BOOL encodingKnown = FALSE;
  241. UINT32 codePage = CP_ACP;
  242. CComPtr<IDxcBlobEncoding> pBlobEncoding;
  243. if (SUCCEEDED(pBlob->QueryInterface(&pBlobEncoding))) {
  244. IFR(pBlobEncoding->GetEncoding(&encodingKnown, &codePage));
  245. }
  246. CComPtr<InternalDxcBlobEncoding> pCreated;
  247. IFR(InternalDxcBlobEncoding::CreateFromBlob(pBlob, encodingKnown, codePage,
  248. &pCreated));
  249. pCreated->AdjustPtrAndSize(offset, length);
  250. *ppResult = pCreated.Detach();
  251. return S_OK;
  252. }
  253. _Use_decl_annotations_
  254. HRESULT
  255. DxcCreateBlobOnHeap(LPCVOID pData, UINT32 size, IDxcBlob **ppResult) {
  256. if (pData == nullptr || ppResult == nullptr) {
  257. return E_POINTER;
  258. }
  259. *ppResult = nullptr;
  260. CComPtr<InternalDxcBlobEncoding> blob;
  261. IFR(InternalDxcBlobEncoding::CreateFromHeap(pData, size, false, 0, &blob));
  262. *ppResult = blob.Detach();
  263. return S_OK;
  264. }
  265. _Use_decl_annotations_
  266. HRESULT
  267. DxcCreateBlobOnHeapCopy(_In_bytecount_(size) LPCVOID pData, UINT32 size,
  268. _COM_Outptr_ IDxcBlob **ppResult) {
  269. if (pData == nullptr || ppResult == nullptr) {
  270. return E_POINTER;
  271. }
  272. *ppResult = nullptr;
  273. CComHeapPtr<char> heapCopy;
  274. if (!heapCopy.AllocateBytes(size)) {
  275. return E_OUTOFMEMORY;
  276. }
  277. memcpy(heapCopy.m_pData, pData, size);
  278. CComPtr<InternalDxcBlobEncoding> blob;
  279. IFR(InternalDxcBlobEncoding::CreateFromHeap(heapCopy.m_pData, size, false, 0, &blob));
  280. heapCopy.Detach();
  281. *ppResult = blob.Detach();
  282. return S_OK;
  283. }
  284. _Use_decl_annotations_
  285. HRESULT DxcCreateBlobFromFile(LPCWSTR pFileName, UINT32 *pCodePage,
  286. IDxcBlobEncoding **ppBlobEncoding) {
  287. if (pFileName == nullptr || ppBlobEncoding == nullptr) {
  288. return E_POINTER;
  289. }
  290. CComHeapPtr<char> pData;
  291. DWORD dataSize;
  292. *ppBlobEncoding = nullptr;
  293. try {
  294. ReadBinaryFile(pFileName, (void **)(&pData), &dataSize);
  295. }
  296. CATCH_CPP_RETURN_HRESULT();
  297. bool known = (pCodePage != nullptr);
  298. UINT32 codePage = (pCodePage != nullptr) ? *pCodePage : 0;
  299. InternalDxcBlobEncoding *internalEncoding;
  300. HRESULT hr = InternalDxcBlobEncoding::CreateFromHeap(
  301. pData, dataSize, known, codePage, &internalEncoding);
  302. if (SUCCEEDED(hr)) {
  303. *ppBlobEncoding = internalEncoding;
  304. pData.Detach();
  305. }
  306. return hr;
  307. }
  308. _Use_decl_annotations_
  309. HRESULT
  310. DxcCreateBlobWithEncodingSet(IDxcBlob *pBlob, UINT32 codePage,
  311. IDxcBlobEncoding **pBlobEncoding) {
  312. *pBlobEncoding = nullptr;
  313. InternalDxcBlobEncoding *internalEncoding;
  314. HRESULT hr = InternalDxcBlobEncoding::CreateFromBlob(pBlob, true, codePage,
  315. &internalEncoding);
  316. if (SUCCEEDED(hr)) {
  317. *pBlobEncoding = internalEncoding;
  318. }
  319. return hr;
  320. }
  321. _Use_decl_annotations_
  322. HRESULT DxcCreateBlobWithEncodingFromPinned(LPCVOID pText, UINT32 size,
  323. UINT32 codePage,
  324. IDxcBlobEncoding **pBlobEncoding) {
  325. *pBlobEncoding = nullptr;
  326. InternalDxcBlobEncoding *internalEncoding;
  327. HRESULT hr = InternalDxcBlobEncoding::CreateFromHeap(
  328. pText, size, true, codePage, &internalEncoding);
  329. if (SUCCEEDED(hr)) {
  330. internalEncoding->ClearFreeFlag();
  331. *pBlobEncoding = internalEncoding;
  332. }
  333. return hr;
  334. }
  335. _Use_decl_annotations_
  336. HRESULT
  337. DxcCreateBlobWithEncodingFromStream(IStream *pStream, bool newInstanceAlways,
  338. UINT32 codePage,
  339. IDxcBlobEncoding **ppBlobEncoding) {
  340. *ppBlobEncoding = nullptr;
  341. if (pStream == nullptr) {
  342. return S_OK;
  343. }
  344. // Try to reuse the existing stream.
  345. if (!newInstanceAlways) {
  346. CComPtr<IDxcBlobEncoding> blobEncoding;
  347. if (SUCCEEDED(pStream->QueryInterface(&blobEncoding))) {
  348. *ppBlobEncoding = blobEncoding.Detach();
  349. return S_OK;
  350. }
  351. }
  352. // Layer over the blob if possible.
  353. CComPtr<IDxcBlob> blob;
  354. if (SUCCEEDED(pStream->QueryInterface(&blob))) {
  355. return DxcCreateBlobWithEncodingSet(blob, codePage, ppBlobEncoding);
  356. }
  357. // Create a copy of contents, last resort.
  358. // TODO: implement when we find this codepath internally
  359. return E_NOTIMPL;
  360. }
  361. _Use_decl_annotations_
  362. HRESULT
  363. DxcCreateBlobWithEncodingOnHeap(LPCVOID pText, UINT32 size, UINT32 codePage,
  364. IDxcBlobEncoding **pBlobEncoding) {
  365. *pBlobEncoding = nullptr;
  366. InternalDxcBlobEncoding *internalEncoding;
  367. HRESULT hr = InternalDxcBlobEncoding::CreateFromHeap(
  368. pText, size, true, codePage, &internalEncoding);
  369. if (SUCCEEDED(hr)) {
  370. *pBlobEncoding = internalEncoding;
  371. }
  372. return hr;
  373. }
  374. _Use_decl_annotations_
  375. HRESULT
  376. DxcCreateBlobWithEncodingOnHeapCopy(LPCVOID pText, UINT32 size, UINT32 codePage,
  377. IDxcBlobEncoding **pBlobEncoding) {
  378. *pBlobEncoding = nullptr;
  379. CComHeapPtr<char> heapCopy;
  380. if (!heapCopy.AllocateBytes(size)) {
  381. return E_OUTOFMEMORY;
  382. }
  383. memcpy(heapCopy.m_pData, pText, size);
  384. InternalDxcBlobEncoding* internalEncoding;
  385. HRESULT hr = InternalDxcBlobEncoding::CreateFromHeap(heapCopy.m_pData, size, true, codePage, &internalEncoding);
  386. if (SUCCEEDED(hr)) {
  387. *pBlobEncoding = internalEncoding;
  388. heapCopy.Detach();
  389. }
  390. return hr;
  391. }
  392. _Use_decl_annotations_
  393. HRESULT
  394. DxcCreateBlobWithEncodingOnMalloc(LPCVOID pText, IMalloc *pIMalloc, UINT32 size, UINT32 codePage,
  395. IDxcBlobEncoding **pBlobEncoding) {
  396. *pBlobEncoding = nullptr;
  397. InternalDxcBlobEncoding* internalEncoding;
  398. HRESULT hr = InternalDxcBlobEncoding::CreateFromMalloc(pText, pIMalloc, size, true, codePage, &internalEncoding);
  399. if (SUCCEEDED(hr)) {
  400. *pBlobEncoding = internalEncoding;
  401. }
  402. return hr;
  403. }
  404. _Use_decl_annotations_
  405. HRESULT DxcGetBlobAsUtf8(IDxcBlob *pBlob, IDxcBlobEncoding **pBlobEncoding) {
  406. *pBlobEncoding = nullptr;
  407. HRESULT hr;
  408. CComPtr<IDxcBlobEncoding> pSourceBlob;
  409. UINT32 codePage = CP_ACP;
  410. BOOL known = FALSE;
  411. if (SUCCEEDED(pBlob->QueryInterface(&pSourceBlob))) {
  412. hr = pSourceBlob->GetEncoding(&known, &codePage);
  413. if (FAILED(hr)) {
  414. return hr;
  415. }
  416. // If it's known to be CP_UTF8, there is nothing else to be done.
  417. if (known && codePage == CP_UTF8) {
  418. *pBlobEncoding = pSourceBlob.Detach();
  419. return S_OK;
  420. }
  421. }
  422. else {
  423. known = FALSE;
  424. }
  425. SIZE_T blobLen = pBlob->GetBufferSize();
  426. if (!known && blobLen > 0) {
  427. codePage = DxcCodePageFromBytes((char *)pBlob->GetBufferPointer(), blobLen);
  428. }
  429. if (codePage == CP_UTF8) {
  430. // Reuse the underlying blob but create an object with the encoding known.
  431. InternalDxcBlobEncoding* internalEncoding;
  432. hr = InternalDxcBlobEncoding::CreateFromBlob(pBlob, true, CP_UTF8, &internalEncoding);
  433. if (SUCCEEDED(hr)) {
  434. *pBlobEncoding = internalEncoding;
  435. }
  436. return hr;
  437. }
  438. // Convert and create a blob that owns the encoding.
  439. // Any UTF-16 output must be converted to UTF-16 first, then
  440. // back to the target code page.
  441. CComHeapPtr<WCHAR> utf16NewCopy;
  442. wchar_t* utf16Chars = nullptr;
  443. UINT32 utf16CharCount;
  444. if (codePage == CP_UTF16) {
  445. utf16Chars = (wchar_t*)pBlob->GetBufferPointer();
  446. utf16CharCount = blobLen / sizeof(wchar_t);
  447. }
  448. else {
  449. hr = CodePageBufferToUtf16(codePage, pBlob->GetBufferPointer(), blobLen,
  450. utf16NewCopy, &utf16CharCount);
  451. if (FAILED(hr)) {
  452. return hr;
  453. }
  454. utf16Chars = utf16NewCopy;
  455. }
  456. const UINT32 targetCodePage = CP_UTF8;
  457. CComHeapPtr<char> finalNewCopy;
  458. int numToConvertFinal = WideCharToMultiByte(
  459. targetCodePage, 0, utf16Chars, utf16CharCount,
  460. finalNewCopy, 0, NULL, NULL);
  461. if (numToConvertFinal == 0)
  462. return HRESULT_FROM_WIN32(GetLastError());
  463. unsigned buffSizeFinal;
  464. IFR(Int32ToUInt32(numToConvertFinal, &buffSizeFinal));
  465. IFR(UInt32Add(buffSizeFinal, 1, &buffSizeFinal));
  466. finalNewCopy.AllocateBytes(buffSizeFinal);
  467. IFROOM(finalNewCopy.m_pData);
  468. int numActuallyConvertedFinal = WideCharToMultiByte(
  469. targetCodePage, 0, utf16Chars, utf16CharCount,
  470. finalNewCopy, buffSizeFinal, NULL, NULL);
  471. if (numActuallyConvertedFinal == 0)
  472. return HRESULT_FROM_WIN32(GetLastError());
  473. ((LPSTR)finalNewCopy)[numActuallyConvertedFinal] = '\0';
  474. InternalDxcBlobEncoding* internalEncoding;
  475. hr = InternalDxcBlobEncoding::CreateFromHeap(finalNewCopy.m_pData,
  476. numActuallyConvertedFinal, true, targetCodePage, &internalEncoding);
  477. if (SUCCEEDED(hr)) {
  478. *pBlobEncoding = internalEncoding;
  479. finalNewCopy.Detach();
  480. }
  481. return hr;
  482. }
  483. HRESULT
  484. DxcGetBlobAsUtf8NullTerm(_In_ IDxcBlob *pBlob,
  485. _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) {
  486. *ppBlobEncoding = nullptr;
  487. HRESULT hr;
  488. CComPtr<IDxcBlobEncoding> pSourceBlob;
  489. unsigned blobSize = pBlob->GetBufferSize();
  490. // Check whether we already have a null-terminated UTF-8 blob.
  491. if (SUCCEEDED(pBlob->QueryInterface(&pSourceBlob))) {
  492. UINT32 codePage = CP_ACP;
  493. BOOL known = FALSE;
  494. hr = pSourceBlob->GetEncoding(&known, &codePage);
  495. if (FAILED(hr)) {
  496. return hr;
  497. }
  498. if (known && codePage == CP_UTF8) {
  499. char *pChars = (char *)pBlob->GetBufferPointer();
  500. if (blobSize > 0) {
  501. if (pChars[blobSize - 1] == '\0') {
  502. *ppBlobEncoding = pSourceBlob.Detach();
  503. return S_OK;
  504. }
  505. }
  506. // We have a non-null-terminated UTF-8 stream. Copy to a new location.
  507. CComHeapPtr<char> pCopy;
  508. if (!pCopy.Allocate(blobSize + 1))
  509. return E_OUTOFMEMORY;
  510. memcpy(pCopy.m_pData, pChars, blobSize);
  511. pCopy.m_pData[blobSize] = '\0';
  512. IFR(DxcCreateBlobWithEncodingOnHeap(pCopy.m_pData, blobSize + 1, CP_UTF8,
  513. ppBlobEncoding));
  514. pCopy.Detach();
  515. return S_OK;
  516. }
  517. }
  518. // Perform the conversion, which typically adds a new null terminator,
  519. // but run this again just in case.
  520. CComPtr<IDxcBlobEncoding> pConverted;
  521. IFR(DxcGetBlobAsUtf8(pBlob, &pConverted));
  522. return DxcGetBlobAsUtf8NullTerm(pConverted, ppBlobEncoding);
  523. }
  524. _Use_decl_annotations_
  525. HRESULT DxcGetBlobAsUtf16(IDxcBlob *pBlob, IDxcBlobEncoding **pBlobEncoding) {
  526. *pBlobEncoding = nullptr;
  527. HRESULT hr;
  528. CComPtr<IDxcBlobEncoding> pSourceBlob;
  529. UINT32 codePage = CP_ACP;
  530. BOOL known = FALSE;
  531. if (SUCCEEDED(pBlob->QueryInterface(&pSourceBlob))) {
  532. hr = pSourceBlob->GetEncoding(&known, &codePage);
  533. if (FAILED(hr)) {
  534. return hr;
  535. }
  536. // If it's known to be CP_UTF8, there is nothing else to be done.
  537. if (known && codePage == CP_UTF16) {
  538. *pBlobEncoding = pSourceBlob.Detach();
  539. return S_OK;
  540. }
  541. }
  542. else {
  543. known = FALSE;
  544. }
  545. SIZE_T blobLen = pBlob->GetBufferSize();
  546. if (!known) {
  547. codePage = DxcCodePageFromBytes((char *)pBlob->GetBufferPointer(), blobLen);
  548. }
  549. // Reuse the underlying blob but create an object with the encoding known.
  550. if (codePage == CP_UTF16) {
  551. InternalDxcBlobEncoding* internalEncoding;
  552. hr = InternalDxcBlobEncoding::CreateFromBlob(pBlob, true, CP_UTF16, &internalEncoding);
  553. if (SUCCEEDED(hr)) {
  554. *pBlobEncoding = internalEncoding;
  555. }
  556. return hr;
  557. }
  558. // Convert and create a blob that owns the encoding.
  559. CComHeapPtr<WCHAR> utf16NewCopy;
  560. UINT32 utf16CharCount;
  561. hr = CodePageBufferToUtf16(codePage, pBlob->GetBufferPointer(), blobLen,
  562. utf16NewCopy, &utf16CharCount);
  563. if (FAILED(hr)) {
  564. return hr;
  565. }
  566. InternalDxcBlobEncoding* internalEncoding;
  567. hr = InternalDxcBlobEncoding::CreateFromHeap(utf16NewCopy.m_pData,
  568. utf16CharCount * sizeof(WCHAR), true, CP_UTF16, &internalEncoding);
  569. if (SUCCEEDED(hr)) {
  570. *pBlobEncoding = internalEncoding;
  571. utf16NewCopy.Detach();
  572. }
  573. return hr;
  574. }
  575. bool IsBlobNullOrEmpty(_In_opt_ IDxcBlob *pBlob) throw() {
  576. return pBlob == nullptr || pBlob->GetBufferSize() == 0;
  577. }
  578. ///////////////////////////////////////////////////////////////////////////////
  579. // Stream implementations.
  580. class MemoryStream : public AbstractMemoryStream, public IDxcBlob {
  581. private:
  582. DXC_MICROCOM_REF_FIELD(m_dwRef)
  583. CComPtr<IMalloc> m_pMalloc;
  584. LPBYTE m_pMemory;
  585. ULONG m_offset;
  586. ULONG m_size;
  587. ULONG m_allocSize;
  588. public:
  589. DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef)
  590. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) {
  591. return DoBasicQueryInterface3<IStream, ISequentialStream, IDxcBlob>(this, iid, ppvObject);
  592. }
  593. MemoryStream(_In_ IMalloc *pMalloc)
  594. : m_dwRef(0), m_pMalloc(pMalloc), m_pMemory(nullptr), m_offset(0),
  595. m_size(0), m_allocSize(0) {}
  596. ~MemoryStream() {
  597. Reset();
  598. }
  599. HRESULT Grow(ULONG targetSize) {
  600. if (targetSize < m_allocSize * 2) {
  601. targetSize = m_allocSize * 2;
  602. }
  603. return Reserve(targetSize);
  604. }
  605. void Reset() {
  606. if (m_pMemory != nullptr) {
  607. m_pMalloc->Free(m_pMemory);
  608. }
  609. m_pMemory = nullptr;
  610. m_offset = 0;
  611. m_size = 0;
  612. m_allocSize = 0;
  613. }
  614. // AbstractMemoryStream implementation.
  615. __override LPBYTE GetPtr() {
  616. return m_pMemory;
  617. }
  618. __override ULONG GetPtrSize() {
  619. return m_size;
  620. }
  621. __override LPBYTE Detach() {
  622. LPBYTE result = m_pMemory;
  623. m_pMemory = nullptr;
  624. Reset();
  625. return result;
  626. }
  627. __override HRESULT Reserve(ULONG targetSize) {
  628. if (m_pMemory == nullptr) {
  629. m_pMemory = (LPBYTE)m_pMalloc->Alloc(targetSize);
  630. if (m_pMemory == nullptr) {
  631. return E_OUTOFMEMORY;
  632. }
  633. }
  634. else {
  635. void* newPtr = m_pMalloc->Realloc(m_pMemory, targetSize);
  636. if (newPtr == nullptr) {
  637. return E_OUTOFMEMORY;
  638. }
  639. m_pMemory = (LPBYTE)newPtr;
  640. }
  641. m_allocSize = targetSize;
  642. return S_OK;
  643. }
  644. // IDxcBlob implementation. Requires no further writes.
  645. __override LPVOID STDMETHODCALLTYPE GetBufferPointer(void) {
  646. return m_pMemory;
  647. }
  648. __override SIZE_T STDMETHODCALLTYPE GetBufferSize(void) {
  649. return m_size;
  650. }
  651. __override UINT64 GetPosition() {
  652. return m_offset;
  653. }
  654. // ISequentialStream implementation.
  655. __override HRESULT STDMETHODCALLTYPE Read(void* pv, ULONG cb, ULONG* pcbRead) {
  656. if (!pv || !pcbRead) return E_POINTER;
  657. // If we seeked past the end, read nothing.
  658. if (m_offset > m_size) {
  659. *pcbRead = 0;
  660. return S_FALSE;
  661. }
  662. ULONG cbLeft = m_size - m_offset;
  663. *pcbRead = std::min(cb, cbLeft);
  664. memcpy(pv, m_pMemory + m_offset, *pcbRead);
  665. m_offset += *pcbRead;
  666. return (*pcbRead == cb) ? S_OK : S_FALSE;
  667. }
  668. __override HRESULT STDMETHODCALLTYPE Write(void const* pv, ULONG cb, ULONG* pcbWritten) {
  669. if (!pv || !pcbWritten) return E_POINTER;
  670. if (cb + m_offset > m_allocSize) {
  671. HRESULT hr = Grow(cb + m_offset);
  672. if (FAILED(hr)) return hr;
  673. // Implicitly extend as needed with zeroes.
  674. if (m_offset > m_size) {
  675. memset(m_pMemory + m_size, 0, m_offset - m_size);
  676. }
  677. }
  678. *pcbWritten = cb;
  679. memcpy(m_pMemory + m_offset, pv, cb);
  680. m_offset += cb;
  681. m_size = std::max(m_size, m_offset);
  682. return S_OK;
  683. }
  684. // IStream implementation.
  685. __override HRESULT STDMETHODCALLTYPE SetSize(ULARGE_INTEGER val) {
  686. if (val.HighPart != 0) {
  687. return E_OUTOFMEMORY;
  688. }
  689. if (val.LowPart > m_allocSize) {
  690. return Grow(m_allocSize);
  691. }
  692. if (val.LowPart < m_size) {
  693. m_size = val.LowPart;
  694. m_offset = std::min(m_offset, m_size);
  695. }
  696. else if (val.LowPart > m_size) {
  697. memset(m_pMemory + m_size, 0, val.LowPart - m_size);
  698. m_size = val.LowPart;
  699. }
  700. return S_OK;
  701. }
  702. __override HRESULT STDMETHODCALLTYPE CopyTo(IStream *, ULARGE_INTEGER,
  703. ULARGE_INTEGER *,
  704. ULARGE_INTEGER *) {
  705. return E_NOTIMPL;
  706. }
  707. __override HRESULT STDMETHODCALLTYPE Commit(DWORD) { return E_NOTIMPL; }
  708. __override HRESULT STDMETHODCALLTYPE Revert(void) { return E_NOTIMPL; }
  709. __override HRESULT STDMETHODCALLTYPE LockRegion(ULARGE_INTEGER,
  710. ULARGE_INTEGER, DWORD) {
  711. return E_NOTIMPL;
  712. }
  713. __override HRESULT STDMETHODCALLTYPE UnlockRegion(ULARGE_INTEGER,
  714. ULARGE_INTEGER, DWORD) {
  715. return E_NOTIMPL;
  716. }
  717. __override HRESULT STDMETHODCALLTYPE Clone(IStream **) { return E_NOTIMPL; }
  718. __override HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER liDistanceToMove,
  719. DWORD dwOrigin,
  720. ULARGE_INTEGER *lpNewFilePointer) {
  721. if (lpNewFilePointer != nullptr) {
  722. lpNewFilePointer->QuadPart = 0;
  723. }
  724. if (liDistanceToMove.HighPart != 0) {
  725. return E_FAIL;
  726. }
  727. ULONG targetOffset;
  728. switch (dwOrigin) {
  729. case STREAM_SEEK_SET:
  730. targetOffset = liDistanceToMove.LowPart;
  731. break;
  732. case STREAM_SEEK_CUR:
  733. targetOffset = liDistanceToMove.LowPart + m_offset;
  734. break;
  735. case STREAM_SEEK_END:
  736. targetOffset = liDistanceToMove.LowPart + m_size;
  737. break;
  738. default:
  739. return STG_E_INVALIDFUNCTION;
  740. }
  741. m_offset = targetOffset;
  742. if (lpNewFilePointer != nullptr) {
  743. lpNewFilePointer->LowPart = targetOffset;
  744. }
  745. return S_OK;
  746. }
  747. __override HRESULT STDMETHODCALLTYPE Stat(STATSTG *pStatstg,
  748. DWORD grfStatFlag) {
  749. if (pStatstg == nullptr) {
  750. return E_POINTER;
  751. }
  752. ZeroMemory(pStatstg, sizeof(*pStatstg));
  753. pStatstg->type = STGTY_STREAM;
  754. pStatstg->cbSize.LowPart = m_size;
  755. return S_OK;
  756. }
  757. };
  758. class ReadOnlyBlobStream : public IStream {
  759. private:
  760. DXC_MICROCOM_REF_FIELD(m_dwRef)
  761. CComPtr<IDxcBlob> m_pSource;
  762. LPBYTE m_pMemory;
  763. ULONG m_offset;
  764. ULONG m_size;
  765. public:
  766. DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef)
  767. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) {
  768. return DoBasicQueryInterface2<IStream, ISequentialStream>(this, iid, ppvObject);
  769. }
  770. ReadOnlyBlobStream(IDxcBlob *pSource) : m_pSource(pSource), m_offset(0), m_dwRef(0) {
  771. m_size = m_pSource->GetBufferSize();
  772. m_pMemory = (LPBYTE)m_pSource->GetBufferPointer();
  773. }
  774. // ISequentialStream implementation.
  775. __override HRESULT STDMETHODCALLTYPE Read(void *pv, ULONG cb,
  776. ULONG *pcbRead) {
  777. if (!pv || !pcbRead)
  778. return E_POINTER;
  779. ULONG cbLeft = m_size - m_offset;
  780. *pcbRead = std::min(cb, cbLeft);
  781. memcpy(pv, m_pMemory + m_offset, *pcbRead);
  782. m_offset += *pcbRead;
  783. return (*pcbRead == cb) ? S_OK : S_FALSE;
  784. }
  785. __override HRESULT STDMETHODCALLTYPE Write(void const *, ULONG, ULONG *) {
  786. return STG_E_ACCESSDENIED;
  787. }
  788. // IStream implementation.
  789. __override HRESULT STDMETHODCALLTYPE SetSize(ULARGE_INTEGER val) {
  790. return STG_E_ACCESSDENIED;
  791. }
  792. __override HRESULT STDMETHODCALLTYPE CopyTo(IStream *, ULARGE_INTEGER,
  793. ULARGE_INTEGER *,
  794. ULARGE_INTEGER *) {
  795. return E_NOTIMPL;
  796. }
  797. __override HRESULT STDMETHODCALLTYPE Commit(DWORD) { return E_NOTIMPL; }
  798. __override HRESULT STDMETHODCALLTYPE Revert(void) { return E_NOTIMPL; }
  799. __override HRESULT STDMETHODCALLTYPE LockRegion(ULARGE_INTEGER,
  800. ULARGE_INTEGER, DWORD) {
  801. return E_NOTIMPL;
  802. }
  803. __override HRESULT STDMETHODCALLTYPE UnlockRegion(ULARGE_INTEGER,
  804. ULARGE_INTEGER, DWORD) {
  805. return E_NOTIMPL;
  806. }
  807. __override HRESULT STDMETHODCALLTYPE Clone(IStream **) { return E_NOTIMPL; }
  808. __override HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER liDistanceToMove,
  809. DWORD dwOrigin,
  810. ULARGE_INTEGER *lpNewFilePointer) {
  811. if (lpNewFilePointer != nullptr) {
  812. lpNewFilePointer->QuadPart = 0;
  813. }
  814. if (liDistanceToMove.HighPart != 0) {
  815. return E_FAIL;
  816. }
  817. ULONG targetOffset;
  818. switch (dwOrigin) {
  819. case STREAM_SEEK_SET:
  820. targetOffset = liDistanceToMove.LowPart;
  821. break;
  822. case STREAM_SEEK_CUR:
  823. targetOffset = liDistanceToMove.LowPart + m_offset;
  824. break;
  825. case STREAM_SEEK_END:
  826. targetOffset = liDistanceToMove.LowPart + m_size;
  827. break;
  828. default:
  829. return STG_E_INVALIDFUNCTION;
  830. }
  831. // Do not implicility extend.
  832. if (targetOffset > m_size) {
  833. return E_FAIL;
  834. }
  835. m_offset = targetOffset;
  836. if (lpNewFilePointer != nullptr) {
  837. lpNewFilePointer->LowPart = targetOffset;
  838. }
  839. return S_OK;
  840. }
  841. __override HRESULT STDMETHODCALLTYPE Stat(STATSTG *pStatstg,
  842. DWORD grfStatFlag) {
  843. if (pStatstg == nullptr) {
  844. return E_POINTER;
  845. }
  846. ZeroMemory(pStatstg, sizeof(*pStatstg));
  847. pStatstg->type = STGTY_STREAM;
  848. pStatstg->cbSize.LowPart = m_size;
  849. return S_OK;
  850. }
  851. };
  852. HRESULT CreateMemoryStream(_In_ IMalloc *pMalloc, _COM_Outptr_ AbstractMemoryStream** ppResult) {
  853. if (pMalloc == nullptr || ppResult == nullptr) {
  854. return E_POINTER;
  855. }
  856. CComPtr<MemoryStream> stream = new (std::nothrow) MemoryStream(pMalloc);
  857. *ppResult = stream.Detach();
  858. return (*ppResult == nullptr) ? E_OUTOFMEMORY : S_OK;
  859. }
  860. HRESULT CreateReadOnlyBlobStream(_In_ IDxcBlob *pSource, _COM_Outptr_ IStream** ppResult) {
  861. if (pSource == nullptr || ppResult == nullptr) {
  862. return E_POINTER;
  863. }
  864. CComPtr<ReadOnlyBlobStream> stream = new (std::nothrow) ReadOnlyBlobStream(pSource);
  865. *ppResult = stream.Detach();
  866. return (*ppResult == nullptr) ? E_OUTOFMEMORY : S_OK;
  867. }
  868. } // namespace hlsl