Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Linux: Implement prefix-counted BSTR allocation in SysAllocStringLen #3250

Merged
merged 1 commit into from
Nov 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions include/dxc/Support/WinAdapter.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,6 @@
#define CoTaskMemAlloc malloc
#define CoTaskMemFree free

#define SysFreeString free
#define SysAllocStringLen(ptr, size) \
(wchar_t *)realloc(ptr, (size + 1) * sizeof(wchar_t))

#define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0]))

#define _countof(a) (sizeof(a) / sizeof(*(a)))
Expand Down Expand Up @@ -916,6 +912,12 @@ class CHeapPtr : public CHeapPtrBase<T, Allocator> {

#define CComHeapPtr CHeapPtr

//===--------------------------- BSTR Allocation --------------------------===//

void SysFreeString(BSTR bstrString);
// Allocate string with length prefix
BSTR SysAllocStringLen(const OLECHAR *strIn, UINT ui);

//===--------------------- UTF-8 Related Types ----------------------------===//

// Code Page
Expand Down
30 changes: 30 additions & 0 deletions lib/DxcSupport/WinAdapter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,36 @@ void *CAllocator::Reallocate(void *p, size_t nBytes) throw() {
void *CAllocator::Allocate(size_t nBytes) throw() { return malloc(nBytes); }
void CAllocator::Free(void *p) throw() { free(p); }

//===--------------------------- BSTR Allocation --------------------------===//

void SysFreeString(BSTR bstrString) {
if (bstrString)
free((void *)((uintptr_t)bstrString - sizeof(uint32_t)));
}

// Allocate string with length prefix
// https://docs.microsoft.com/en-us/previous-versions/windows/desktop/automat/bstr
BSTR SysAllocStringLen(const OLECHAR *strIn, UINT ui) {
uint32_t *blobOut =
(uint32_t *)malloc(sizeof(uint32_t) + (ui + 1) * sizeof(OLECHAR));

if (!blobOut)
return nullptr;

// Size in bytes without trailing NULL character
blobOut[0] = ui * sizeof(OLECHAR);

BSTR strOut = (BSTR)&blobOut[1];

if (strIn)
memcpy(strOut, strIn, blobOut[0]);

// Write trailing NULL character:
strOut[ui] = 0;

return strOut;
}

//===---------------------- Char converstion ------------------------------===//

const char *CPToLocale(uint32_t CodePage) {
Expand Down