/* ** MapQueueMove ** ** Applies a function to each element in a queue. If the function returns ** moveVal, it enqueues the element to q2, otherwise it requeues it to ** the original queue. */ int MapQueueMove(QUEUE q, int (*pFunc)(void *, void**), void **argv, int moveVal, QUEUE q2) { void *item; int count = QueueCount(q); int status = SUCCESS; TypeCheck(q,TYPE_QUEUE); TypeCheck(q2,TYPE_QUEUE); assert(! IS_ERROR(moveVal)); while (count--) { item = DeQueue(q); if (NULL == item) return(-1); status = (*pFunc)(item,argv); if (IS_ERROR(status)) return(status); if (status == moveVal) status = EnQueue(q2,item); else status = EnQueue(q,item); if (IS_ERROR(status)) return(status); } return(status); }
/* ** MapQueue ** Applies a function to all elements of a queue. ** ** As long as each function continues to return a non-negative value, ** MapQueue will apply it to the next element. When a negative return ** value occurs, MapQueue will stop. ** ** In any case, it returns the return value from the last call to the ** applied function, or SUCCESS if the queue is empty. ** ** Important note: ** Do not attempt to enqueue or dequeue in a MapQueue'd ** function. It will be ruinous. */ int MapQueue(QUEUE queue, int (*pFunc)(void *, void**), void **argv) { TRAY tray; int status; int count; assert(queue); TypeCheck(queue,TYPE_QUEUE); tray = queue->front; for (tray = queue->front, count = queue->count, status = SUCCESS; (! IS_ERROR(status)) && tray != NULL && count > 0; tray = (tray->next), count-- ) status = (*pFunc)(tray->item,argv); if (! IS_ERROR(status)) /* consistency check */ assert (NULL == tray && count == 0); return(status); }
/* Construct IsoDepTag @param hw : Instantiated NFC */ IsoDepTag::IsoDepTag(NFC* hw) { ovrImpl = NULL; if (hw == NULL) { LOGE("NFC H/W not initialized"); return; } ulhw = hw; /*Generate NDEF Records for default IsoDepApp Implementation*/ NdefRecord* rcds[] = {NdefRecord::createTextRecord("Date : 2014.1.17", "en",NdefRecord::UTF8),NdefRecord::createAndroidApplicationRecord("com.example.nfc_client"),NdefRecord::createUriRecord(URI_HTTP,"com.example.nfc_client")}; NdefMessage msg(rcds, 3); /*Construct Default Implementation of IsoDepApp*/ defaultImpl = new DefaultDepAppImpl(msg); /** * To configure pn532 as a picc which support NFC Type Tag, PICC Emulation Mode "Must be" enabled * otherwise it'll send error code when any command which is relevant to Picc Operation is received. * @param : Auto ATR_RES | ISO_14443-4 Picc Emulation * */ if (IS_ERROR(ulhw->setParameter(1 << 2 | 1 << 5))) { LOGE("Fail to config Pn532 as PICC Target"); return; } #if DBG LOGD("Parameter Configured"); #endif if (IS_ERROR(ulhw->SAMConfiguration(0x01, 0xF, true))) { LOGE("PN532 fails to enter to normal state"); } #if DBG LOGD("Configuration of SAM is done"); #endif }
/* Обработка уведомления о запросе ассоциации */ void znet_assoc_indication( zcall_t *zc ) { neighbor_t *child_ptr; zargs_passoc_t *arg = (zargs_passoc_t *)(zc->args); bool_t alloc_addr; /* Логический флаг - выделять ли короткий адрес */ if( nwkMaxChildren <= child_count() ) goto assoc_denied; /* Достигнут максимальный порог числа детей. Больше детей заводить нельзя. */ child_ptr = nbr_place_by_eaddr( &(arg->dev_addr) ); /* Ищем место в таблице соседей */ if( !IN_TABLE( child_ptr) ) goto assoc_denied; /* Не удалось найти место в таблице соседей */ alloc_addr = TRUE; if( child_ptr->ext_addr == arg->dev_addr ) { /* Уже есть запись об узле в таблице соседей */ if( ( child_ptr->relationship == NWK_PARENT )||( child_ptr->relationship == NWK_SIBLING ) ) goto assoc_denied; /* Родителя и братьев не присоединяем */ if( ( child_ptr->relationship == NWK_CHILD ) ||( ( child_ptr->relationship == NWK_PREVIOUS_CHILD )&&( child_ptr->net_addr != 0xFFFF ) ) ) alloc_addr = FALSE; /* Не выделяем короткий адрес детям, у которых он уже есть */ } if( alloc_addr == TRUE ) { arg->assoc_addr = znet_addr_alloc( arg->cap_info.dev_type ); if( child_ptr->net_addr == 0xFFFF ) { /* Не удалось выделить короткий адрес */ bcn_cap_off( arg->cap_info.dev_type ); /* Сбрасываем флаг разрешения присоединения для данного типа устройств */ child_ptr->busy = 0; /* Запись не очень важная. Можно и удалить. */ goto assoc_denied; } } /* Заносим в таблицу соседей информацию о новом дочернем узле */ child_ptr->rx_on_when_idle = arg->cap_info.rx_on_when_idle; child_ptr->potential_parent = 0; child_ptr->permit_joining = 0; child_ptr->dev_type = ( arg->cap_info.dev_type == FFD )? ZIGBEE_ROUTER : ZIGBEE_ENDDEV; child_ptr->relationship = NWK_CHILD; child_ptr->channel = nwkExtraAttr.channel; child_ptr->beacon_order = macBeaconOrder; child_ptr->depth = nwkExtraAttr.depth+1; child_ptr->ext_addr = arg->dev_addr; child_ptr->net_addr = arg->assoc_addr; child_ptr->e_panid = nwkExtendedPANID; /* Отправляем положительный ответ узлу */ ZCALL_INIT( zc, ZCALL_MLME_ASSOC_PARENT, znet_pjoin_done ); arg->status = SUCCESS; if( IS_ERROR(zcall_invoke( zc )) ) zcall_del( zc ); return; assoc_denied: /* Присоединить узел не получилось. Отправляем узлу отрицательный ответ. */ arg->assoc_addr = 0xFFFF; arg->status = MAC_PAN_ACCESS_DENIED; ZCALL_INIT( zc, ZCALL_MLME_ASSOC_PARENT, 0 ); /* Подтверждение нам не нужно */ if( IS_ERROR(zcall_invoke( zc )) ) zcall_del( zc ); return; }
int main(int argc, char *argv[]) { int ecode; bfcc_options bfopts = {0}; if (parse_arguments(argc, argv, &bfopts) != 0) { return -2; } FILE *f = stdin; if (bfopts.input_file != 0) { f = fopen(bfopts.input_file, "r"); if (!f) { fprintf(stderr, "Unknown file.\n"); return ERROR_FILE_NOT_FOUND; } } c99_options opts; c99_options_default(&opts); backend back = create_c99_backend(&opts); ecode = back.begin(&back, stdout); FATAL_IF_ERROR(ecode, "Backend preamble generation"); tokeniser *t = tokeniser_setup(f); CHECK_ALLOCATION(t, "Tokeniser setup"); while (1) { token tok; int error = tokeniser_next(t, &tok); if (IS_ERROR(error)) { fprintf(stderr, "Tokenisation error detected: %d.\n", error); return ERROR_TOKENISATION; } if (tok == token_eof) break; if (IS_ERROR(back.emit(&back, stdout, (token) tok))) { fprintf(stderr, "Failure encountered when translating token: %s\n", token_name((token) tok)); } } ecode = back.end(&back, stdout); FATAL_IF_ERROR(ecode, "Backend could not finish") return 0; }
void stimer_fired( const uint8_t tnum ) { port_t ledport; result_t res; if( tnum != TIMER_NUM ) return; if( state == GERCON_OPEN ) { port_read( RED_PORT, RED_PIN, &ledport ); ledport ^= RED_PIN; port_write( RED_PORT, RED_PIN, ledport ); res = stimer_set( TIMER_NUM, RED_PERIOD ); } else if( state == GERCON_CLOSE ) { if( MAX_GREEN_COUNT <= green_count ) port_write( GREEN_PORT, GREEN_PIN, PIN_HI ); green_count++; port_read( GREEN_PORT, GREEN_PIN, &ledport ); ledport ^= GREEN_PIN; port_write( GREEN_PORT, GREEN_PIN, ledport ); res = stimer_set( TIMER_NUM, GREEN_PERIOD ); } if( IS_ERROR(res) ) port_write( RED_PORT, RED_PIN, PIN_HI ); return; }
static void delete_config( void * priv, int delta ) { char* path = get_config_dir(); struct fio_file file; struct fio_dirent * dirent = FIO_FindFirstEx( path, &file ); if( IS_ERROR(dirent) ) return; do { if (file.mode & ATTR_DIRECTORY) { continue; // is a directory } char fn[0x80]; snprintf(fn, sizeof(fn), "%s%s", path, file.name); FIO_RemoveFile(fn); } while( FIO_FindNextEx( dirent, &file ) == 0); FIO_FindClose(dirent); config_deleted = 1; if (config_autosave) { /* at shutdown, config autosave may re-create the config files we just deleted */ /* => disable this feature in RAM only, until next reboot, without commiting it to card */ config_autosave = 0; } }
uint8_t IsoDepTag::listenRATS() { NfcTargetConfig config(1 << 2 | 1 << 0, MIFARE_PARAM, FELICA_PARAM, NFCID); if (IS_ERROR(ulhw->tgInitAsTarget(&config, rxBuf))) { return 0xFF; } return rxBuf[2] == CMD_RATS ? rxBuf[3] : 0xFF; }
*/ void Do_Function(REBVAL *func) /* ***********************************************************************/ { REBVAL *result; REBVAL *ds; #if !defined(NDEBUG) const REBYTE *name = Get_Word_Name(DSF_LABEL(DSF)); #endif Eval_Functions++; //Dump_Block(VAL_FUNC_BODY(func)); result = Do_Blk(VAL_FUNC_BODY(func), 0); ds = DS_OUT; if (IS_ERROR(result) && IS_RETURN(result)) { // Value below is kept safe from GC because no-allocation is // done between point of SET_THROW and here. if (VAL_ERR_VALUE(result)) *ds = *VAL_ERR_VALUE(result); else SET_UNSET(ds); } else *ds = *result; // Set return value (atomic) }
*/ int main(int argc, char **argv) /* ***********************************************************************/ { char *cmd; // Parse command line arguments. Done early. May affect REBOL boot. Parse_Args(argc, argv, &Main_Args); Print_Str("REBOL 3.0\n"); REBOL_Init(&Main_Args); // Evaluate user input: while (TRUE) { cmd = Prompt_User(); REBOL_Do_String(cmd); if (!IS_UNSET(DS_TOP)) { //if (DSP > 0) { if (!IS_ERROR(DS_TOP)) { Prin("== "); Print_Value(DS_TOP, 0, TRUE); } else Print_Value(DS_TOP, 0, FALSE); //} } //DS_DROP; // result } return 0; }
static void find_scripts(void) { struct fio_file file; struct fio_dirent * dirent = FIO_FindFirstEx( "ML/SCRIPTS/", &file ); if( IS_ERROR(dirent) ) { NotifyBox(2000, "Scripts dir missing" ); return; } script_cnt = 0; do { if (file.mode & ATTR_DIRECTORY) continue; // is a directory if (is_valid_script_filename(file.name)) { snprintf(script_list[script_cnt++], FILENAME_SIZE, "%s", file.name); if (script_cnt >= MAX_SCRIPT_NUM) { NotifyBox(2000, "Too many scripts" ); break; } } } while( FIO_FindNextEx( dirent, &file ) == 0); FIO_FindClose(dirent); for (int i = 0; i < script_cnt; i++) script_parse_header(i); }
/* * Open a drive or volume with optional write and lock access * Return INVALID_HANDLE_VALUE (/!\ which is DIFFERENT from NULL /!\) on failure. */ static HANDLE GetHandle(char* Path, BOOL bWriteAccess, BOOL bLockDrive) { int i; DWORD size; HANDLE hDrive = INVALID_HANDLE_VALUE; if (Path == NULL) goto out; hDrive = CreateFileA(Path, GENERIC_READ|(bWriteAccess?GENERIC_WRITE:0), FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); if (hDrive == INVALID_HANDLE_VALUE) { uprintf("Could not open drive %s: %s\n", Path, WindowsErrorString()); goto out; } if (bWriteAccess) { uprintf("Caution: Opened drive %s for write access\n", Path); } if (bLockDrive) { for (i = 0; i < DRIVE_ACCESS_RETRIES; i++) { if (DeviceIoControl(hDrive, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &size, NULL)) goto out; if (IS_ERROR(FormatStatus)) // User cancel break; Sleep(DRIVE_ACCESS_TIMEOUT/DRIVE_ACCESS_RETRIES); } // If we reached this section, either we didn't manage to get a lock or the user cancelled uprintf("Could not get exclusive access to device %s: %s\n", Path, WindowsErrorString()); safe_closehandle(hDrive); } out: return hDrive; }
*/ REBINT Check_Error(REBVAL *val) /* ** Process a loop exceptions. Pass in the TOS value, returns: ** ** 2 - if break/return, change val to that set by break ** 1 - if break ** -1 - if continue, change val to unset ** 0 - if not break or continue ** else: error if not an ERROR value ** ***********************************************************************/ { // It's UNSET, not an error: if (!IS_ERROR(val)) Trap0(RE_NO_RETURN); //!!! change to special msg // If it's a BREAK, check for /return value: if (IS_BREAK(val)) { if (VAL_ERR_VALUE(val)) { *val = *VAL_ERR_VALUE(val); return 2; } else { SET_UNSET(val); return 1; } } if (IS_CONTINUE(val)) { SET_UNSET(val); return -1; } return 0; // Else: Let all other errors return as values. }
bool DriverMinifilterCommunicator::InstallDriver(void) { // don't install the driver if it already exists if(m_isInstalled) { return true; } // check if current user is administrator Logger::Instance().Log(_T("Check if running under administrator context..."), INFO); if(!Utils::IsAdmin()) { Logger::Instance().Log(_T("Not admin - try to run the program as administrator"), CRITICAL_ERROR); return false; } Logger::Instance().Log(_T("Running as administrator -- connecting to driver port"), SUCCESS); // connect to communication port HRESULT hResult = FilterConnectCommunicationPort( PORT_NAME, // port name 0, // options must be zero (documentation) NULL, // don't pass context to connect routine 0, // size of context NULL, // don't inherit this handle &m_driverPort // handle to communication port ); if (IS_ERROR( hResult )) { Logger::Instance().Log(_T("Cannot connect to driver port"), CRITICAL_ERROR); return false; } m_isInstalled = true; return true; }
BOOL CCookieMgr::SaveToFile(LPCSTR lpszFile, BOOL bKeepExists) { if(bKeepExists) { if(!LoadFromFile(lpszFile, TRUE) && !IS_ERROR(ERROR_FILE_NOT_FOUND)) return FALSE; } BOOL isOK = FALSE; FILE* pFile = nullptr; if((pFile = fopen(lpszFile, "w")) == nullptr) goto _ERROR_END; { __time64_t tmCurrent = _time64(nullptr); CReadLock locallock(m_cs); for(CCookieDomainMapCI it = m_cookies.begin(), end = m_cookies.end(); it != end; ++it) { const CStringA& strDomain = it->first; const CCookiePathMap& paths = it->second; for(CCookiePathMapCI it2 = paths.begin(), end2 = paths.end(); it2 != end2; ++it2) { const CStringA& strPath = it2->first; const CCookieSet& cookies = it2->second; if(fprintf(pFile, "%s %s\n", (LPCSTR)strDomain, (LPCSTR)strPath) < 0) goto _ERROR_END; for(CCookieSetCI it3 = cookies.begin(), end3 = cookies.end(); it3 != end3; ++it3) { const CCookie& cookie = *it3; if(cookie.expires <= tmCurrent) continue; LPCSTR lpszValue = (LPCSTR)cookie.value; if(lpszValue[0] == 0) lpszValue = " "; if(fprintf(pFile, "\t%s;%s;%lld;%d;%d;%d\n", (LPCSTR)cookie.name, lpszValue, cookie.expires, cookie.httpOnly, cookie.secure, cookie.sameSite) < 0) goto _ERROR_END; } } } } isOK = TRUE; _ERROR_END: if(pFile) fclose(pFile); return isOK; }
bool IsoDepTag::sendAckApdu() { uint8_t Ack[] = { 0x90, 0x00 }; PRINT_ARRAY("R-APDU Send : ", Ack, 2); if (IS_ERROR(ulhw->tgSetData(Ack, 2))) { return false; } return true; }
void WasapiOutputDevice::wasapiMixingThreadFunction() { //Stuff here can run outside the apartment. auto res = CoInitializeEx(NULL, COINIT_MULTITHREADED); if(IS_ERROR(res)) { logDebug("Wassapi device mixing thread: could not initialize COM. Error %i", (int)res); return; //We really can't recover from this. } IAudioRenderClient *renderClient_raw = nullptr; UINT32 padding, bufferSize; client->GetBufferSize(&bufferSize); client->GetCurrentPadding(&padding); client->GetService(IID_IAudioRenderClient, (void**)&renderClient_raw); auto renderClient = wrapComPointer(renderClient_raw); //We use double buffering, as processing can take a long time. //MSDN warns us not to do intensive processing between GetBuffer and ReleaseBuffer. float* workspace = new float[output_channels*bufferSize](); BYTE* audioBuffer = nullptr; sample_format_converter->write(bufferSize-padding, workspace); renderClient->GetBuffer(bufferSize-padding, &audioBuffer); memcpy(audioBuffer, workspace, sizeof(float)*output_channels*(bufferSize-padding)); renderClient->ReleaseBuffer(bufferSize-padding, 0); //The buffer is filled, so we begin processing. client->Start(); logDebug("Wasapi mixing thread: audio client is started. Mixing audio."); bool workspaceContainsChunk = false; while(should_continue.test_and_set()) { //Get the number of frames we want before continuing. double targetLatency = latency_predictor->predictLatency(); int targetLatencyFrames = (int)(output_sr*targetLatency); //Predicted latency can go too high for us to write anything, so clamp it at the buffer size less half a period. int targetLatencyFramesMax = (int)(wasapi_buffer_size-period_in_secs*output_sr*0.5); int targetPadding = std::min(targetLatencyFrames, targetLatencyFramesMax); client->GetCurrentPadding(&padding); //Wait until we have enough data. if(padding > targetPadding) { std::this_thread::sleep_for(std::chrono::milliseconds((padding-targetPadding)*1000/output_sr)); continue; } latency_predictor->beginPass(); if(workspaceContainsChunk == false) sample_format_converter->write(wasapi_chunk_length, workspace); workspaceContainsChunk = true; if(renderClient->GetBuffer(wasapi_chunk_length, &audioBuffer) != S_OK) { latency_predictor->endPass(); std::this_thread::yield(); continue; } memcpy(audioBuffer, workspace, sizeof(float)*wasapi_chunk_length*output_channels); renderClient->ReleaseBuffer(wasapi_chunk_length, 0); workspaceContainsChunk = false; latency_predictor->endPass(); } client->Stop(); client->Reset(); delete[] workspace; CoUninitialize(); logDebug("Wasapi mixing thread: exiting."); }
static void set_dtv_action(int ampIndex, action_t action) { DFBResult err; struct SMediaSession *media; media = &mediaTab[ampIndex]; // reset the query result media->queryResult[0] = 0; if (action == ACTION_POST) { err = media->amp->PostPresentationCmd(media->amp, &Command.generic); if (err != DFB_OK) { if (err == DFB_BUSY) { media->tempStatus = TSTS_BUSY; } else { media->tempStatus = TSTS_AMP_ERROR; } } } else if (action == ACTION_EXECUTE) { err = media->amp->ExecutePresentationCmd(media->amp, &Command.generic, &media->result.generic); if (err != DFB_OK || IS_ERROR(media->result.generic.value)) { if (err == DFB_BUSY) { D_ERROR("\tAMP BUSY!!!\n"); media->tempStatus = TSTS_BUSY; } else { D_ERROR("\tExecute error %d (%ld)\n", err, media->result.generic.value); media->tempStatus = TSTS_AMP_ERROR; } } else { if ((media->msRT->mediaSpace == MEDIA_SPACE_DTV) && (*(media->msRT->pCmd) == (int) DTVCmd_SET_PARTIALTSCBF)) { if (!ampCommand.dtv.param3.fPTSCallback) close_TS_file(ampIndex); } processMediaQuery(media); } } else { assert(false); } // set up adjustment structure for the next time adjustment.type = ADJ_MIXER_PAN_MAIN; return; }
int ISISandBoxSetRedirectPath(const wchar_t *aRedirectPath) { int errCode = ERROR_SUCCESS; HANDLE driverPort = NULL; __try { if (!aRedirectPath) { errCode = ERROR_INVALID_PARAMETER; __leave; } if (wcslen(aRedirectPath) > 260) { errCode = ERROR_BAD_LENGTH; __leave; } // 测试连接 HRESULT ret = FilterConnectCommunicationPort(ISISandBoxPortName, 0, NULL, 0, NULL, &driverPort); if (IS_ERROR(ret)) { errCode = ERROR_NOT_CONNECTED; __leave; } MESSAGE_REDIRECT_PATH_SEND message; message.Message.MessageType = MESSAGE_INSERT_REDIRECT_PATH; wcscpy_s(message.Message.RedirectPath, 260, aRedirectPath); _wcsupr_s(message.Message.RedirectPath, 260); // 在用户态强制改为大写 message.Message.Length = (ULONG)wcslen(aRedirectPath); DWORD replyLength = 0; MESSAGE_REPLY reply; ret = FilterSendMessage(driverPort, (PFILTER_MESSAGE_HEADER)&message, sizeof(MESSAGE_PROTECT_PATH_SEND), (PVOID)&reply, sizeof(MESSAGE_REPLY), &replyLength); if (ret != S_OK) { errCode = GetLastError(); __leave; } if (reply.MessageType != MESSAGE_INSERT_REDIRECT_PATH && reply.status != 0) { errCode = ERROR_NOT_SUPPORTED; __leave; } } __finally { CloseHandle(driverPort); driverPort = NULL; } return errCode; }
/* * Access BFILE element of the current row in the row set */ SQLITE_API int sqlite3_column_bfile( sqlite3_stmt *pStmt, int iCol, sqlite3_bfile **ppBfile ) { BfileHdl *pHdl; char * pLoc; int loc_size, rc; sqlite3 *db; #define IS_ERROR(rc) \ ((rc)!= SQLITE_OK && (rc) != SQLITE_ROW && (rc) != SQLITE_DONE) if (pStmt == NULL || iCol < 0 || iCol >= sqlite3_column_count(pStmt) || ppBfile == NULL) return SQLITE_ERROR; db = sqlite3_db_handle(pStmt); /* * If a memory allocation error occurs during the evaluation of any of * these routines, a default value is returned. The default value is * either the integer 0, the floating point number 0.0, or a NULL * pointer. Subsequent calls to sqlite3_errcode() will return * SQLITE_NOMEM. */ pLoc = (char *)sqlite3_column_blob(pStmt, iCol); if (pLoc == NULL) { *ppBfile = NULL; rc = sqlite3_errcode(db); return (IS_ERROR(rc) ? SQLITE_ERROR : SQLITE_OK); } pHdl = sqlite3_malloc(sizeof(BfileHdl)); if (pHdl == NULL) { *ppBfile = NULL; return SQLITE_ERROR; } pHdl->fd = -1; loc_size = sqlite3_column_bytes(pStmt, iCol); rc = get_full_path(db, pLoc, loc_size,&(pHdl->full_path)); if (rc) { if (pHdl != NULL) sqlite3_free(pHdl); *ppBfile = NULL; return SQLITE_ERROR; } *ppBfile = (sqlite3_bfile *)pHdl; return SQLITE_OK; }
result_t _atimer_set( const uint16_t obj_offset, const uint8_t tnum, const uint32_t tpoint ) { if( ISZIGLOAD ) { atimers[ tnum ].obj_offset = obj_offset; if( IS_ERROR( __atimer_set( tnum, tpoint ) ) ) return EINVAL; return ENOERR; } return ENOSYS; }
bool DriverMinifilterCommunicator::SendSymbolsToDriver(const SymbolList &symbolList) { // allocate symbol array which will be passed to the driver // count of the symbols is checked inside the driver and must be equal to the number of symbols obtained from the driver DWORD dwArraySize = m_driverSymbolCount * sizeof(INTERNAL_SYMBOL); PINTERNAL_SYMBOL pSymbolsArray = (PINTERNAL_SYMBOL) VirtualAlloc(0, dwArraySize, MEM_COMMIT, PAGE_READWRITE); if(pSymbolsArray == NULL) { Logger::Instance().Log(_T("Failed to allocate memory for driver symbols"), ERR); return false; } DWORD symIndex = 0; symIndex = TransformFromSymbolListToArray(symbolList, pSymbolsArray, symIndex, _T("")); // simple error checking - number of transformed items should be the same as the initial array size if(m_driverSymbolCount != symIndex) { Logger::Instance().Log(_T("Number of transformed driver symbols not equal to number of symbols received from the driver!"), WARNING); // do not exit, this is probably a non-fatal error } // format new message (be cautious when setting the required size) ULONG uCommandBlockSize = FIELD_OFFSET(COMMAND_MESSAGE, pData[dwArraySize]); PCOMMAND_MESSAGE pCommandMessage = (PCOMMAND_MESSAGE) VirtualAlloc(0, uCommandBlockSize, MEM_COMMIT, PAGE_READWRITE); if(pCommandMessage == NULL) { Logger::Instance().Log(_T("Failed to allocate memory for port command message block"), ERR); return false; } pCommandMessage->Command = DmfsSaveSymbols; memcpy_s(pCommandMessage->pData, uCommandBlockSize - FIELD_OFFSET(COMMAND_MESSAGE, pData), pSymbolsArray, dwArraySize); // send symbols to driver DWORD dwBytesReturned = 0; if(IS_ERROR(FilterSendMessage( m_driverPort, // communication port pCommandMessage, // command message uCommandBlockSize, // size of command message NULL, // no output array 0, // no output array size &dwBytesReturned // actual size of the array (in bytes) ))) { Logger::Instance().Log(_T("Error sending symbols to driver"), ERR); VirtualFree(pSymbolsArray, 0, MEM_RELEASE); return false; } Logger::Instance().Log(_T("Symbols successfully sent to kernel-mode!"), SUCCESS); VirtualFree(pSymbolsArray, 0, MEM_RELEASE); VirtualFree(pCommandMessage, 0, MEM_RELEASE); return true; }
result_t _atimer_stop( const uint16_t obj_offset, const uint8_t tnum ) { if( ISZIGLOAD ) { if( obj_offset != atimers[ tnum ].obj_offset ) return EACCESS; if( IS_ERROR( __atimer_stop( tnum ) ) ) return EINVAL; return ENOERR; } return ENOSYS; }
DWORD WINAPI wrInitDll(PVOID pParameter) { HRESULT hResult; hResult = AsyncInit(); if (IS_ERROR(hResult)) DbPrint("r3hook::wrInitDll - failed to AsyncInit!\n"); // SetPriorityClass(GetCurrentProcess(), g_InitialPriorityClass); return 0; }
result_t _atimer_info( const uint8_t tnum, struct timerinfo *const info ) { if( 0 == info ) return EINVAL; if( ISZIGLOAD ) { int16_t is_set; if( IS_ERROR( is_set = __atimer_is_set( tnum ) ) ) return EINVAL; info->is_set = is_set; info->tpoint = __atimer_point( tnum ); return ENOERR; } return ENOSYS; }
*/ RL_API int RL_Do_Binary(REBYTE *bin, REBINT length, REBCNT flags, REBCNT key, RXIARG *result) /* ** Evaluate an encoded binary script such as compressed text. ** ** Returns: ** The datatype of the result or zero if error in the encoding. ** Arguments: ** bin - by default, a REBOL compressed UTF-8 (or ASCII) script. ** length - the length of the data. ** flags - special flags (set to zero at this time). ** key - encoding, encryption, or signature key. ** result - value returned from evaluation. ** Notes: ** As of A104, only compressed scripts are supported, however, ** rebin, cloaked, signed, and encrypted formats will be supported. ** ***********************************************************************/ { REBSER spec = {0}; REBSER *text; REBVAL *val; #ifdef DUMP_INIT_SCRIPT int f; #endif //Cloak(TRUE, code, NAT_SPEC_SIZE, &key[0], 20, TRUE); spec.data = bin; spec.tail = length; text = Decompress(&spec, 0, -1, 10000000, 0); if (!text) return FALSE; Append_Byte(text, 0); #ifdef DUMP_INIT_SCRIPT f = _open("host-boot.r", _O_CREAT | _O_RDWR, _S_IREAD | _S_IWRITE ); _write(f, STR_HEAD(text), LEN_BYTES(STR_HEAD(text))); _close(f); #endif SAVE_SERIES(text); val = Do_String(text->data, flags); UNSAVE_SERIES(text); if (IS_ERROR(val)) // && (VAL_ERR_NUM(val) != RE_QUIT)) { Print_Value(val, 1000, FALSE); if (result) { *result = Value_To_RXI(val); return Reb_To_RXT[VAL_TYPE(val)]; } return 0; }
/* Инициализация портов */ void sys_init() { port_attr_t port_attr; /* Настройка выхода на зелёный светодиод */ PIN_SET( port_attr.dir, GREEN_PIN, PIN_HI ); /* Направление на вывод */ PIN_CLEAR( port_attr.sel, GREEN_PIN ); /* Функция ввода/вывода */ port_set_attr( GREEN_PORT, GREEN_PIN, &port_attr ); port_write( GREEN_PORT, GREEN_PIN, PIN_LO ); /* По умолчанию гасим светодиод */ /* Настройка выхода на красный светодиод */ PIN_SET( port_attr.dir, RED_PIN, PIN_HI ); /* Направление на вывод */ PIN_CLEAR( port_attr.sel, RED_PIN ); /* Функция ввода/вывода */ port_set_attr( RED_PORT, RED_PIN, &port_attr ); port_write( RED_PORT, RED_PIN, PIN_LO ); /* По умолчанию гасим светодиод */ /* Настройка входа от геркона */ { port_t gercon_port = 0x00; event_type_t event_type = 0; result_t res = ENOSYS; port_reset_iflag( GERCON_PORT, GERCON_PIN ); PIN_CLEAR( port_attr.dir, GERCON_PIN ); /* Направление на ввод */ PIN_CLEAR( port_attr.sel, GERCON_PIN ); /* Функция ввода/вывода */ PIN_SET( port_attr.ie, GERCON_PIN, PIN_HI ); /* Разрешаем прерывания от кнопки */ PIN_SET( port_attr.ies, GERCON_PIN, PIN_HI ); /* Ловим изменение с высокого на низкий уровень */ port_set_attr( GERCON_PORT, GERCON_PIN, &port_attr ); port_read( GERCON_PORT, GERCON_PIN, &gercon_port ); /* Определение текущего состояния геркона */ if( PIN_IS_SET( gercon_port, GERCON_PIN) ) { event_type = EV_TYPE_OPEN; } else { PIN_SET( port_attr.ies, GERCON_PIN, PIN_LO ); /* Ловим изменение с низкого на высокий уровень */ port_set_attr( GERCON_PORT, GERCON_PIN, &port_attr ); event_type = EV_TYPE_CLOSE; } res = event_emit( PRIORITY_LOW, event_type, 0 ); if( IS_ERROR(res) ) { /* Не смогли начать работу, зажигаем красный светодиод */ port_write( RED_PORT, RED_PIN, PIN_HI ); } } return; }
bool NtlmProxy::NtlmStep1(char* pOutBuffer, int* pOutBufferLen) { memset(pOutBuffer, 0, *pOutBufferLen); if(!m_pFunTable) { return false; } SECURITY_STATUS SecurityStatus = SEC_E_OK; BYTE Buffer[1024]; memset(Buffer,0,1024); SecBuffer sBuffer; sBuffer.cbBuffer = 1024; sBuffer.BufferType = SECBUFFER_TOKEN; sBuffer.pvBuffer = Buffer; SecBufferDesc OutBufferDesc; OutBufferDesc.ulVersion = SECBUFFER_VERSION; OutBufferDesc.cBuffers = 1; OutBufferDesc.pBuffers = &sBuffer; SecurityStatus = m_pFunTable->InitializeSecurityContextA( &m_hCredentials, 0, "NTLM", ISC_REQ_USE_DCE_STYLE | ISC_REQ_DELEGATE | ISC_REQ_MUTUAL_AUTH |ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT |ISC_REQ_CONFIDENTIALITY | ISC_REQ_CONNECTION, 0, 0, 0, 0, &m_SecurityContext, &OutBufferDesc, &m_ulContextAttributes, &m_ts ); if (IS_ERROR(SecurityStatus)) return false; Base64Encode((unsigned char*)sBuffer.pvBuffer, sBuffer.cbBuffer, pOutBuffer, pOutBufferLen, BASE64_FLAG_NOCRLF); return true; }
bool IsoDepTag::startIsoDepTag() { uint8_t rats = listenRATS(); if (rats == 0xFF) { LOGE("RATS(Request for Answer to select) is not received"); return false; } if (ovrImpl != NULL) { ovrImpl->onInitiatorDetected(*this); } else { defaultImpl->onInitiatorDetected(*this); } uint16_t rxresult = 0; while (!IS_ERROR((rxresult = ulhw->tgGetData(rxBuf)))) { IsoApdu::parse(rxBuf, GET_VALUE(rxresult), this); } return true; }
SymbolList DriverMinifilterCommunicator::GetDriverSymbols(void) { SymbolList symbolList; // allocate space for 100 symbols -- will increase it if necessary DWORD dwArraySize = sizeof(INTERNAL_SYMBOL) * 100; COMMAND_MESSAGE command; command.Command = DmfsGetSymbols; // initialize array which will hold private symbols PINTERNAL_SYMBOL pSymbolsArray = (PINTERNAL_SYMBOL) VirtualAlloc(0, dwArraySize, MEM_COMMIT, PAGE_READWRITE); if(pSymbolsArray == NULL) { Logger::Instance().Log(_T("Failed to allocate memory for driver symbols"), ERR); return symbolList; } // get symbol array from the driver DWORD dwReturnedArraySize = 0; if(IS_ERROR(FilterSendMessage( m_driverPort, // communication port &command, // command message specifying the action sizeof(COMMAND_MESSAGE), // size of the message pSymbolsArray, // output array that will hold the symbols from the driver dwArraySize, // size of the output array &dwReturnedArraySize // actual size of the array (in bytes) ))) { Logger::Instance().Log(_T("Error getting symbols from the driver"), ERR); VirtualFree(pSymbolsArray, 0, MEM_RELEASE); return symbolList; } // get number of the symbols returned from the driver m_driverSymbolCount = dwReturnedArraySize / sizeof(INTERNAL_SYMBOL); // put symbols into symbol list which will be passed to SymbolHelper TransformFromArrayToSymbolList(symbolList, pSymbolsArray, m_driverSymbolCount); // release allocated memory VirtualFree(pSymbolsArray, 0, MEM_RELEASE); return symbolList; }