本文整理汇总了C++中LocalFree函数的典型用法代码示例。如果您正苦于以下问题:C++ LocalFree函数的具体用法?C++ LocalFree怎么用?C++ LocalFree使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了LocalFree函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: EDT_UtilReg_LogPermissions
int EDT_UtilReg_LogPermissions(HKEY hRootKey, const wchar_t *wzKey)
{
int iReturnCode = EDT_OK;
int err = ERROR_SUCCESS;
HKEY hRegKey;
LOG_ENTER();
LOG_TIME(L"registry key (%ls\\%ls) --> \n",hRootKey==HKEY_CURRENT_USER?L"HKCU":L"HKLM",wzKey);
if(ERROR_SUCCESS != (err = RegOpenKeyEx(hRootKey, wzKey, 0L, KEY_READ , &hRegKey)))
{
if(err != ERROR_FILE_NOT_FOUND)
{
LOG_ERRORCODE(L"RegOpenKeyEx failed",err);
return EDT_ERR_REGISTRY_READ_FAILED;
}
else
{
LOG_EXIT(L"NOT FOUND\n");
return EDT_ERR_REGISTRY_NOT_FOUND;
}
}
PSECURITY_DESCRIPTOR pSecurityDescriptor = NULL;
DWORD lcbSecurityDescriptor = 0;
if(ERROR_INSUFFICIENT_BUFFER == (err = RegGetKeySecurity(hRegKey, DACL_SECURITY_INFORMATION, pSecurityDescriptor, &lcbSecurityDescriptor)))
{
pSecurityDescriptor = (PSECURITY_DESCRIPTOR)malloc(lcbSecurityDescriptor);
if(ERROR_SUCCESS != (err = RegGetKeySecurity(hRegKey, DACL_SECURITY_INFORMATION, pSecurityDescriptor, &lcbSecurityDescriptor)))
{
LOG_ERRORCODE(L"RegQueryValueEx failed",err);
iReturnCode = EDT_ERR_REGISTRY_READ_FAILED;
}
else
{
BOOL bDaclPresent = FALSE;
BOOL bDaclDefaulted = FALSE;
PACL pDacl = NULL;
GetSecurityDescriptorDacl(pSecurityDescriptor, &bDaclPresent, &pDacl, &bDaclDefaulted);
if(bDaclPresent == TRUE)
{
if(pDacl == NULL)
{
LOG(L"A NULL discretionary access control list (DACL) found \nA NULL DACL implicitly allows all access to an object.\n");
}
else
{
LOG(L"A discretionary access control list (DACL) was found with Length = %d\n",pDacl->AclSize);
LOG(L"Number of Access Control Elements (ACE's): %d\n",pDacl->AceCount);
registryLogAces(pDacl);
}
}
else
{
LOG(L"No discretionary access control list (DACL) found \n");
}
LPTSTR StringSecurityDescriptor;
ULONG StringSecurityDescriptorLen;
ConvertSecurityDescriptorToStringSecurityDescriptor(pSecurityDescriptor,SDDL_REVISION_1,DACL_SECURITY_INFORMATION,
&StringSecurityDescriptor,&StringSecurityDescriptorLen);
LOG(L"%s\n",(const wchar_t*)StringSecurityDescriptor);
//parse info see http://msdn.microsoft.com/en-us/library/aa379570%28v=vs.85%29.aspx
LocalFree(StringSecurityDescriptor);
}
free(pSecurityDescriptor);
}
else
{
LOG_ERRORCODE(L"RegGetKeySecurity failed",err);
}
if(ERROR_SUCCESS != (err = RegCloseKey(hRegKey)))
{
LOG_ERRORCODE(L"RegCloseKey failed",err);
}
LOG_EXIT(iReturnCode);
return iReturnCode;
}
示例2: kuhl_m_kerberos_list
NTSTATUS kuhl_m_kerberos_list(int argc, wchar_t * argv[])
{
NTSTATUS status, packageStatus;
KERB_QUERY_TKT_CACHE_REQUEST kerbCacheRequest = {KerbQueryTicketCacheExMessage, {0, 0}};
PKERB_QUERY_TKT_CACHE_EX_RESPONSE pKerbCacheResponse;
PKERB_RETRIEVE_TKT_REQUEST pKerbRetrieveRequest;
PKERB_RETRIEVE_TKT_RESPONSE pKerbRetrieveResponse;
DWORD szData, i;
wchar_t * filename;
BOOL export = kull_m_string_args_byName(argc, argv, L"export", NULL, NULL);
status = LsaCallKerberosPackage(&kerbCacheRequest, sizeof(KERB_QUERY_TKT_CACHE_REQUEST), (PVOID *) &pKerbCacheResponse, &szData, &packageStatus);
if(NT_SUCCESS(status))
{
if(NT_SUCCESS(packageStatus))
{
for(i = 0; i < pKerbCacheResponse->CountOfTickets; i++)
{
kprintf(L"\n[%08x] - 0x%08x - %s", i, pKerbCacheResponse->Tickets[i].EncryptionType, kuhl_m_kerberos_ticket_etype(pKerbCacheResponse->Tickets[i].EncryptionType));
kprintf(L"\n Start/End/MaxRenew: ");
kull_m_string_displayLocalFileTime((PFILETIME) &pKerbCacheResponse->Tickets[i].StartTime); kprintf(L" ; ");
kull_m_string_displayLocalFileTime((PFILETIME) &pKerbCacheResponse->Tickets[i].EndTime); kprintf(L" ; ");
kull_m_string_displayLocalFileTime((PFILETIME) &pKerbCacheResponse->Tickets[i].RenewTime);
kprintf(L"\n Server Name : %wZ @ %wZ", &pKerbCacheResponse->Tickets[i].ServerName, &pKerbCacheResponse->Tickets[i].ServerRealm);
kprintf(L"\n Client Name : %wZ @ %wZ", &pKerbCacheResponse->Tickets[i].ClientName, &pKerbCacheResponse->Tickets[i].ClientRealm);
kprintf(L"\n Flags %08x : ", pKerbCacheResponse->Tickets[i].TicketFlags);
kuhl_m_kerberos_ticket_displayFlags(pKerbCacheResponse->Tickets[i].TicketFlags);
if(export)
{
szData = sizeof(KERB_RETRIEVE_TKT_REQUEST) + pKerbCacheResponse->Tickets[i].ServerName.MaximumLength;
if(pKerbRetrieveRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LPTR, szData)) // LPTR implicates KERB_ETYPE_NULL
{
pKerbRetrieveRequest->MessageType = KerbRetrieveEncodedTicketMessage;
pKerbRetrieveRequest->CacheOptions = /*KERB_RETRIEVE_TICKET_USE_CACHE_ONLY | */KERB_RETRIEVE_TICKET_AS_KERB_CRED;
pKerbRetrieveRequest->TicketFlags = pKerbCacheResponse->Tickets[i].TicketFlags;
pKerbRetrieveRequest->TargetName = pKerbCacheResponse->Tickets[i].ServerName;
pKerbRetrieveRequest->TargetName.Buffer = (PWSTR) ((PBYTE) pKerbRetrieveRequest + sizeof(KERB_RETRIEVE_TKT_REQUEST));
RtlCopyMemory(pKerbRetrieveRequest->TargetName.Buffer, pKerbCacheResponse->Tickets[i].ServerName.Buffer, pKerbRetrieveRequest->TargetName.MaximumLength);
status = LsaCallKerberosPackage(pKerbRetrieveRequest, szData, (PVOID *) &pKerbRetrieveResponse, &szData, &packageStatus);
if(NT_SUCCESS(status))
{
if(NT_SUCCESS(packageStatus))
{
if(filename = kuhl_m_kerberos_generateFileName(i, &pKerbCacheResponse->Tickets[i], MIMIKATZ_KERBEROS_EXT))
{
if(kull_m_file_writeData(filename, pKerbRetrieveResponse->Ticket.EncodedTicket, pKerbRetrieveResponse->Ticket.EncodedTicketSize))
kprintf(L"\n * Saved to file : %s", filename);
else PRINT_ERROR_AUTO(L"kull_m_file_writeData");
LocalFree(filename);
}
LsaFreeReturnBuffer(pKerbRetrieveResponse);
}
else PRINT_ERROR(L"LsaCallAuthenticationPackage KerbRetrieveEncodedTicketMessage / Package : %08x\n", packageStatus);
}
else PRINT_ERROR(L"LsaCallAuthenticationPackage KerbRetrieveEncodedTicketMessage : %08x\n", status);
LocalFree(pKerbRetrieveRequest);
}
}
kprintf(L"\n");
}
LsaFreeReturnBuffer(pKerbCacheResponse);
}
else PRINT_ERROR(L"LsaCallAuthenticationPackage KerbQueryTicketCacheEx2Message / Package : %08x\n", packageStatus);
}
示例3: kill
int LLProcessLauncher::launch(void)
{
// If there was already a process associated with this object, kill it.
kill();
orphan();
int result = 0;
PROCESS_INFORMATION pinfo;
STARTUPINFOA sinfo;
memset(&sinfo, 0, sizeof(sinfo));
std::string args = mExecutable;
for(int i = 0; i < (int)mLaunchArguments.size(); i++)
{
args += " ";
args += mLaunchArguments[i];
}
// So retarded. Windows requires that the second parameter to CreateProcessA be a writable (non-const) string...
char *args2 = new char[args.size() + 1];
strcpy(args2, args.c_str());
const char * working_directory = 0;
if(!mWorkingDir.empty()) working_directory = mWorkingDir.c_str();
if( ! CreateProcessA( NULL, args2, NULL, NULL, FALSE, 0, NULL, working_directory, &sinfo, &pinfo ) )
{
result = GetLastError();
LPTSTR error_str = 0;
if(
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
result,
0,
(LPTSTR)&error_str,
0,
NULL)
!= 0)
{
char message[256];
wcstombs(message, error_str, 256);
message[255] = 0;
llwarns << "CreateProcessA failed: " << message << llendl;
LocalFree(error_str);
}
if(result == 0)
{
// Make absolutely certain we return a non-zero value on failure.
result = -1;
}
}
else
{
// foo = pinfo.dwProcessId; // get your pid here if you want to use it later on
// CloseHandle(pinfo.hProcess); // stops leaks - nothing else
mProcessHandle = pinfo.hProcess;
CloseHandle(pinfo.hThread); // stops leaks - nothing else
}
delete[] args2;
return result;
}
示例4: make_private_security_descriptor
int make_private_security_descriptor(DWORD permissions,
PSECURITY_DESCRIPTOR *psd,
PACL *acl,
char **error)
{
SID_IDENTIFIER_AUTHORITY world_auth = SECURITY_WORLD_SID_AUTHORITY;
SID_IDENTIFIER_AUTHORITY nt_auth = SECURITY_NT_AUTHORITY;
EXPLICIT_ACCESS ea[3];
int acl_err;
int ret = FALSE;
/* Initialised once, then kept around to reuse forever */
static PSID worldsid, networksid, usersid;
*psd = NULL;
*acl = NULL;
*error = NULL;
if (!got_advapi()) {
*error = dupprintf("unable to load advapi32.dll");
goto cleanup;
}
if (!usersid) {
if ((usersid = get_user_sid()) == NULL) {
*error = dupprintf("unable to construct SID for current user: %s",
win_strerror(GetLastError()));
goto cleanup;
}
}
if (!worldsid) {
if (!AllocateAndInitializeSid(&world_auth, 1, SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0, &worldsid)) {
*error = dupprintf("unable to construct SID for world: %s",
win_strerror(GetLastError()));
goto cleanup;
}
}
if (!networksid) {
if (!AllocateAndInitializeSid(&nt_auth, 1, SECURITY_NETWORK_RID,
0, 0, 0, 0, 0, 0, 0, &networksid)) {
*error = dupprintf("unable to construct SID for "
"local same-user access only: %s",
win_strerror(GetLastError()));
goto cleanup;
}
}
memset(ea, 0, sizeof(ea));
ea[0].grfAccessPermissions = permissions;
ea[0].grfAccessMode = REVOKE_ACCESS;
ea[0].grfInheritance = NO_INHERITANCE;
ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea[0].Trustee.ptstrName = (LPTSTR)worldsid;
ea[1].grfAccessPermissions = permissions;
ea[1].grfAccessMode = GRANT_ACCESS;
ea[1].grfInheritance = NO_INHERITANCE;
ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea[1].Trustee.ptstrName = (LPTSTR)usersid;
ea[2].grfAccessPermissions = permissions;
ea[2].grfAccessMode = REVOKE_ACCESS;
ea[2].grfInheritance = NO_INHERITANCE;
ea[2].Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea[2].Trustee.ptstrName = (LPTSTR)networksid;
acl_err = p_SetEntriesInAclA(3, ea, NULL, acl);
if (acl_err != ERROR_SUCCESS || *acl == NULL) {
*error = dupprintf("unable to construct ACL: %s",
win_strerror(acl_err));
goto cleanup;
}
*psd = (PSECURITY_DESCRIPTOR)
LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
if (!*psd) {
*error = dupprintf("unable to allocate security descriptor: %s",
win_strerror(GetLastError()));
goto cleanup;
}
if (!InitializeSecurityDescriptor(*psd, SECURITY_DESCRIPTOR_REVISION)) {
*error = dupprintf("unable to initialise security descriptor: %s",
win_strerror(GetLastError()));
goto cleanup;
}
if (!SetSecurityDescriptorDacl(*psd, TRUE, *acl, FALSE)) {
*error = dupprintf("unable to set DACL in security descriptor: %s",
win_strerror(GetLastError()));
goto cleanup;
}
ret = TRUE;
cleanup:
if (!ret) {
if (*psd) {
LocalFree(*psd);
//.........这里部分代码省略.........
示例5: SetException
void SetException(DWORD code, EXCEPTION_RECORD *pr)
{
TCHAR *lpMsgBuf;
lpMsgBuf = FormatError(code);
if(lpMsgBuf) {
PyErr_SetFromWindowsErr(code);
LocalFree(lpMsgBuf);
} else {
switch (code) {
case EXCEPTION_ACCESS_VIOLATION:
/* The thread attempted to read from or write
to a virtual address for which it does not
have the appropriate access. */
if (pr->ExceptionInformation[0] == 0)
PyErr_Format(PyExc_WindowsError,
"exception: access violation reading %p",
pr->ExceptionInformation[1]);
else
PyErr_Format(PyExc_WindowsError,
"exception: access violation writing %p",
pr->ExceptionInformation[1]);
break;
case EXCEPTION_BREAKPOINT:
/* A breakpoint was encountered. */
PyErr_SetString(PyExc_WindowsError,
"exception: breakpoint encountered");
break;
case EXCEPTION_DATATYPE_MISALIGNMENT:
/* The thread attempted to read or write data that is
misaligned on hardware that does not provide
alignment. For example, 16-bit values must be
aligned on 2-byte boundaries, 32-bit values on
4-byte boundaries, and so on. */
PyErr_SetString(PyExc_WindowsError,
"exception: datatype misalignment");
break;
case EXCEPTION_SINGLE_STEP:
/* A trace trap or other single-instruction mechanism
signaled that one instruction has been executed. */
PyErr_SetString(PyExc_WindowsError,
"exception: single step");
break;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
/* The thread attempted to access an array element
that is out of bounds, and the underlying hardware
supports bounds checking. */
PyErr_SetString(PyExc_WindowsError,
"exception: array bounds exceeded");
break;
case EXCEPTION_FLT_DENORMAL_OPERAND:
/* One of the operands in a floating-point operation
is denormal. A denormal value is one that is too
small to represent as a standard floating-point
value. */
PyErr_SetString(PyExc_WindowsError,
"exception: floating-point operand denormal");
break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
/* The thread attempted to divide a floating-point
value by a floating-point divisor of zero. */
PyErr_SetString(PyExc_WindowsError,
"exception: float divide by zero");
break;
case EXCEPTION_FLT_INEXACT_RESULT:
/* The result of a floating-point operation cannot be
represented exactly as a decimal fraction. */
PyErr_SetString(PyExc_WindowsError,
"exception: float inexact");
break;
case EXCEPTION_FLT_INVALID_OPERATION:
/* This exception represents any floating-point
exception not included in this list. */
PyErr_SetString(PyExc_WindowsError,
"exception: float invalid operation");
break;
case EXCEPTION_FLT_OVERFLOW:
/* The exponent of a floating-point operation is
greater than the magnitude allowed by the
corresponding type. */
PyErr_SetString(PyExc_WindowsError,
"exception: float overflow");
break;
case EXCEPTION_FLT_STACK_CHECK:
/* The stack overflowed or underflowed as the result
of a floating-point operation. */
PyErr_SetString(PyExc_WindowsError,
"exception: stack over/underflow");
break;
case EXCEPTION_STACK_OVERFLOW:
/* The stack overflowed or underflowed as the result
//.........这里部分代码省略.........
示例6: OpenPortalHandleFromGUID
BOOL OpenPortalHandleFromGUID(GUID guid, PHANDLE phPortalHandle)
{
int memberIndex = 0;
BOOL bResult = TRUE;
HDEVINFO hDevInfo;
SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
PSP_DEVICE_INTERFACE_DETAIL_DATA pInterfaceDetailData = NULL;
HIDD_ATTRIBUTES attributes;
ULONG requiredLength=0;
hDevInfo = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
deviceInterfaceData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA);
*phPortalHandle = NULL;
for(memberIndex = 0;
SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &guid, memberIndex, &deviceInterfaceData);
memberIndex++)
{
SetupDiGetDeviceInterfaceDetail(hDevInfo, &deviceInterfaceData, NULL, 0, &requiredLength, NULL);
//we got the size, allocate buffer
pInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, requiredLength);
assert(pInterfaceDetailData);
//get the interface detailed data
pInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, &deviceInterfaceData, pInterfaceDetailData, requiredLength, &requiredLength, NULL))
{
continue;
}
*phPortalHandle = CreateFile (
pInterfaceDetailData->DevicePath,
GENERIC_EXECUTE | GENERIC_ALL,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
LocalFree(pInterfaceDetailData);
pInterfaceDetailData = NULL;
if(guid == xbox_guid) {
break; // we are done. xbox_guid does not have HID attributes
}
if (*phPortalHandle != INVALID_HANDLE_VALUE)
{
if (HidD_GetAttributes(*phPortalHandle , &attributes))
{
if (((attributes.VendorID == 0x12ba) || (attributes.VendorID == 0x54c)) || (attributes.VendorID == 0x1430))
{
if ((attributes.ProductID == 0x150) || (attributes.ProductID == 0x967))
{
break; // found the portal. leave the handle open
}
}
}
CloseHandle(*phPortalHandle);
*phPortalHandle = NULL;
}
}
SetupDiDestroyDeviceInfoList(hDevInfo);
return (*phPortalHandle != NULL);
}
示例7: InitRunDlg
void InitRunDlg(HWND hDlg, LPRUNDLG_DATA lprd)
{
HWND hCB;
int i;
#ifdef WINNT
HANDLE hThread = NULL;
DWORD dwDummy;
#endif
if (lprd->lpszTitle)
SetWindowText(hDlg, lprd->lpszTitle);
if (lprd->lpszPrompt)
{
SetDlgItemText(hDlg, IDD_PROMPT, lprd->lpszPrompt);
}
if (lprd->hIcon)
{
Static_SetIcon(GetDlgItem(hDlg, IDD_ICON), lprd->hIcon);
}
if (lprd->dwFlags & RFD_NOBROWSE)
{
HWND hBrowse;
hBrowse = GetDlgItem(hDlg, IDD_BROWSE);
ExchangeWindowPos(hBrowse, GetDlgItem(hDlg, IDCANCEL));
ExchangeWindowPos(hBrowse, GetDlgItem(hDlg, IDOK));
ShowWindow(hBrowse, SW_HIDE);
}
if (lprd->dwFlags & RFD_NOSHOWOPEN)
{
ShowWindow(GetDlgItem(hDlg, IDD_RUNDLGOPENPROMPT), SW_HIDE);
}
#ifdef SHOWSTATES
/* Note that we need to fill this list first so that the SELCHANGE
* message sent below will do the right thing.
*/
hCB = GetDlgItem(hDlg, IDD_STATE);
for (i = 0; i < ARRAYSIZE(pnStates); ++i)
{
if (SendMessage(hCB, CB_ADDSTRING, 0, (LPARAM)(LPTSTR)szStates[i]) < 0)
{
break;
}
}
SendMessage(hCB, CB_SETCURSEL, 0, 0L);
#endif
hCB = GetDlgItem(hDlg, IDD_COMMAND);
SendMessage(hCB, CB_LIMITTEXT, MAX_PATH-1, 0L);
OpenRunDlgMRU();
if (g_hMRURunDlg)
{
int nMax;
TCHAR szCommand[MAX_PATH];
for (nMax=EnumMRUList(g_hMRURunDlg, -1, NULL, 0), i=0; i<nMax; ++i)
{
if (EnumMRUList(g_hMRURunDlg, i, szCommand, ARRAYSIZE(szCommand)) > 0)
{
PSTARTINFO pStartInfo;
/* Parse the line into the STARTINFO struct
*/
pStartInfo = ParseIniLine(szCommand);
/* The command to run goes in the combobox.
*/
if (SendMessage(hCB, CB_ADDSTRING, 0, (LPARAM)(LPTSTR)szCommand)
!= i)
{
if (pStartInfo)
{
LocalFree((HLOCAL)pStartInfo);
}
}
else
{
SendMessage(hCB, CB_SETITEMDATA, i, (LPARAM)(LPSTARTINFO)pStartInfo);
}
}
}
}
if (!(lprd->dwFlags & RFD_NODEFFILE))
{
SendMessage(hCB, CB_SETCURSEL, 0, 0L);
}
SendMessage(hDlg, WM_COMMAND, MAKEWPARAM(IDD_COMMAND, CBN_SELCHANGE), (LPARAM) hCB);
SetWindowLong(hDlg, DWL_USER, (LONG)lprd);
//.........这里部分代码省略.........
示例8: args_tchar
void ProgramRunner::launchProcess( int child_stdout ) {
#ifdef _WIN32
stringstream ss;
for( unsigned i=0; i < _argv.size(); i++ ) {
if (i) ss << ' ';
if (_argv[i].find(' ') == string::npos)
ss << _argv[i];
else {
ss << '"';
// escape all embedded quotes
for (size_t j=0; j<_argv[i].size(); ++j) {
if (_argv[i][j]=='"') ss << '"';
ss << _argv[i][j];
}
ss << '"';
}
}
string args = ss.str();
boost::scoped_array<TCHAR> args_tchar (new TCHAR[args.size() + 1]);
size_t i;
for(i=0; i < args.size(); i++)
args_tchar[i] = args[i];
args_tchar[i] = 0;
HANDLE h = (HANDLE)_get_osfhandle(child_stdout);
verify(h != INVALID_HANDLE_VALUE);
verify(SetHandleInformation(h, HANDLE_FLAG_INHERIT, 1));
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.hStdError = h;
si.hStdOutput = h;
si.dwFlags |= STARTF_USESTDHANDLES;
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
bool success = CreateProcess( NULL, args_tchar.get(), NULL, NULL, true, 0, NULL, NULL, &si, &pi) != 0;
if (!success) {
LPSTR lpMsgBuf=0;
DWORD dw = GetLastError();
FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,
0, NULL );
stringstream ss;
ss << "couldn't start process " << _argv[0] << "; " << lpMsgBuf;
uassert(14042, ss.str(), success);
LocalFree(lpMsgBuf);
}
CloseHandle(pi.hThread);
_pid = ProcessId::fromNative(pi.dwProcessId);
registry._handles.insert( make_pair( _pid, pi.hProcess ) );
#else
scoped_array<const char *> argvStorage( new const char* [_argv.size()+1] );
const char** argv = argvStorage.get();
for (unsigned i=0; i < _argv.size(); i++) {
argv[i] = _argv[i].c_str();
}
argv[_argv.size()] = 0;
scoped_array<const char *> envStorage( new const char* [2] );
const char** env = envStorage.get();
env[0] = NULL;
env[1] = NULL;
bool isMongos = ( _argv[0].find( "mongos" ) != string::npos );
pid_t nativePid = fork();
_pid = ProcessId::fromNative(nativePid);
// Async signal unsafe functions should not be called in the child process.
verify( nativePid != -1 );
if ( nativePid == 0 ) {
// DON'T ASSERT IN THIS BLOCK - very bad things will happen
if ( dup2( child_stdout, STDOUT_FILENO ) == -1 ||
dup2( child_stdout, STDERR_FILENO ) == -1 ) {
// Async signal unsafe code reporting a terminal error condition.
cout << "Unable to dup2 child output: " << errnoWithDescription() << endl;
::_Exit(-1); //do not pass go, do not call atexit handlers
}
// Heap-check for mongos only. 'argv[0]' must be in the path format.
if ( isMongos ) {
#if defined(HEAP_CHECKING)
env[0] = "HEAPCHECK=normal";
//.........这里部分代码省略.........
示例9: wxSysErrorCode
// get error message from system
const wxChar *wxSysErrorMsg(unsigned long nErrCode)
{
if ( nErrCode == 0 )
nErrCode = wxSysErrorCode();
#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
static wxChar s_szBuf[1024];
// get error message from system
LPVOID lpMsgBuf;
if ( ::FormatMessage
(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
nErrCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf,
0,
NULL
) == 0 )
{
// if this happens, something is seriously wrong, so don't use _() here
// for safety
wxSprintf(s_szBuf, wxS("unknown error %lx"), nErrCode);
return s_szBuf;
}
// copy it to our buffer and free memory
// Crashes on SmartPhone (FIXME)
#if !defined(__SMARTPHONE__) /* of WinCE */
if( lpMsgBuf != 0 )
{
wxStrlcpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf));
LocalFree(lpMsgBuf);
// returned string is capitalized and ended with '\r\n' - bad
s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
size_t len = wxStrlen(s_szBuf);
if ( len > 0 ) {
// truncate string
if ( s_szBuf[len - 2] == wxS('\r') )
s_szBuf[len - 2] = wxS('\0');
}
}
else
#endif // !__SMARTPHONE__
{
s_szBuf[0] = wxS('\0');
}
return s_szBuf;
#else // !__WXMSW__
#if wxUSE_UNICODE
static wchar_t s_wzBuf[1024];
wxConvCurrent->MB2WC(s_wzBuf, strerror((int)nErrCode),
WXSIZEOF(s_wzBuf) - 1);
return s_wzBuf;
#else
return strerror((int)nErrCode);
#endif
#endif // __WXMSW__/!__WXMSW__
}
示例10: dup
//.........这里部分代码省略.........
StartupInfo.hStdError = mStdErrorHandle;
else
StartupInfo.hStdError =GetStdHandle(STD_ERROR_HANDLE);
if (mStdInputFilename.length())
StartupInfo.hStdInput = mStdInputHandle;
else
StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
if (mStdOutputFilename.length())
StartupInfo.hStdOutput = mStdOutputHandle;
else
StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
//now apply the env variables the user may have set
ApplyEnv();
//3...2...1... LAUNCH!!!!
int retcode = CreateProcess(
NULL,
// name of executable module (null because we want to execute all commands)
// even things such as dir
(char *)cmdLine.data(), // command line string
NULL,
NULL,
//this originally was TRUE but the web browser was never coming back.
FALSE, // handle inheritance flag
// CREATE_NEW_CONSOLE,
CREATE_NO_WINDOW | DETACHED_PROCESS, // creation flags
NULL, // new environment block
startupDir.data(), // startupdir
&StartupInfo,
&ProcessInformation
);
if (retcode != 0)
{
//translate the incoming priority to Wnt values
DWORD wntPrio = NORMAL_PRIORITY_CLASS;
switch(prioClass)
{
case IdlePriorityClass: wntPrio = IDLE_PRIORITY_CLASS;
break;
case NormalPriorityClass: wntPrio = NORMAL_PRIORITY_CLASS;
break;
case HighPriorityClass: wntPrio = HIGH_PRIORITY_CLASS;
break;
case RealtimePriorityClass: wntPrio = REALTIME_PRIORITY_CLASS;
break;
default: osPrintf("**** Invalid process priority class specified!\n");
osPrintf("*** Defaulting to NormalPriorityClass *** \n");
break;
}
if (!SetPriorityClass(ProcessInformation.hProcess, wntPrio))
{
osPrintf("*** Could not change the process priority on launch ***\n");
osPrintf("*** Priority will be the parents priority ! ***\n");
}
if (bExeclusive)
{
//here is where we check if a process by the same name is already running
}
mPID = ProcessInformation.dwProcessId;
mParentPID = getpid();
mhProcess = ProcessInformation.hProcess;
mhThread = ProcessInformation.hThread;
retval = OS_SUCCESS;
}
else
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
osPrintf("***** ERROR FROM LAUNCH: %s",(LPCTSTR)lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
}
/*
dup2(saved_stderr,2);
dup2(saved_stdout,1);
dup2(saved_stdin, 0);
*/
return retval;
}
示例11: GetDeviceInterfaceDetailData
PSP_DEVICE_INTERFACE_DETAIL_DATA
GetDeviceInterfaceDetailData(
_In_ LPGUID InterfaceGuid
)
{
HDEVINFO HardwareDeviceInfo;
SP_DEVICE_INTERFACE_DATA DeviceInterfaceData;
PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = NULL;
ULONG Length, RequiredLength = 0;
BOOL bResult;
HardwareDeviceInfo = SetupDiGetClassDevs(
InterfaceGuid,
NULL,
NULL,
(DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
if (HardwareDeviceInfo == INVALID_HANDLE_VALUE) {
printf("SetupDiGetClassDevs failed!\n");
exit(1);
}
DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
bResult = SetupDiEnumDeviceInterfaces(HardwareDeviceInfo,
0,
InterfaceGuid,
0,
&DeviceInterfaceData);
if (bResult == FALSE) {
LPVOID lpMsgBuf = NULL;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) &lpMsgBuf,
0,
NULL
)) {
printf("Error: %s", (LPSTR)lpMsgBuf);
LocalFree(lpMsgBuf);
}
printf("SetupDiEnumDeviceInterfaces failed.\n");
SetupDiDestroyDeviceInfoList(HardwareDeviceInfo);
exit(1);
}
SetupDiGetDeviceInterfaceDetail(
HardwareDeviceInfo,
&DeviceInterfaceData,
NULL,
0,
&RequiredLength,
NULL
);
DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) LocalAlloc(LMEM_FIXED, RequiredLength);
if (DeviceInterfaceDetailData == NULL) {
SetupDiDestroyDeviceInfoList(HardwareDeviceInfo);
printf("Failed to allocate memory.\n");
exit(1);
}
DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
Length = RequiredLength;
bResult = SetupDiGetDeviceInterfaceDetail(
HardwareDeviceInfo,
&DeviceInterfaceData,
DeviceInterfaceDetailData,
Length,
&RequiredLength,
NULL);
if (bResult == FALSE) {
LPVOID lpMsgBuf = NULL;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) &lpMsgBuf,
0,
NULL)) {
MessageBox(NULL, (LPCTSTR) lpMsgBuf, "Error", MB_OK);
LocalFree(lpMsgBuf);
}
//.........这里部分代码省略.........
示例12: fprintf
bool vrpn_Semaphore::init() {
#ifdef sgi
if (vrpn_Semaphore::ppaArena==NULL) {
vrpn_Semaphore::allocArena();
}
if (cResources==1) {
fUsingLock=true;
ps=NULL;
// use lock instead of semaphore
if ((l = usnewlock(vrpn_Semaphore::ppaArena)) == NULL) {
fprintf(stderr,"vrpn_Semaphore::vrpn_Semaphore: error allocating lock from arena.\n");
return false;
}
} else {
fUsingLock=false;
l=NULL;
if ((ps = usnewsema(vrpn_Semaphore::ppaArena, cResources)) == NULL) {
fprintf(stderr,"vrpn_Semaphore::vrpn_Semaphore: error allocating semaphore from arena.\n");
return false;
}
}
#elif defined(_WIN32)
// args are security, initial count, max count, and name
// TCH 20 Feb 2001 - Make the PC behavior closer to the SGI behavior.
int numMax = cResources;
if (numMax < 1) {
numMax = 1;
}
hSemaphore = CreateSemaphore(NULL, cResources, numMax, NULL);
if (!hSemaphore) {
// get error info from windows (from FormatMessage help page)
LPVOID lpMsgBuf;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
// Default language
(LPTSTR) &lpMsgBuf, 0, NULL );
fprintf(stderr,"vrpn_Semaphore::vrpn_Semaphore: error creating semaphore, "
"WIN32 CreateSemaphore call caused the following error: %s\n", (LPTSTR) lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
return false;
}
#elif defined(__APPLE__)
// We need to use sem_open on the mac because sem_init is not implemented
int numMax = cResources;
if (numMax < 1) {
numMax = 1;
}
char *tempname = new char[100];
sprintf(tempname, "/tmp/vrpn_sem.XXXXXXX");
semaphore = sem_open(mktemp(tempname), O_CREAT, 0600, numMax);
if (semaphore == SEM_FAILED) {
perror("vrpn_Semaphore::vrpn_Semaphore: error opening semaphore");
delete [] tempname;
return false;
}
delete [] tempname;
#else
// Posix threads are the default.
// We use sem_init on linux (instead of sem_open).
int numMax = cResources;
if (numMax < 1) {
numMax = 1;
}
semaphore = new sem_t;
if (sem_init(semaphore, 0, numMax) != 0) {
perror("vrpn_Semaphore::vrpn_Semaphore: error initializing semaphore");
return false;
}
#endif
return true;
}
示例13: uscsetlock
// 0 if it can't get the resource, 1 if it can
// -1 if fail
int vrpn_Semaphore::condP() {
int iRetVal=1;
#ifdef sgi
if (fUsingLock) {
// don't spin at all
iRetVal = uscsetlock(l, 0);
if (iRetVal<=0) {
perror("vrpn_Semaphore::condP: uscsetlock:");
return -1;
}
} else {
iRetVal = uscpsema(ps);
if (iRetVal<=0) {
perror("vrpn_Semaphore::condP: uscpsema:");
return -1;
}
}
#elif defined(_WIN32)
switch (WaitForSingleObject(hSemaphore, 0)) {
case WAIT_OBJECT_0:
// got the resource
break;
case WAIT_TIMEOUT:
// resource not free
iRetVal=0;
break;
case WAIT_ABANDONED:
ALL_ASSERT(0,"vrpn_Semaphore::condP: thread holding resource died");
return -1;
break;
case WAIT_FAILED:
// get error info from windows (from FormatMessage help page)
LPVOID lpMsgBuf;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
// Default language
(LPTSTR) &lpMsgBuf, 0, NULL );
fprintf(stderr, "Semaphore::condP: error waiting for resource, "
"WIN32 WaitForSingleObject call caused the following error: %s", (LPTSTR) lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
return -1;
break;
default:
ALL_ASSERT(0,"vrpn_Semaphore::p: unknown return code");
return -1;
}
#else
// Posix by default
iRetVal = sem_trywait(semaphore);
if (iRetVal == 0) { iRetVal = 1;
} else if (errno == EAGAIN) { iRetVal = 0;
} else {
perror("vrpn_Semaphore::condP: ");
iRetVal = -1;
}
#endif
return iRetVal;
}
示例14: adjustLockDirectoryAccess
// allow different users to read\write\delete files in lock directory
// in case of any error just log it and don't stop engine execution
void adjustLockDirectoryAccess(const char* pathname)
{
PSECURITY_DESCRIPTOR pSecDesc = NULL;
PSID pSID_Users = NULL;
PSID pSID_Administrators = NULL;
PACL pNewACL = NULL;
try
{
// We should pass root directory in format "C:\" into GetVolumeInformation().
// In case of pathname is not local folder (i.e. \\share\folder) let
// GetVolumeInformation() return an error.
Firebird::PathName root(pathname);
const size_t pos = root.find(':', 0);
if (pos == 1)
{
root.erase(pos + 1, root.length());
PathUtils::ensureSeparator(root);
}
DWORD fsflags;
if (!GetVolumeInformation(root.c_str(), NULL, 0, NULL, NULL, &fsflags, NULL, 0))
Firebird::system_error::raise("GetVolumeInformation");
if (!(fsflags & FS_PERSISTENT_ACLS))
return;
// Adjust security for our new folder : allow BUILTIN\Users group to
// read\write\delete files
PACL pOldACL = NULL;
if (GetNamedSecurityInfo((LPSTR) pathname,
SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
NULL, NULL, &pOldACL, NULL,
&pSecDesc) != ERROR_SUCCESS)
{
Firebird::system_error::raise("GetNamedSecurityInfo");
}
SID_IDENTIFIER_AUTHORITY sidAuth = SECURITY_NT_AUTHORITY;
if (!AllocateAndInitializeSid(&sidAuth, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pSID_Users))
{
Firebird::system_error::raise("AllocateAndInitializeSid");
}
if (!AllocateAndInitializeSid(&sidAuth, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSID_Administrators))
{
Firebird::system_error::raise("AllocateAndInitializeSid");
}
EXPLICIT_ACCESS eas[2];
memset(eas, 0, sizeof(eas));
eas[0].grfAccessPermissions = FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE;
eas[0].grfAccessMode = GRANT_ACCESS;
eas[0].grfInheritance = SUB_OBJECTS_ONLY_INHERIT;
eas[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
eas[0].Trustee.TrusteeType = TRUSTEE_IS_GROUP;
eas[0].Trustee.ptstrName = (LPSTR) pSID_Users;
eas[1].grfAccessPermissions = FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE;
eas[1].grfAccessMode = GRANT_ACCESS;
eas[1].grfInheritance = SUB_OBJECTS_ONLY_INHERIT;
eas[1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
eas[1].Trustee.TrusteeType = TRUSTEE_IS_GROUP;
eas[1].Trustee.ptstrName = (LPSTR) pSID_Administrators;
if (SetEntriesInAcl(2, eas, pOldACL, &pNewACL) != ERROR_SUCCESS)
Firebird::system_error::raise("SetEntriesInAcl");
if (SetNamedSecurityInfo((LPSTR) pathname,
SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
NULL, NULL, pNewACL, NULL) != ERROR_SUCCESS)
{
Firebird::system_error::raise("SetNamedSecurityInfo");
}
}
catch (const Firebird::Exception& ex)
{
Firebird::string str;
str.printf("Error adjusting access rights for folder \"%s\" :", pathname);
iscLogException(str.c_str(), ex);
}
if (pSID_Users) {
FreeSid(pSID_Users);
}
if (pSID_Administrators) {
FreeSid(pSID_Administrators);
}
if (pNewACL) {
LocalFree(pNewACL);
}
if (pSecDesc) {
LocalFree(pSecDesc);
}
//.........这里部分代码省略.........
示例15: MessageBox
int MachineInstaller::PerformMachineInstallSetup()
{
wchar_t packageName[512];
if (!findPackageFromEmbeddedZip(packageName, sizeof(packageName))) {
MessageBox(NULL, L"Corrupt installer", L"Cannot find package name for installer, is it created correctly?", MB_OK);
return ERROR_INVALID_PARAMETER;
}
wchar_t machineInstallFolder[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, machineInstallFolder);
wcscat(machineInstallFolder, L"\\SquirrelMachineInstalls");
// NB: This is the DACL for Program Files
wchar_t sddl[512] = L"D:PAI(A;;FA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;CIIO;GA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;;0x1301bf;;;SY)(A;OICIIO;GA;;;SY)(A;;0x1301bf;;;BA)(A;OICIIO;GA;;;BA)(A;;0x1200a9;;;BU)(A;OICIIO;GXGR;;;BU)(A;OICIIO;GA;;;CO)";
if (IsWindows8OrGreater()) {
// Add ALL APPLICATION PACKAGES account (Only available on Windows 8 and greater)
wcscat(sddl, L"(A;;0x1200a9;;;AC)(A;OICIIO;GXGR;;;AC)");
}
PSECURITY_DESCRIPTOR descriptor;
ConvertStringSecurityDescriptorToSecurityDescriptor(
sddl,
SDDL_REVISION_1,
&descriptor, NULL);
SECURITY_ATTRIBUTES attrs;
attrs.nLength = sizeof(SECURITY_ATTRIBUTES);
attrs.bInheritHandle = false;
attrs.lpSecurityDescriptor = descriptor;
if (!CreateDirectory(machineInstallFolder, &attrs) && GetLastError() != ERROR_ALREADY_EXISTS) {
LocalFree(descriptor);
return GetLastError();
}
LocalFree(descriptor);
wcscat(machineInstallFolder, L"\\");
wcscat(machineInstallFolder, packageName);
wcscat(machineInstallFolder, L".exe");
wchar_t ourFile[MAX_PATH];
HMODULE hMod = GetModuleHandle(NULL);
GetModuleFileName(hMod, ourFile, _countof(ourFile));
if (!CopyFile(ourFile, machineInstallFolder, false)) {
return GetLastError();
}
HKEY runKey;
DWORD dontcare;
if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &runKey, &dontcare) != ERROR_SUCCESS) {
return GetLastError();
}
wcscat_s(machineInstallFolder, L" --checkInstall");
if (RegSetValueEx(runKey, packageName, 0, REG_SZ, (BYTE*)machineInstallFolder, (wcsnlen(machineInstallFolder, sizeof(machineInstallFolder)) + 1) * sizeof(wchar_t)) != ERROR_SUCCESS) {
return GetLastError();
}
RegCloseKey(runKey);
return 0;
}