int EventLoopNotifier::NotifyEventLoop( EventLoop* event_loop, NotifyMessage* message) { IODescriptor* descriptor = NULL; if (message->fd == kDescriptorFD) { uint64_t descriptor_id = (uint64_t)message->data; descriptor = IODescriptorFactory::GetIODescriptor(descriptor_id); if (!descriptor) { LOG_ERROR(logger, "EventLoopNotifier::NotifyEventLoop descriptor not found:" << descriptor_id); ADE_DELETE(message); return -1; } } LOG_TRACE(logger, "EventLoopNotifier::NotifyEventLoop" << ", message:" << *message << ", descriptor:" << *descriptor); int ret = 0; switch (message->mask) { case NotifyMessage::ADD_READ: ret = event_loop->AddEvent( descriptor ? descriptor->GetIN() : message->fd, EventType::EV_READ, message->proc, message->data); break; case NotifyMessage::ADD_WRITE: ret = event_loop->AddEvent( descriptor ? descriptor->GetOUT() : message->fd, EventType::EV_WRITE, message->proc, message->data); break; case NotifyMessage::ADD_READ_WRITE: ret = event_loop->AddEvent( descriptor ? descriptor->GetIN() : message->fd, EventType::EV_READ | EventType::EV_WRITE, message->proc, message->data); break; case NotifyMessage::REMOVE_READ: ret = event_loop->RemoveEvent( descriptor ? descriptor->GetIN() : message->fd, EventType::EV_READ); break; case NotifyMessage::REMOVE_WRITE: ret = event_loop->RemoveEvent( descriptor ? descriptor->GetOUT() : message->fd, EventType::EV_WRITE); break; case NotifyMessage::REGISTER_CLOSE: event_loop->FireEvent(descriptor->GetIN(), EventType::EV_CLOSE); break; default: LOG_WARN(logger, "EventLoopNotifier::NotifyEventLoop unknown mask:" << message->mask); break; } ADE_DELETE(message); return ret; }
void SocketServer::run(std::mutex& mutex) { bool alive = true; while (alive) { bool performedRead = false; bool performedWrite = false; { std::lock_guard<std::mutex> m(mutex); alive = m_alive; } if (!alive) break; fd_set reader; fd_set writer; FD_ZERO(&reader); FD_ZERO(&writer); // set server socket FD_SET(m_serverSocket->m_socket, &reader); if(m_serverSocket->m_data.size() > 0) FD_SET(m_serverSocket->m_socket, &writer); // set client sockets for (auto&& sock : m_clients) { FD_SET(sock.socket->m_socket, &reader); if(sock.socket->m_data.size() > 0) //if (sock->hasData()) FD_SET(sock.socket->m_socket, &writer); } timeval time; time.tv_sec = 0; time.tv_usec = 1000; // 500 ms auto changedSockets = select(0, &reader, &writer, nullptr, &time); if (changedSockets == SOCKET_ERROR) LOG_ERROR("Socket select failed"); // check for new connections if (FD_ISSET(m_serverSocket->m_socket, &reader)) { if(!m_broadcasting) { // new connection LOG_WARNING("SocketServer got a new connection"); m_clients.emplace_back(ClientContainer{ std::make_shared<PrefixLengthMessageParser>(m_onData), std::shared_ptr<Socket>( new Socket(accept(m_serverSocket->m_socket, 0, 0)), [](Socket* ptr) { if(ptr->m_socket != INVALID_SOCKET) { closesocket(ptr->m_socket); } delete ptr; })}); SocketServer::ClientContainer& client = m_clients.back(); if (client.socket->m_socket == INVALID_SOCKET) { LOG_ERROR("Client socket failed"); m_clients.pop_back(); } else { client.parser->setSocket(client.socket); client.socket->enableSocketReuse(); client.socket->enableNoDelay(); client.socket->enableNonBlockingSocket(); if (m_onConnect) m_onConnect(client.socket); } } else { auto dataSize = m_serverSocket->dataAvailableInSocket(); if (dataSize > 0) { //LOG_INFO("got data: %i", static_cast<int>(dataSize)); std::vector<char> buffer(dataSize); auto readBytes = m_serverSocket->read(&buffer[0], dataSize); m_serverSocketParser.onData(m_serverSocket, &buffer[0], readBytes); performedRead = true; //client.parser->onData(client.socket, &buffer[0], readBytes); } } } // perform client reads/writes std::vector<ClientContainer> remove; for (auto&& client : m_clients) { if (FD_ISSET(client.socket->m_socket, &reader)) { size_t bytesRead = 0; auto dataSize = client.socket->dataAvailableInSocket(); std::vector<char> buffer(dataSize); while(bytesRead < dataSize) { //LOG_INFO("got data: %i", static_cast<int>(dataSize)); bytesRead += client.socket->read(&buffer[bytesRead], dataSize - bytesRead); performedRead = true; } ASSERT(bytesRead == dataSize, "Something went bad"); if(bytesRead > 0) client.parser->onData(client.socket, &buffer[0], bytesRead); if(dataSize == 0) { //LOG_INFO("got 0 packet"); // client disconnected remove.emplace_back(client); } } if (FD_ISSET(client.socket->m_socket, &writer)) { if(client.socket->private_write() > 0) performedWrite = true; } } /*while (remove.size() > 0) { auto sock = remove.back(); if (m_onDisconnect) m_onDisconnect(sock.socket); remove.pop_back(); for (auto iter = m_clients.begin(); iter != m_clients.end(); ++iter) { if ((*iter).socket == sock.socket) { m_clients.erase(iter); break; } } }*/ if (!performedRead && !performedWrite) { std::this_thread::sleep_for(std::chrono::milliseconds(200)); } } }
void PluginDatabase::loadPersistentMetadataCache() { if (!isPersistentMetadataCacheEnabled() || persistentMetadataCachePath().isEmpty()) return; PlatformFileHandle file; String absoluteCachePath = pathByAppendingComponent(persistentMetadataCachePath(), persistentPluginMetadataCacheFilename); file = openFile(absoluteCachePath, OpenForRead); if (!isHandleValid(file)) return; // Mark cache as loaded regardless of success or failure. If // there's error in the cache, we won't try to load it anymore. m_persistentMetadataCacheIsLoaded = true; Vector<char> fileContents; fillBufferWithContentsOfFile(file, fileContents); closeFile(file); if (fileContents.size() < 2 || fileContents.first() != schemaVersion || fileContents.last() != '\0') { LOG_ERROR("Unable to read plugin metadata cache: corrupt schema"); deleteFile(absoluteCachePath); return; } char* bufferPos = fileContents.data() + 1; char* end = fileContents.data() + fileContents.size(); PluginSet cachedPlugins; HashMap<String, time_t> cachedPluginPathsWithTimes; HashMap<String, RefPtr<PluginPackage> > cachedPluginsByPath; while (bufferPos < end) { String path; time_t lastModified; String name; String desc; String mimeDesc; if (!(readUTF8String(path, bufferPos, end) && readTime(lastModified, bufferPos, end) && readUTF8String(name, bufferPos, end) && readUTF8String(desc, bufferPos, end) && readUTF8String(mimeDesc, bufferPos, end))) { LOG_ERROR("Unable to read plugin metadata cache: corrupt data"); deleteFile(absoluteCachePath); return; } // Skip metadata that points to plugins from directories that // are not part of plugin directory list anymore. String pluginDirectoryName = directoryName(path); if (m_pluginDirectories.find(pluginDirectoryName) == WTF::notFound) continue; RefPtr<PluginPackage> package = PluginPackage::createPackageFromCache(path, lastModified, name, desc, mimeDesc); if (package && cachedPlugins.add(package).isNewEntry) { cachedPluginPathsWithTimes.add(package->path(), package->lastModified()); cachedPluginsByPath.add(package->path(), package); } } m_plugins.swap(cachedPlugins); m_pluginsByPath.swap(cachedPluginsByPath); m_pluginPathsWithTimes.swap(cachedPluginPathsWithTimes); }
bool Shader::addShader(const std::string& shader, UI32 type) { const char* shaderSrc = shader.c_str(); bool success = false; UI32 shaderHandle = 0; switch (type) { case ODIN_VERTEX_SHADER: shaderHandle = render::lib::createShader(ODIN_VERTEX_SHADER); render::lib::shaderSource(shaderHandle, 1, &shaderSrc, nullptr); render::lib::compileShader(shaderHandle); success = checkCompileErrors(shaderHandle, "VERTEX"); break; case ODIN_FRAGMENT_SHADER: shaderHandle = render::lib::createShader(ODIN_FRAGMENT_SHADER); render::lib::shaderSource(shaderHandle, 1, &shaderSrc, nullptr); render::lib::compileShader(shaderHandle); success = checkCompileErrors(shaderHandle, "FRAGMENT"); break; case ODIN_GEOMETRY_SHADER: shaderHandle = render::lib::createShader(ODIN_GEOMETRY_SHADER); render::lib::shaderSource(shaderHandle, 1, &shaderSrc, nullptr); render::lib::compileShader(shaderHandle); success = checkCompileErrors(shaderHandle, "GEOMETRY"); break; case ODIN_TESS_CONTROL_SHADER: shaderHandle =render::lib::createShader(ODIN_TESS_CONTROL_SHADER); render::lib::shaderSource(shaderHandle, 1, &shaderSrc, nullptr); render::lib::compileShader(shaderHandle); success = checkCompileErrors(shaderHandle, "TESSELATION_CONTROL"); break; case ODIN_TESS_EVALUATION_SHADER: shaderHandle = render::lib::createShader(ODIN_TESS_EVALUATION_SHADER); render::lib::shaderSource(shaderHandle, 1, &shaderSrc, nullptr); render::lib::compileShader(shaderHandle); success = checkCompileErrors(shaderHandle, "TESSELATION_EVALUATION"); break; #if defined ODIN_COMPUTE_SHADER case ODIN_COMPUTE_SHADER: shaderHandle = render::lib::createShader(ODIN_COMPUTE_SHADER); render::lib::shaderSource(shaderHandle, 1, &shaderSrc, nullptr); render::lib::compileShader(shaderHandle); success = checkCompileErrors(shaderHandle, "COMPUTE"); break; #endif default: LOG_ERROR("Unsupported shader type"); return false; } if (success) { render::lib::attachShader(m_program, shaderHandle); render::lib::deleteShader(shaderHandle); } else { render::lib::deleteShader(shaderHandle); render::lib::deleteProgram(m_program); m_program = 0; } return success; }
static int stmsmi_write(struct flash_bank *bank, uint8_t *buffer, uint32_t offset, uint32_t count) { struct target *target = bank->target; struct stmsmi_flash_bank *stmsmi_info = bank->driver_priv; uint32_t io_base = stmsmi_info->io_base; uint32_t cur_count, page_size, page_offset; int sector; int retval = ERROR_OK; LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32, __FUNCTION__, offset, count); if (target->state != TARGET_HALTED) { LOG_ERROR("Target not halted"); return ERROR_TARGET_NOT_HALTED; } if (offset + count > stmsmi_info->dev->size_in_bytes) { LOG_WARNING("Write pasts end of flash. Extra data discarded."); count = stmsmi_info->dev->size_in_bytes - offset; } /* Check sector protection */ for (sector = 0; sector < bank->num_sectors; sector++) { /* Start offset in or before this sector? */ /* End offset in or behind this sector? */ if ( (offset < (bank->sectors[sector].offset + bank->sectors[sector].size)) && ((offset + count - 1) >= bank->sectors[sector].offset) && bank->sectors[sector].is_protected ) { LOG_ERROR("Flash sector %d protected", sector); return ERROR_FAIL; } } page_size = stmsmi_info->dev->pagesize; /* unaligned buffer head */ if (count > 0 && (offset & 3) != 0) { cur_count = 4 - (offset & 3); if (cur_count > count) cur_count = count; retval = smi_write_buffer(bank, buffer, bank->base + offset, cur_count); if (retval != ERROR_OK) goto err; offset += cur_count; buffer += cur_count; count -= cur_count; } page_offset = offset % page_size; /* central part, aligned words */ while (count >= 4) { /* clip block at page boundary */ if (page_offset + count > page_size) cur_count = page_size - page_offset; else cur_count = count & ~3; retval = smi_write_buffer(bank, buffer, bank->base + offset, cur_count); if (retval != ERROR_OK) goto err; page_offset = 0; buffer += cur_count; offset += cur_count; count -= cur_count; keep_alive(); } /* buffer tail */ if (count > 0) retval = smi_write_buffer(bank, buffer, bank->base + offset, count); err: /* Switch to HW mode before return to prompt */ SMI_SET_HW_MODE(); return retval; }
/* * no_increment - in the future we may want to be able * to read/write a range of data to a "port". a "port" is an action on * read memory address for some peripheral. */ static int arm11_write_memory_inner(struct target *target, uint32_t address, uint32_t size, uint32_t count, uint8_t *buffer, bool no_increment) { int retval; if (target->state != TARGET_HALTED) { LOG_WARNING("target was not halted"); return ERROR_TARGET_NOT_HALTED; } LOG_DEBUG("ADDR %08" PRIx32 " SIZE %08" PRIx32 " COUNT %08" PRIx32 "", address, size, count); struct arm11_common *arm11 = target_to_arm11(target); retval = arm11_run_instr_data_prepare(arm11); if (retval != ERROR_OK) return retval; /* load r0 with buffer address */ /* MRC p14,0,r0,c0,c5,0 */ retval = arm11_run_instr_data_to_core1(arm11, 0xee100e15, address); if (retval != ERROR_OK) return retval; /* burst writes are not used for single words as those may well be * reset init script writes. * * The other advantage is that as burst writes are default, we'll * now exercise both burst and non-burst code paths with the * default settings, increasing code coverage. */ bool burst = arm11_config_memwrite_burst && (count > 1); switch (size) { case 1: { arm11->arm.core_cache->reg_list[1].dirty = true; for (size_t i = 0; i < count; i++) { /* load r1 from DCC with byte data */ /* MRC p14,0,r1,c0,c5,0 */ retval = arm11_run_instr_data_to_core1(arm11, 0xee101e15, *buffer++); if (retval != ERROR_OK) return retval; /* write r1 to memory */ /* strb r1, [r0], #1 */ /* strb r1, [r0] */ retval = arm11_run_instr_no_data1(arm11, !no_increment ? 0xe4c01001 : 0xe5c01000); if (retval != ERROR_OK) return retval; } break; } case 2: { arm11->arm.core_cache->reg_list[1].dirty = true; for (size_t i = 0; i < count; i++) { uint16_t value; memcpy(&value, buffer + i * sizeof(uint16_t), sizeof(uint16_t)); /* load r1 from DCC with halfword data */ /* MRC p14,0,r1,c0,c5,0 */ retval = arm11_run_instr_data_to_core1(arm11, 0xee101e15, value); if (retval != ERROR_OK) return retval; /* write r1 to memory */ /* strh r1, [r0], #2 */ /* strh r1, [r0] */ retval = arm11_run_instr_no_data1(arm11, !no_increment ? 0xe0c010b2 : 0xe1c010b0); if (retval != ERROR_OK) return retval; } break; } case 4: { /* stream word data through DCC directly to memory */ /* increment: STC p14,c5,[R0],#4 */ /* no increment: STC p14,c5,[R0]*/ uint32_t instr = !no_increment ? 0xeca05e01 : 0xed805e00; /** \todo TODO: buffer cast to uint32_t* causes alignment warnings */ uint32_t *words = (uint32_t*)buffer; /* "burst" here just means trusting each instruction executes * fully before we run the next one: per-word roundtrips, to * check the Ready flag, are not used. */ if (!burst) retval = arm11_run_instr_data_to_core(arm11, instr, words, count); else retval = arm11_run_instr_data_to_core_noack(arm11, instr, words, count); if (retval != ERROR_OK) return retval; break; } } /* r0 verification */ if (!no_increment) { uint32_t r0; /* MCR p14,0,R0,c0,c5,0 */ retval = arm11_run_instr_data_from_core(arm11, 0xEE000E15, &r0, 1); if (retval != ERROR_OK) return retval; if (address + size * count != r0) { LOG_ERROR("Data transfer failed. Expected end " "address 0x%08x, got 0x%08x", (unsigned) (address + size * count), (unsigned) r0); if (burst) LOG_ERROR("use 'arm11 memwrite burst disable' to disable fast burst mode"); if (arm11_config_memwrite_error_fatal) return ERROR_FAIL; } } return arm11_run_instr_data_finish(arm11); }
int adaptor_init(zhandle_t *zh) { pthread_mutexattr_t recursive_mx_attr; struct adaptor_threads *adaptor_threads = calloc(1, sizeof(*adaptor_threads)); if (!adaptor_threads) { LOG_ERROR(("Out of memory")); return -1; } /* We use a pipe for interrupting select() in unix/sol and socketpair in windows. */ #ifdef WIN32 if (create_socket_pair(adaptor_threads->self_pipe) == -1){ LOG_ERROR(("Can't make a socket.")); #else if(pipe(adaptor_threads->self_pipe)==-1) { LOG_ERROR(("Can't make a pipe %d",errno)); #endif free(adaptor_threads); return -1; } set_nonblock(adaptor_threads->self_pipe[1]); set_nonblock(adaptor_threads->self_pipe[0]); pthread_mutex_init(&zh->auth_h.lock,0); zh->adaptor_priv = adaptor_threads; pthread_mutex_init(&zh->to_process.lock,0); pthread_mutex_init(&adaptor_threads->zh_lock,0); // to_send must be recursive mutex pthread_mutexattr_init(&recursive_mx_attr); pthread_mutexattr_settype(&recursive_mx_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&zh->to_send.lock,&recursive_mx_attr); pthread_mutexattr_destroy(&recursive_mx_attr); pthread_mutex_init(&zh->sent_requests.lock,0); pthread_cond_init(&zh->sent_requests.cond,0); pthread_mutex_init(&zh->completions_to_process.lock,0); pthread_cond_init(&zh->completions_to_process.cond,0); start_threads(zh); return 0; } void adaptor_finish(zhandle_t *zh) { struct adaptor_threads *adaptor_threads; // make sure zh doesn't get destroyed until after we're done here api_prolog(zh); adaptor_threads = zh->adaptor_priv; if(adaptor_threads==0) { api_epilog(zh,0); return; } if(!pthread_equal(adaptor_threads->io,pthread_self())){ wakeup_io_thread(zh); pthread_join(adaptor_threads->io, 0); }else pthread_detach(adaptor_threads->io); if(!pthread_equal(adaptor_threads->completion,pthread_self())){ pthread_mutex_lock(&zh->completions_to_process.lock); pthread_cond_broadcast(&zh->completions_to_process.cond); pthread_mutex_unlock(&zh->completions_to_process.lock); pthread_join(adaptor_threads->completion, 0); }else pthread_detach(adaptor_threads->completion); api_epilog(zh,0); } void adaptor_destroy(zhandle_t *zh) { struct adaptor_threads *adaptor = zh->adaptor_priv; if(adaptor==0) return; pthread_cond_destroy(&adaptor->cond); pthread_mutex_destroy(&adaptor->lock); pthread_mutex_destroy(&zh->to_process.lock); pthread_mutex_destroy(&zh->to_send.lock); pthread_mutex_destroy(&zh->sent_requests.lock); pthread_cond_destroy(&zh->sent_requests.cond); pthread_mutex_destroy(&zh->completions_to_process.lock); pthread_cond_destroy(&zh->completions_to_process.cond); pthread_mutex_destroy(&adaptor->zh_lock); pthread_mutex_destroy(&zh->auth_h.lock); close(adaptor->self_pipe[0]); close(adaptor->self_pipe[1]); free(adaptor); zh->adaptor_priv=0; } int wakeup_io_thread(zhandle_t *zh) { struct adaptor_threads *adaptor_threads = zh->adaptor_priv; char c=0; #ifndef WIN32 return write(adaptor_threads->self_pipe[1],&c,1)==1? ZOK: ZSYSTEMERROR; #else return send(adaptor_threads->self_pipe[1], &c, 1, 0)==1? ZOK: ZSYSTEMERROR; #endif } int adaptor_send_queue(zhandle_t *zh, int timeout) { if(!zh->close_requested) return wakeup_io_thread(zh); // don't rely on the IO thread to send the messages if the app has // requested to close return flush_send_queue(zh, timeout); } /* These two are declared here because we will run the event loop * and not the client */ #ifdef WIN32 int zookeeper_interest(zhandle_t *zh, SOCKET *fd, int *interest, struct timeval *tv); #else int zookeeper_interest(zhandle_t *zh, int *fd, int *interest, struct timeval *tv); #endif int zookeeper_process(zhandle_t *zh, int events); #ifdef WIN32 unsigned __stdcall do_io( void * v) #else void *do_io(void *v) #endif { zhandle_t *zh = (zhandle_t*)v; #ifndef WIN32 struct pollfd fds[2]; struct adaptor_threads *adaptor_threads = zh->adaptor_priv; api_prolog(zh); notify_thread_ready(zh); LOG_DEBUG(("started IO thread")); fds[0].fd=adaptor_threads->self_pipe[0]; fds[0].events=POLLIN; while(!zh->close_requested) { struct timeval tv; int fd; int interest; int timeout; int maxfd=1; int rc; zookeeper_interest(zh, &fd, &interest, &tv); if (fd != -1) { fds[1].fd=fd; fds[1].events=(interest&ZOOKEEPER_READ)?POLLIN:0; fds[1].events|=(interest&ZOOKEEPER_WRITE)?POLLOUT:0; maxfd=2; } timeout=tv.tv_sec * 1000 + (tv.tv_usec/1000); poll(fds,maxfd,timeout); if (fd != -1) { interest=(fds[1].revents&POLLIN)?ZOOKEEPER_READ:0; interest|=((fds[1].revents&POLLOUT)||(fds[1].revents&POLLHUP))?ZOOKEEPER_WRITE:0; } if(fds[0].revents&POLLIN){ // flush the pipe char b[128]; while(read(adaptor_threads->self_pipe[0],b,sizeof(b))==sizeof(b)){} } #else fd_set rfds, wfds, efds; struct adaptor_threads *adaptor_threads = zh->adaptor_priv; api_prolog(zh); notify_thread_ready(zh); LOG_DEBUG(("started IO thread")); FD_ZERO(&rfds); FD_ZERO(&wfds); FD_ZERO(&efds); while(!zh->close_requested) { struct timeval tv; SOCKET fd; SOCKET maxfd=adaptor_threads->self_pipe[0]; int interest; int rc; zookeeper_interest(zh, &fd, &interest, &tv); if (fd != -1) { if (interest&ZOOKEEPER_READ) { FD_SET(fd, &rfds); } else { FD_CLR(fd, &rfds); } if (interest&ZOOKEEPER_WRITE) { FD_SET(fd, &wfds); } else { FD_CLR(fd, &wfds); } } FD_SET( adaptor_threads->self_pipe[0] ,&rfds ); rc = select((int)maxfd, &rfds, &wfds, &efds, &tv); if (fd != -1) { interest = (FD_ISSET(fd, &rfds))? ZOOKEEPER_READ:0; interest|= (FD_ISSET(fd, &wfds))? ZOOKEEPER_WRITE:0; } if (FD_ISSET(adaptor_threads->self_pipe[0], &rfds)){ // flush the pipe/socket char b[128]; while(recv(adaptor_threads->self_pipe[0],b,sizeof(b), 0)==sizeof(b)){} } #endif // dispatch zookeeper events rc = zookeeper_process(zh, interest); // check the current state of the zhandle and terminate // if it is_unrecoverable() if(is_unrecoverable(zh)) break; } api_epilog(zh, 0); LOG_DEBUG(("IO thread terminated")); return 0; } #ifdef WIN32 unsigned __stdcall do_completion( void * v) #else void *do_completion(void *v) #endif { zhandle_t *zh = v; api_prolog(zh); notify_thread_ready(zh); LOG_DEBUG(("started completion thread")); while(!zh->close_requested) { pthread_mutex_lock(&zh->completions_to_process.lock); while(!zh->completions_to_process.head && !zh->close_requested) { pthread_cond_wait(&zh->completions_to_process.cond, &zh->completions_to_process.lock); } pthread_mutex_unlock(&zh->completions_to_process.lock); process_completions(zh); } api_epilog(zh, 0); LOG_DEBUG(("completion thread terminated")); return 0; }
OSStatus TextCodecMac::decode(const unsigned char* inputBuffer, int inputBufferLength, int& inputLength, void *outputBuffer, int outputBufferLength, int& outputLength) { OSStatus status; unsigned long bytesRead = 0; unsigned long bytesWritten = 0; if (m_numBufferedBytes != 0) { // Finish converting a partial character that's in our buffer. // First, fill the partial character buffer with as many bytes as are available. ASSERT(m_numBufferedBytes < sizeof(m_bufferedBytes)); const int spaceInBuffer = sizeof(m_bufferedBytes) - m_numBufferedBytes; const int bytesToPutInBuffer = MIN(spaceInBuffer, inputBufferLength); ASSERT(bytesToPutInBuffer != 0); memcpy(m_bufferedBytes + m_numBufferedBytes, inputBuffer, bytesToPutInBuffer); // Now, do a conversion on the buffer. status = TECConvertText(m_converterTEC, m_bufferedBytes, m_numBufferedBytes + bytesToPutInBuffer, &bytesRead, reinterpret_cast<unsigned char*>(outputBuffer), outputBufferLength, &bytesWritten); ASSERT(bytesRead <= m_numBufferedBytes + bytesToPutInBuffer); if (status == kTECPartialCharErr && bytesRead == 0) { // Handle the case where the partial character was not converted. if (bytesToPutInBuffer >= spaceInBuffer) { LOG_ERROR("TECConvertText gave a kTECPartialCharErr but read none of the %zu bytes in the buffer", sizeof(m_bufferedBytes)); m_numBufferedBytes = 0; status = kTECUnmappableElementErr; // should never happen, but use this error code } else { // Tell the caller we read all the source bytes and keep them in the buffer. m_numBufferedBytes += bytesToPutInBuffer; bytesRead = bytesToPutInBuffer; status = noErr; } } else { // We are done with the partial character buffer. // Also, we have read some of the bytes from the main buffer. if (bytesRead > m_numBufferedBytes) { bytesRead -= m_numBufferedBytes; } else { LOG_ERROR("TECConvertText accepted some bytes it previously rejected with kTECPartialCharErr"); bytesRead = 0; } m_numBufferedBytes = 0; if (status == kTECPartialCharErr) { // While there may be a partial character problem in the small buffer, // we have to try again and not get confused and think there is a partial // character problem in the large buffer. status = noErr; } } } else { status = TECConvertText(m_converterTEC, inputBuffer, inputBufferLength, &bytesRead, static_cast<unsigned char*>(outputBuffer), outputBufferLength, &bytesWritten); ASSERT(static_cast<int>(bytesRead) <= inputBufferLength); } // Work around bug 3351093, where sometimes we get kTECBufferBelowMinimumSizeErr instead of kTECOutputBufferFullStatus. if (status == kTECBufferBelowMinimumSizeErr && bytesWritten != 0) status = kTECOutputBufferFullStatus; inputLength = bytesRead; outputLength = bytesWritten; return status; }
String TextCodecMac::decode(const char* bytes, size_t length, bool flush, bool stopOnError, bool& sawError) { // Get a converter for the passed-in encoding. if (!m_converterTEC && createTECConverter() != noErr) return String(); Vector<UChar> result; const unsigned char* sourcePointer = reinterpret_cast<const unsigned char*>(bytes); int sourceLength = length; bool bufferWasFull = false; UniChar buffer[ConversionBufferSize]; while ((sourceLength || bufferWasFull) && !sawError) { int bytesRead = 0; int bytesWritten = 0; OSStatus status = decode(sourcePointer, sourceLength, bytesRead, buffer, sizeof(buffer), bytesWritten); ASSERT(bytesRead <= sourceLength); sourcePointer += bytesRead; sourceLength -= bytesRead; switch (status) { case noErr: case kTECOutputBufferFullStatus: break; case kTextMalformedInputErr: case kTextUndefinedElementErr: // FIXME: Put FFFD character into the output string in this case? TECClearConverterContextInfo(m_converterTEC); if (stopOnError) { sawError = true; break; } if (sourceLength) { sourcePointer += 1; sourceLength -= 1; } break; case kTECPartialCharErr: { // Put the partial character into the buffer. ASSERT(m_numBufferedBytes == 0); const int bufferSize = sizeof(m_numBufferedBytes); if (sourceLength < bufferSize) { memcpy(m_bufferedBytes, sourcePointer, sourceLength); m_numBufferedBytes = sourceLength; } else { LOG_ERROR("TECConvertText gave a kTECPartialCharErr, but left %u bytes in the buffer", sourceLength); } sourceLength = 0; break; } default: sawError = true; return String(); } ASSERT(!(bytesWritten % sizeof(UChar))); result.append(buffer, bytesWritten / sizeof(UChar)); bufferWasFull = status == kTECOutputBufferFullStatus; } if (flush) { unsigned long bytesWritten = 0; TECFlushText(m_converterTEC, reinterpret_cast<unsigned char*>(buffer), sizeof(buffer), &bytesWritten); ASSERT(!(bytesWritten % sizeof(UChar))); result.append(buffer, bytesWritten / sizeof(UChar)); } String resultString = String::adopt(result); // <rdar://problem/3225472> // Simplified Chinese pages use the code A3A0 to mean "full-width space". // But GB18030 decodes it to U+E5E5, which is correct in theory but not in practice. // To work around, just change all occurences of U+E5E5 to U+3000 (ideographic space). if (m_encoding == kCFStringEncodingGB_18030_2000) resultString.replace(0xE5E5, ideographicSpace); return resultString; }
/** Enable processing on a port */ static MMAL_STATUS_T mmal_vc_port_enable(MMAL_PORT_T *port, MMAL_PORT_BH_CB_T cb) { MMAL_PORT_MODULE_T *module = port->priv->module; MMAL_STATUS_T status; mmal_worker_reply reply; mmal_worker_port_action msg; size_t replylen = sizeof(reply); MMAL_PARAM_UNUSED(cb); if (!port->component->priv->module->event_ctx_initialised) { MMAL_POOL_T *pool = port->component->priv->event_pool; MMAL_DRIVER_BUFFER_T *drv; unsigned int i; /* We need to associate our vc client context to all our event buffers. * This only needs to be done when the first port is enabled because no event * can be received on disabled ports. */ for (i = 0; i < pool->headers_num; i++) { drv = mmal_buffer_header_driver_data(pool->header[i]); drv->client_context = &port->component->priv->module->event_ctx; drv->magic = MMAL_MAGIC; } port->component->priv->module->event_ctx_initialised = MMAL_TRUE; } if (!module->connected) { if (vcos_blockpool_create_on_heap(&module->pool, port->buffer_num, sizeof(MMAL_VC_CLIENT_BUFFER_CONTEXT_T), VCOS_BLOCKPOOL_ALIGN_DEFAULT, VCOS_BLOCKPOOL_FLAG_NONE, "mmal vc port pool") != VCOS_SUCCESS) { LOG_ERROR("failed to create port pool"); return MMAL_ENOMEM; } module->has_pool = 1; } if (module->connected) { /* The connected port won't be enabled explicitly so make sure we apply * the buffer requirements now. */ status = mmal_vc_port_requirements_set(module->connected); if (status != MMAL_SUCCESS) goto error; } msg.component_handle = module->component_handle; msg.action = MMAL_WORKER_PORT_ACTION_ENABLE; msg.port_handle = module->port_handle; msg.param.enable.port = *port; status = mmal_vc_sendwait_message(mmal_vc_get_client(), &msg.header, sizeof(msg), MMAL_WORKER_PORT_ACTION, &reply, &replylen, MMAL_FALSE); if (status == MMAL_SUCCESS) { vcos_assert(replylen == sizeof(reply)); status = reply.status; } if (status != MMAL_SUCCESS) { LOG_ERROR("failed to enable port %s: %s", port->name, mmal_status_to_string(status)); goto error; } if (module->connected) mmal_vc_port_info_get(module->connected); return MMAL_SUCCESS; error: if (module->has_pool) vcos_blockpool_delete(&module->pool); return status; }
static int swddp_transaction_endcheck(struct adiv5_dap *dap) { int retval; uint32_t ctrlstat; /* too expensive to call keep_alive() here */ /* Here be dragons! * * It is easy to be in a JTAG clock range where the target * is not operating in a stable fashion. This happens * for a few reasons: * * - the user may construct a simple test case to try to see * if a higher JTAG clock works to eke out more performance. * This simple case may pass, but more complex situations can * fail. * * - The mostly works JTAG clock rate and the complete failure * JTAG clock rate may be as much as 2-4x apart. This seems * to be especially true on RC oscillator driven parts. * * So: even if calling adi_jtag_scan_inout_check_u32() multiple * times here seems to "make things better here", it is just * hiding problems with too high a JTAG clock. * * Note that even if some parts have RCLK/RTCK, that doesn't * mean that RCLK/RTCK is the *correct* rate to run the JTAG * interface at, i.e. RCLK/RTCK rates can be "too high", especially * before the RC oscillator phase is not yet complete. */ /* Post CTRL/STAT read; discard any previous posted read value * but collect its ACK status. */ retval = adi_swd_scan_inout_check_u32(dap, SWD_DP_DPACC, DP_CTRL_STAT, DPAP_READ, 0, &ctrlstat); if (retval != ERROR_OK) return retval; retval = jtag_execute_queue(); if (retval != ERROR_OK) return retval; dap->ack = dap->ack & 0x7; /* common code path avoids calling timeval_ms() */ if (dap->ack != SWD_ACK_OK) { long long then = timeval_ms(); while (dap->ack != SWD_ACK_OK) { if (dap->ack == SWD_ACK_WAIT) { if ((timeval_ms()-then) > 1000) { /* NOTE: this would be a good spot * to use JTAG_DP_ABORT. */ LOG_WARNING("Timeout (1000ms) waiting " "for ACK=OK/FAULT " "in swd-DP transaction"); return ERROR_JTAG_DEVICE_ERROR; } } else { LOG_WARNING("Invalid ACK %#x " "in swd-DP transaction", dap->ack); return ERROR_JTAG_DEVICE_ERROR; } retval = adi_swd_scan_inout_check_u32(dap, SWD_DP_DPACC, DP_CTRL_STAT, DPAP_READ, 0, &ctrlstat); if (retval != ERROR_OK) return retval; retval = dap_run(dap); if (retval != ERROR_OK) return retval; dap->ack = dap->ack & 0x7; } } /* REVISIT also STICKYCMP, for pushed comparisons (nyet used) */ /* Check for STICKYERR and STICKYORUN */ if (ctrlstat & (SSTICKYORUN | SSTICKYERR)) { LOG_DEBUG("swd-dp: CTRL/STAT error, 0x%" PRIx32, ctrlstat); /* Check power to debug regions */ if ((ctrlstat & 0xf0000000) != 0xf0000000) { retval = ahbap_debugport_init(dap); if (retval != ERROR_OK) return retval; } else { uint32_t mem_ap_csw, mem_ap_tar; /* Maybe print information about last intended * MEM-AP access; but not if autoincrementing. * *Real* CSW and TAR values are always shown. */ if (dap->ap_tar_value != (uint32_t) -1) LOG_DEBUG("MEM-AP Cached values: " "ap_bank 0x%" PRIx32 ", ap_csw 0x%" PRIx32 ", ap_tar 0x%" PRIx32, dap->ap_bank_value, dap->ap_csw_value, dap->ap_tar_value); if (ctrlstat & SSTICKYORUN) LOG_ERROR("SWD-DP OVERRUN - check clock, " "memaccess, or reduce swd speed"); if (ctrlstat & SSTICKYERR) LOG_ERROR("SWD-DP STICKY ERROR"); /* Clear Sticky Error Bits */ // DIFF retval = adi_swd_scan_inout_check_u32(dap, SWD_DP_DPACC, DP_ABORT, DPAP_WRITE, dap->dp_ctrl_stat | ORUNERRCLR | STKERRCLR, NULL); if (retval != ERROR_OK) return retval; retval = adi_swd_scan_inout_check_u32(dap, SWD_DP_DPACC, DP_CTRL_STAT, DPAP_READ, 0, &ctrlstat); if (retval != ERROR_OK) return retval; retval = dap_run(dap); if (retval != ERROR_OK) return retval; LOG_DEBUG("swd-dp: CTRL/STAT 0x%" PRIx32, ctrlstat); retval = dap_queue_ap_read(dap, AP_REG_CSW, &mem_ap_csw); if (retval != ERROR_OK) return retval; retval = dap_queue_ap_read(dap, AP_REG_TAR, &mem_ap_tar); if (retval != ERROR_OK) return retval; retval = dap_run(dap); if (retval != ERROR_OK) return retval; LOG_ERROR("MEM_AP_CSW 0x%" PRIx32 ", MEM_AP_TAR 0x%" PRIx32, mem_ap_csw, mem_ap_tar); } retval = dap_run(dap); if (retval != ERROR_OK) return retval; return ERROR_JTAG_DEVICE_ERROR; } return ERROR_OK; }
bool CHttpDownloader::download(std::list<IDownload*>& download) { std::list<IDownload*>::iterator it; std::vector <DownloadData*> downloads; CURLM* curlm=curl_multi_init(); for(it=download.begin(); it!=download.end(); ++it) { const int count=std::min(MAX_PARALLEL_DOWNLOADS, std::max(1, std::min((int)(*it)->pieces.size(), (*it)->getMirrorCount()))); //count of parallel downloads if((*it)->getMirrorCount()<=0) { LOG_ERROR("No mirrors found"); return false; } LOG_DEBUG("Using %d parallel downloads", count); CFile* file=new CFile(); if(!file->Open((*it)->name, (*it)->size, (*it)->piecesize)) { delete file; return false; } (*it)->file = file; for(int i=0; i<count; i++) { DownloadData* dlData=new DownloadData(); dlData->download=*it; if (!setupDownload(dlData)) { //no piece found (all pieces already downloaded), skip delete dlData; if ((*it)->state!=IDownload::STATE_FINISHED) { LOG_ERROR("no piece found"); return false; } } else { downloads.push_back(dlData); curl_multi_add_handle(curlm, dlData->easy_handle); } } } bool aborted=false; int running=1, last=-1; while((running>0)&&(!aborted)) { CURLMcode ret = CURLM_CALL_MULTI_PERFORM; while(ret == CURLM_CALL_MULTI_PERFORM) { ret=curl_multi_perform(curlm, &running); } if ( ret == CURLM_OK ) { // showProcess(download, file); if (last!=running) { //count of running downloads changed aborted=processMessages(curlm, downloads); last=running++; } } else { LOG_ERROR("curl_multi_perform_error: %d", ret); aborted=true; } fd_set rSet; fd_set wSet; fd_set eSet; FD_ZERO(&rSet); FD_ZERO(&wSet); FD_ZERO(&eSet); int count=0; struct timeval t; t.tv_sec = 1; t.tv_usec = 0; curl_multi_fdset(curlm, &rSet, &wSet, &eSet, &count); //sleep for one sec / until something happened select(count+1, &rSet, &wSet, &eSet, &t); } if (!aborted) { // if download didn't fail, get file size reported in http-header double size=-1; for (unsigned i=0; i<downloads.size(); i++) { double tmp; curl_easy_getinfo(downloads[i]->easy_handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &tmp); if (tmp>size) { size=tmp; } } //set download size if isn't set and we have a valid number // if ((size>0) && (download->size<0)) { // download->size = size; // } } // showProcess(download, file); LOG("\n"); if (!aborted) { LOG_DEBUG("download complete"); } //close all open files for(it=download.begin(); it!=download.end(); ++it) { if ((*it)->file!=NULL) (*it)->file->Close(); } for (unsigned i=0; i<downloads.size(); i++) { long timestamp; if (curl_easy_getinfo(downloads[i]->easy_handle, CURLINFO_FILETIME, ×tamp) == CURLE_OK) { if (downloads[i]->download->state != IDownload::STATE_FINISHED) //decrease local timestamp if download failed to force redownload next time timestamp--; downloads[i]->download->file->SetTimestamp(timestamp); } delete downloads[i]; } downloads.clear(); curl_multi_cleanup(curlm); return !aborted; }
bool CHttpDownloader::search(std::list<IDownload*>& res, const std::string& name, IDownload::category cat) { LOG_DEBUG("%s", name.c_str() ); const std::string method(XMLRPC_METHOD); //std::string category; XmlRpc::XmlRpcClient client(XMLRPC_HOST,XMLRPC_PORT, XMLRPC_URI); XmlRpc::XmlRpcValue arg; arg["springname"]=name; arg["torrent"]=true; switch(cat) { case IDownload::CAT_MAPS: arg["category"]="map"; break; case IDownload::CAT_GAMES: arg["category"]="game"; break; case IDownload::CAT_ENGINE_LINUX: arg["category"]="engine_linux"; break; case IDownload::CAT_ENGINE_LINUX64: arg["category"]="engine_linux64"; break; case IDownload::CAT_ENGINE_WINDOWS: arg["category"]="engine_windows"; break; case IDownload::CAT_ENGINE_MACOSX: arg["category"]="engine_macosx"; break; default: break; } XmlRpc::XmlRpcValue result; client.execute(method.c_str(),arg, result); if (result.getType()!=XmlRpc::XmlRpcValue::TypeArray) { return false; } for(int i=0; i<result.size(); i++) { XmlRpc::XmlRpcValue resfile = result[i]; if (resfile.getType()!=XmlRpc::XmlRpcValue::TypeStruct) { return false; } if (resfile["category"].getType()!=XmlRpc::XmlRpcValue::TypeString) { LOG_ERROR("No category in result"); return false; } std::string filename=fileSystem->getSpringDir(); std::string category=resfile["category"]; filename+=PATH_DELIMITER; if (category=="map") filename+="maps"; else if (category=="game") filename+="games"; else if (category.find("engine")==0) // engine_windows, engine_linux, engine_macosx filename+="engine"; else LOG_ERROR("Unknown Category %s", category.c_str()); filename+=PATH_DELIMITER; if ((resfile["mirrors"].getType()!=XmlRpc::XmlRpcValue::TypeArray) || (resfile["filename"].getType()!=XmlRpc::XmlRpcValue::TypeString)) { LOG_ERROR("Invalid type in result"); return false; } filename.append(resfile["filename"]); IDownload* dl=new IDownload(filename); XmlRpc::XmlRpcValue mirrors = resfile["mirrors"]; for(int j=0; j<mirrors.size(); j++) { if (mirrors[j].getType()!=XmlRpc::XmlRpcValue::TypeString) { LOG_ERROR("Invalid type in result"); } else { dl->addMirror(mirrors[j]); } } if(resfile["torrent"].getType()==XmlRpc::XmlRpcValue::TypeBase64) { const std::vector<char> torrent = resfile["torrent"]; fileSystem->parseTorrent(&torrent[0], torrent.size(), dl); } if (resfile["version"].getType()==XmlRpc::XmlRpcValue::TypeString) { const std::string& version = resfile["version"]; dl->version = version; } if (resfile["md5"].getType()==XmlRpc::XmlRpcValue::TypeString) { dl->hash=new HashMD5(); dl->hash->Set(resfile["md5"]); } if (resfile["size"].getType()==XmlRpc::XmlRpcValue::TypeInt) { dl->size=resfile["size"]; } if (resfile["depends"].getType() == XmlRpc::XmlRpcValue::TypeArray) { for(int i=0; i<resfile["depends"].size(); i++) { if (resfile["depends"][i].getType() == XmlRpc::XmlRpcValue::TypeString) { const std::string &dep = resfile["depends"][i]; dl->addDepend(dep); } } } res.push_back(dl); } return true; }
bool CHttpDownloader::processMessages(CURLM* curlm, std::vector <DownloadData*>& downloads) { int msgs_left; HashSHA1 sha1; bool aborted=false; while(struct CURLMsg* msg=curl_multi_info_read(curlm, &msgs_left)) { switch(msg->msg) { case CURLMSG_DONE: { //a piece has been downloaded, verify it DownloadData* data=getDataByHandle(downloads, msg->easy_handle); switch(msg->data.result) { case CURLE_OK: break; case CURLE_HTTP_RETURNED_ERROR: //some 4* HTTP-Error (file not found, access denied,...) default: long http_code = 0; curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_code); LOG_ERROR("CURL error(%d): %s %d (%s)",msg->msg, curl_easy_strerror(msg->data.result), http_code, data->mirror->url.c_str()); if (data->piece>=0) { data->download->pieces[data->piece].state=IDownload::STATE_NONE; } data->mirror->status=Mirror::STATUS_BROKEN; //FIXME: cleanup curl handle here + process next dl } if (data==NULL) { LOG_ERROR("Couldn't find download in download list"); return false; } if (data->piece<0) { //download without pieces return false; } assert(data->download->file!=NULL); assert(data->piece< (int)data->download->pieces.size()); if (data->download->pieces[data->piece].sha->isSet()) { data->download->file->Hash(sha1, data->piece); if (sha1.compare(data->download->pieces[data->piece].sha)) { //piece valid data->download->pieces[data->piece].state=IDownload::STATE_FINISHED; showProcess(data->download, true); // LOG("piece %d verified!", data->piece); } else { //piece download broken, mark mirror as broken (for this file) data->download->pieces[data->piece].state=IDownload::STATE_NONE; data->mirror->status=Mirror::STATUS_BROKEN; //FIXME: cleanup curl handle here + process next dl } } else { LOG_INFO("sha1 checksum seems to be not set, can't check received piece %d", data->piece); } //get speed at which this piece was downloaded + update mirror info double dlSpeed; curl_easy_getinfo(data->easy_handle, CURLINFO_SPEED_DOWNLOAD, &dlSpeed); data->mirror->UpdateSpeed(dlSpeed); if (data->mirror->status == Mirror::STATUS_UNKNOWN) //set mirror status only when unset data->mirror->status=Mirror::STATUS_OK; //remove easy handle, as its finished curl_multi_remove_handle(curlm, data->easy_handle); curl_easy_cleanup(data->easy_handle); data->easy_handle=NULL; //piece finished / failed, try a new one if (!setupDownload(data)) { LOG_DEBUG("No piece found, all pieces finished / currently downloading"); break; } int ret=curl_multi_add_handle(curlm, data->easy_handle); if (ret!=CURLM_OK) { LOG_ERROR("curl_multi_perform_error: %d %d", ret, CURLM_BAD_EASY_HANDLE); } break; } default: LOG_ERROR("Unhandled message %d", msg->msg); } } return aborted; }
/** * Restore processor state. This is called in preparation for * the RESTART function. */ static int arm11_leave_debug_state(struct arm11_common *arm11, bool bpwp) { int retval; /* See e.g. ARM1136 TRM, "14.8.5 Leaving Debug state" */ /* NOTE: the ARM1136 TRM suggests restoring all registers * except R0/PC/CPSR right now. Instead, we do them all * at once, just a bit later on. */ /* REVISIT once we start caring about MMU and cache state, * address it here ... */ /* spec says clear wDTR and rDTR; we assume they are clear as otherwise our programming would be sloppy */ { CHECK_RETVAL(arm11_read_DSCR(arm11)); if (arm11->dscr & (DSCR_DTR_RX_FULL | DSCR_DTR_TX_FULL)) { /* The wDTR/rDTR two registers that are used to send/receive data to/from the core in tandem with corresponding instruction codes that are written into the core. The RDTR FULL/WDTR FULL flag indicates that the registers hold data that was written by one side (CPU or JTAG) and not read out by the other side. */ LOG_ERROR("wDTR/rDTR inconsistent (DSCR %08x)", (unsigned) arm11->dscr); return ERROR_FAIL; } } /* maybe restore original wDTR */ if (arm11->is_wdtr_saved) { retval = arm11_run_instr_data_prepare(arm11); if (retval != ERROR_OK) return retval; /* MCR p14,0,R0,c0,c5,0 */ retval = arm11_run_instr_data_to_core_via_r0(arm11, 0xee000e15, arm11->saved_wdtr); if (retval != ERROR_OK) return retval; retval = arm11_run_instr_data_finish(arm11); if (retval != ERROR_OK) return retval; } /* restore CPSR, PC, and R0 ... after flushing any modified * registers. */ retval = arm_dpm_write_dirty_registers(&arm11->dpm, bpwp); retval = arm11_bpwp_flush(arm11); register_cache_invalidate(arm11->arm.core_cache); /* restore DSCR */ arm11_write_DSCR(arm11, arm11->dscr); /* maybe restore rDTR */ if (arm11->is_rdtr_saved) { arm11_add_debug_SCAN_N(arm11, 0x05, ARM11_TAP_DEFAULT); arm11_add_IR(arm11, ARM11_EXTEST, ARM11_TAP_DEFAULT); struct scan_field chain5_fields[3]; uint8_t Ready = 0; /* ignored */ uint8_t Valid = 0; /* ignored */ arm11_setup_field(arm11, 32, &arm11->saved_rdtr, NULL, chain5_fields + 0); arm11_setup_field(arm11, 1, &Ready, NULL, chain5_fields + 1); arm11_setup_field(arm11, 1, &Valid, NULL, chain5_fields + 2); arm11_add_dr_scan_vc(ARRAY_SIZE(chain5_fields), chain5_fields, TAP_DRPAUSE); } /* now processor is ready to RESTART */ return ERROR_OK; }
static int jiveL_initSDL(lua_State *L) { const SDL_VideoInfo *video_info; JiveSurface *srf, *splash, *icon; Uint16 splash_w, splash_h; /* logging */ log_ui_draw = LOG_CATEGORY_GET("jivelite.ui.draw"); log_ui = LOG_CATEGORY_GET("jivelite.ui"); /* linux fbcon does not need a mouse */ SDL_putenv("SDL_NOMOUSE=1"); /* allow the screensaver */ SDL_putenv("SDL_VIDEO_ALLOW_SCREENSAVER=1"); /* initialise SDL */ if (SDL_Init(SDL_INIT_VIDEO) < 0) { LOG_ERROR(log_ui_draw, "SDL_Init(V|T|A): %s\n", SDL_GetError()); SDL_Quit(); exit(-1); } /* report video info */ if ((video_info = SDL_GetVideoInfo())) { LOG_INFO(log_ui_draw, "%d,%d %d bits/pixel %d bytes/pixel [R<<%d G<<%d B<<%d]", video_info->current_w, video_info->current_h, video_info->vfmt->BitsPerPixel, video_info->vfmt->BytesPerPixel, video_info->vfmt->Rshift, video_info->vfmt->Gshift, video_info->vfmt->Bshift); LOG_INFO(log_ui_draw, "Hardware acceleration %s available", video_info->hw_available?"is":"is not"); LOG_INFO(log_ui_draw, "Window manager %s available", video_info->wm_available?"is":"is not"); } /* Register callback for additional events (used for multimedia keys)*/ SDL_EventState(SDL_SYSWMEVENT,SDL_ENABLE); SDL_SetEventFilter(filter_events); platform_init(L); /* open window */ SDL_WM_SetCaption("JiveLite Alpha", "JiveLite Alpha"); SDL_ShowCursor(SDL_DISABLE); SDL_EnableKeyRepeat (100, 100); SDL_EnableUNICODE(1); /* load the icon */ icon = jive_surface_load_image("jive/app.png"); if (icon) { jive_surface_set_wm_icon(icon); jive_surface_free(icon); } screen_w = video_info->current_w; screen_h = video_info->current_h; screen_bpp = video_info->vfmt->BitsPerPixel; splash = jive_surface_load_image("jive/splash.png"); if (splash) { jive_surface_get_size(splash, &splash_w, &splash_h); if (video_info->wm_available) { screen_w = splash_w; screen_h = splash_h; } } srf = jive_surface_set_video_mode(screen_w, screen_h, screen_bpp, video_info->wm_available ? false : true); if (!srf) { SDL_Quit(); exit(-1); } if (splash) { jive_surface_blit(splash, srf, MAX(0, (screen_w - splash_w) / 2), MAX(0, (screen_h - splash_h) / 2)); jive_surface_flip(srf); } lua_getfield(L, 1, "screen"); if (lua_isnil(L, -1)) { LOG_ERROR(log_ui_draw, "no screen table"); SDL_Quit(); exit(-1); } /* store screen surface */ JiveSurface **p = (JiveSurface **)lua_newuserdata(L, sizeof(JiveSurface *)); *p = jive_surface_ref(srf); luaL_getmetatable(L, "JiveSurface"); lua_setmetatable(L, -2); lua_setfield(L, -2, "surface"); lua_getfield(L, -1, "bounds"); lua_pushinteger(L, screen_w); lua_rawseti(L, -2, 3); lua_pushinteger(L, screen_h); lua_rawseti(L, -2, 4); lua_pop(L, 2); /* background image */ jive_background = jive_tile_fill_color(0x000000FF); /* jive.ui.style = {} */ lua_getglobal(L, "jive"); lua_getfield(L, -1, "ui"); lua_newtable(L); lua_setfield(L, -2, "style"); lua_pop(L, 2); return 0; }
static int arm11_resume(struct target *target, int current, uint32_t address, int handle_breakpoints, int debug_execution) { // LOG_DEBUG("current %d address %08x handle_breakpoints %d debug_execution %d", // current, address, handle_breakpoints, debug_execution); struct arm11_common *arm11 = target_to_arm11(target); LOG_DEBUG("target->state: %s", target_state_name(target)); if (target->state != TARGET_HALTED) { LOG_ERROR("Target not halted"); return ERROR_TARGET_NOT_HALTED; } address = arm11_nextpc(arm11, current, address); LOG_DEBUG("RESUME PC %08" PRIx32 "%s", address, !current ? "!" : ""); /* clear breakpoints/watchpoints and VCR*/ arm11_sc7_clear_vbw(arm11); if (!debug_execution) target_free_all_working_areas(target); /* Should we skip over breakpoints matching the PC? */ if (handle_breakpoints) { struct breakpoint *bp; for (bp = target->breakpoints; bp; bp = bp->next) { if (bp->address == address) { LOG_DEBUG("must step over %08" PRIx32 "", bp->address); arm11_step(target, 1, 0, 0); break; } } } /* activate all breakpoints */ if (true) { struct breakpoint *bp; unsigned brp_num = 0; for (bp = target->breakpoints; bp; bp = bp->next) { struct arm11_sc7_action brp[2]; brp[0].write = 1; brp[0].address = ARM11_SC7_BVR0 + brp_num; brp[0].value = bp->address; brp[1].write = 1; brp[1].address = ARM11_SC7_BCR0 + brp_num; brp[1].value = 0x1 | (3 << 1) | (0x0F << 5) | (0 << 14) | (0 << 16) | (0 << 20) | (0 << 21); arm11_sc7_run(arm11, brp, ARRAY_SIZE(brp)); LOG_DEBUG("Add BP %d at %08" PRIx32, brp_num, bp->address); brp_num++; } if (arm11_vcr) arm11_sc7_set_vcr(arm11, arm11_vcr); } /* activate all watchpoints and breakpoints */ arm11_leave_debug_state(arm11, true); arm11_add_IR(arm11, ARM11_RESTART, TAP_IDLE); CHECK_RETVAL(jtag_execute_queue()); int i = 0; while (1) { CHECK_RETVAL(arm11_read_DSCR(arm11)); LOG_DEBUG("DSCR %08x", (unsigned) arm11->dscr); if (arm11->dscr & DSCR_CORE_RESTARTED) break; long long then = 0; if (i == 1000) { then = timeval_ms(); } if (i >= 1000) { if ((timeval_ms()-then) > 1000) { LOG_WARNING("Timeout (1000ms) waiting for instructions to complete"); return ERROR_FAIL; } } i++; } target->debug_reason = DBG_REASON_NOTHALTED; if (!debug_execution) target->state = TARGET_RUNNING; else target->state = TARGET_DEBUG_RUNNING; CHECK_RETVAL(target_call_event_callbacks(target, TARGET_EVENT_RESUMED)); return ERROR_OK; }
bool initializeOpenGLShims() { static bool success = true; static bool initialized = false; if (initialized) return success; initialized = true; ASSIGN_FUNCTION_TABLE_ENTRY(glActiveTexture, success); ASSIGN_FUNCTION_TABLE_ENTRY(glAttachShader, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBindAttribLocation, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBindBuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBindFramebuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBindRenderbuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBlendColor, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBlendEquation, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBlendEquationSeparate, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBlendFuncSeparate, success); // In GLES2 there is optional an ANGLE extension for glBlitFramebuffer #if defined(GL_ES_VERSION_2_0) ASSIGN_FUNCTION_TABLE_ENTRY_EXT(glBlitFramebuffer); #else ASSIGN_FUNCTION_TABLE_ENTRY(glBlitFramebuffer, success); #endif ASSIGN_FUNCTION_TABLE_ENTRY(glBufferData, success); ASSIGN_FUNCTION_TABLE_ENTRY(glBufferSubData, success); ASSIGN_FUNCTION_TABLE_ENTRY(glCheckFramebufferStatus, success); ASSIGN_FUNCTION_TABLE_ENTRY(glCompileShader, success); ASSIGN_FUNCTION_TABLE_ENTRY(glCreateProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glCreateShader, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDeleteBuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDeleteFramebuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDeleteProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDeleteRenderbuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDeleteShader, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDetachShader, success); ASSIGN_FUNCTION_TABLE_ENTRY(glDisableVertexAttribArray, success); ASSIGN_FUNCTION_TABLE_ENTRY(glEnableVertexAttribArray, success); ASSIGN_FUNCTION_TABLE_ENTRY(glFramebufferRenderbuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glFramebufferTexture2D, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGenBuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGenerateMipmap, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGenFramebuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGenRenderbuffers, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetActiveAttrib, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetActiveUniform, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetAttachedShaders, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetAttribLocation, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetBufferParameteriv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetFramebufferAttachmentParameteriv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetProgramInfoLog, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetProgramiv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetRenderbufferParameteriv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetShaderInfoLog, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetShaderiv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetShaderSource, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetUniformfv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetUniformiv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetUniformLocation, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetVertexAttribfv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetVertexAttribiv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glGetVertexAttribPointerv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glIsBuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glIsFramebuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glIsProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glIsRenderbuffer, success); ASSIGN_FUNCTION_TABLE_ENTRY(glIsShader, success); ASSIGN_FUNCTION_TABLE_ENTRY(glLinkProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glRenderbufferStorage, success); // In GLES2 there are optional ANGLE and APPLE extensions for glRenderbufferStorageMultisample. #if defined(GL_ES_VERSION_2_0) ASSIGN_FUNCTION_TABLE_ENTRY_EXT(glRenderbufferStorageMultisample); #else ASSIGN_FUNCTION_TABLE_ENTRY(glRenderbufferStorageMultisample, success); #endif ASSIGN_FUNCTION_TABLE_ENTRY(glSampleCoverage, success); ASSIGN_FUNCTION_TABLE_ENTRY(glShaderSource, success); ASSIGN_FUNCTION_TABLE_ENTRY(glStencilFuncSeparate, success); ASSIGN_FUNCTION_TABLE_ENTRY(glStencilMaskSeparate, success); ASSIGN_FUNCTION_TABLE_ENTRY(glStencilOpSeparate, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform1f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform1fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform1i, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform1iv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform2f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform2fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform2i, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform2iv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform3f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform3fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform3i, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform3iv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform4f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform4fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform4i, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniform4iv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniformMatrix2fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniformMatrix3fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUniformMatrix4fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glUseProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glValidateProgram, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib1f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib1fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib2f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib2fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib3f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib3fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib4f, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttrib4fv, success); ASSIGN_FUNCTION_TABLE_ENTRY(glVertexAttribPointer, success); if (!success) LOG_ERROR("Could not initialize OpenGL shims"); return success; }
int handle_error(SOCKET sock, char* message) { LOG_ERROR(("%s. %d",message, WSAGetLastError())); closesocket (sock); return -1; }
int argmax_fs_2i_base::_forecastAndProcess( bool &eos, std::vector< gr_istream_base * > &istreams , std::vector< gr_ostream_base * > &ostreams ) { typedef std::vector< gr_istream_base * > _IStreamList; typedef std::vector< gr_ostream_base * > _OStreamList; _OStreamList::iterator ostream; _IStreamList::iterator istream = istreams.begin(); int nout = 0; bool dataReady = false; if ( !eos ) { uint64_t max_items_avail = 0; for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) { LOG_TRACE( argmax_fs_2i_base, "GET MAX ITEMS: STREAM:"<< idx << " NITEMS/SCALARS:" << (*istream)->nitems() << "/" << (*istream)->nelems() ); max_items_avail = std::max( (*istream)->nitems(), max_items_avail ); } if ( max_items_avail == 0 ) { LOG_TRACE( argmax_fs_2i_base, "DATA CHECK - MAX ITEMS NOUTPUT/MAX_ITEMS:" << noutput_items << "/" << max_items_avail); return -1; } // // calc number of output elements based on input items available // noutput_items = 0; if ( !gr_sptr->fixed_rate() ) { noutput_items = round_down((int32_t) (max_items_avail * gr_sptr->relative_rate()), gr_sptr->output_multiple()); LOG_TRACE( argmax_fs_2i_base, " VARIABLE FORECAST NOUTPUT == " << noutput_items ); } else { istream = istreams.begin(); for ( int i=0; istream != istreams.end(); i++, istream++ ) { int t_noutput_items = gr_sptr->fixed_rate_ninput_to_noutput( (*istream)->nitems() ); if ( gr_sptr->output_multiple_set() ) { t_noutput_items = round_up(t_noutput_items, gr_sptr->output_multiple()); } if ( t_noutput_items > 0 ) { if ( noutput_items == 0 ) { noutput_items = t_noutput_items; } if ( t_noutput_items <= noutput_items ) { noutput_items = t_noutput_items; } } } LOG_TRACE( argmax_fs_2i_base, " FIXED FORECAST NOUTPUT/output_multiple == " << noutput_items << "/" << gr_sptr->output_multiple()); } // // ask the block how much input they need to produce noutput_items... // if enough data is available to process then set the dataReady flag // int32_t outMultiple = gr_sptr->output_multiple(); while ( !dataReady && noutput_items >= outMultiple ) { // // ask the block how much input they need to produce noutput_items... // gr_sptr->forecast(noutput_items, _ninput_items_required); LOG_TRACE( argmax_fs_2i_base, "--> FORECAST IN/OUT " << _ninput_items_required[0] << "/" << noutput_items ); istream = istreams.begin(); uint32_t dr_cnt=0; for ( int idx=0 ; noutput_items > 0 && istream != istreams.end(); idx++, istream++ ) { // check if buffer has enough elements _input_ready[idx] = false; if ( (*istream)->nitems() >= (uint64_t)_ninput_items_required[idx] ) { _input_ready[idx] = true; dr_cnt++; } LOG_TRACE( argmax_fs_2i_base, "ISTREAM DATACHECK NELMS/NITEMS/REQ/READY:" << (*istream)->nelems() << "/" << (*istream)->nitems() << "/" << _ninput_items_required[idx] << "/" << _input_ready[idx]); } if ( dr_cnt < istreams.size() ) { if ( outMultiple > 1 ) { noutput_items -= outMultiple; } else { noutput_items /= 2; } } else { dataReady = true; } LOG_TRACE( argmax_fs_2i_base, " TRIM FORECAST NOUTPUT/READY " << noutput_items << "/" << dataReady ); } // check if data is ready... if ( !dataReady ) { LOG_TRACE( argmax_fs_2i_base, "DATA CHECK - NOT ENOUGH DATA AVAIL/REQ:" << _istreams[0]->nitems() << "/" << _ninput_items_required[0] ); return -1; } // reset looping variables int ritems = 0; int nitems = 0; // reset caching vectors _output_items.clear(); _input_items.clear(); _ninput_items.clear(); istream = istreams.begin(); for ( int idx=0 ; istream != istreams.end(); idx++, istream++ ) { // check if the stream is ready if ( !_input_ready[idx] ) { continue; } // get number of items remaining try { ritems = gr_sptr->nitems_read( idx ); } catch(...){ // something bad has happened, we are missing an input stream LOG_ERROR( argmax_fs_2i_base, "MISSING INPUT STREAM FOR GR BLOCK, STREAM ID:" << (*istream)->streamID ); return -2; } nitems = (*istream)->nitems() - ritems; LOG_TRACE( argmax_fs_2i_base, " ISTREAM: IDX:" << idx << " ITEMS AVAIL/READ/REQ " << nitems << "/" << ritems << "/" << _ninput_items_required[idx] ); if ( nitems >= _ninput_items_required[idx] && nitems > 0 ) { //remove eos checks ...if ( nitems < _ninput_items_required[idx] ) nitems=0; _ninput_items.push_back( nitems ); _input_items.push_back( (*istream)->read_pointer(ritems) ); } } // // setup output buffer vector based on noutput.. // ostream = ostreams.begin(); for( ; ostream != ostreams.end(); ostream++ ) { (*ostream)->resize(noutput_items); _output_items.push_back( (*ostream)->write_pointer() ); } nout=0; if ( _input_items.size() != 0 && serviceThread->threadRunning() ) { LOG_TRACE( argmax_fs_2i_base, " CALLING WORK.....N_OUT:" << noutput_items << " N_IN:" << nitems << " ISTREAMS:" << _input_items.size() << " OSTREAMS:" << _output_items.size()); nout = gr_sptr->general_work( noutput_items, _ninput_items, _input_items, _output_items); LOG_TRACE( argmax_fs_2i_base, "RETURN WORK ..... N_OUT:" << nout); } // check for stop condition from work method if ( nout < gr_block::WORK_DONE ) { LOG_WARN( argmax_fs_2i_base, "WORK RETURNED STOP CONDITION..." << nout ); nout=0; eos = true; } } if (nout != 0 or eos ) { noutput_items = nout; LOG_TRACE( argmax_fs_2i_base, " WORK RETURNED: NOUT : " << nout << " EOS:" << eos); ostream = ostreams.begin(); for ( int idx=0 ; ostream != ostreams.end(); idx++, ostream++ ) { bool gotPkt = false; TimeStamp pktTs; int inputIdx = idx; if ( (size_t)(inputIdx) >= istreams.size() ) { for ( inputIdx= istreams.size()-1; inputIdx > -1; inputIdx--) { if ( not istreams[inputIdx]->pktNull() ) { gotPkt = true; pktTs = istreams[inputIdx]->getPktTimeStamp(); break; } } } else { pktTs = istreams[inputIdx]->getPktTimeStamp(); if ( not istreams[inputIdx]->pktNull() ){ gotPkt = true; } } LOG_TRACE( argmax_fs_2i_base, "PUSHING DATA ITEMS/STREAM_ID " << (*ostream)->nitems() << "/" << (*ostream)->streamID ); if ( _maintainTimeStamp ) { // set time stamp for output samples based on input time stamp if ( (*ostream)->nelems() == 0 ) { #ifdef TEST_TIME_STAMP LOG_DEBUG( argmax_fs_2i_base, "SEED - TS SRI: xdelta:" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( argmax_fs_2i_base, "OSTREAM WRITE: maint:" << _maintainTimeStamp ); LOG_DEBUG( argmax_fs_2i_base, " mode:" << ostream->tstamp.tcmode ); LOG_DEBUG( argmax_fs_2i_base, " status:" << ostream->tstamp.tcstatus ); LOG_DEBUG( argmax_fs_2i_base, " offset:" << ostream->tstamp.toff ); LOG_DEBUG( argmax_fs_2i_base, " whole:" << std::setprecision(10) << ostream->tstamp.twsec ); LOG_DEBUG( argmax_fs_2i_base, "SEED - TS frac:" << std::setprecision(12) << ostream->tstamp.tfsec ); #endif (*ostream)->setTimeStamp( pktTs, _maintainTimeStamp ); } // write out samples, and set next time stamp based on xdelta and noutput_items (*ostream)->write ( noutput_items, eos ); } else { // use incoming packet's time stamp to forward if ( gotPkt ) { #ifdef TEST_TIME_STAMP LOG_DEBUG( argmax_fs_2i_base, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( argmax_fs_2i_base, "PKT - TS maint:" << _maintainTimeStamp ); LOG_DEBUG( argmax_fs_2i_base, " mode:" << pktTs.tcmode ); LOG_DEBUG( argmax_fs_2i_base, " status:" << pktTs.tcstatus ); LOG_DEBUG( argmax_fs_2i_base, " offset:" << pktTs.toff ); LOG_DEBUG( argmax_fs_2i_base, " whole:" << std::setprecision(10) << pktTs.twsec ); LOG_DEBUG( argmax_fs_2i_base, "PKT - TS frac:" << std::setprecision(12) << pktTs.tfsec ); #endif (*ostream)->write( noutput_items, eos, pktTs ); } else { #ifdef TEST_TIME_STAMP LOG_DEBUG( argmax_fs_2i_base, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( argmax_fs_2i_base, "OSTREAM TOD maint:" << _maintainTimeStamp ); LOG_DEBUG( argmax_fs_2i_base, " mode:" << ostream->tstamp.tcmode ); LOG_DEBUG( argmax_fs_2i_base, " status:" << ostream->tstamp.tcstatus ); LOG_DEBUG( argmax_fs_2i_base, " offset:" << ostream->tstamp.toff ); LOG_DEBUG( argmax_fs_2i_base, " whole:" << std::setprecision(10) << ostream->tstamp.twsec ); LOG_DEBUG( argmax_fs_2i_base, "OSTREAM TOD frac:" << std::setprecision(12) << ostream->tstamp.tfsec ); #endif // use time of day as time stamp (*ostream)->write( noutput_items, eos, _maintainTimeStamp ); } } } // for ostreams } return nout; }
bool Shader::loadFromFile(const std::string& vertex, const std::string& tessControl, const std::string& tessEvaluation, const std::string& geometry, const std::string& fragment) { // Create a program m_program = render::lib::createProgram(); // Read the files std::string vertexShader; if (!getFileContents(vertex, vertexShader)) { LOG_ERROR("Failed to open Vertex Shader file: %s", vertex.c_str()); return false; } else LOG_INFO("Vertex Shader successfully loaded: %s", vertex.c_str()); std::string tessControlShader; if (!getFileContents(tessControl, tessControlShader)) { LOG_ERROR("Failed to open Tesselation Control Shader file: %s", tessControl.c_str()); return false; } else LOG_INFO("Tesselation Control Shader successfully loaded: %s", tessControl.c_str()); std::string tessEvaluationShader; if (!getFileContents(tessEvaluation, tessEvaluationShader)) { LOG_ERROR("Failed to open Tesselation Evaluation Shader file: %s", tessEvaluation.c_str()); return false; } else LOG_INFO("Tesselation Evaluation Shader successfully loaded: %s", tessEvaluation.c_str()); std::string geometryShader; if (!getFileContents(geometry, geometryShader)) { LOG_ERROR("Failed to open Geometry Shader file: %s", geometry.c_str()); return false; } else LOG_INFO("Geometry Shader successfully loaded: %s", geometry.c_str()); std::string fragmentShader; if (!getFileContents(fragment, fragmentShader)) { LOG_ERROR("Failed to open Fragment Shader file: %s", fragment.c_str()); return false; } else LOG_INFO("Fragment Shader successfully loaded: %s", fragment.c_str()); bool success = false; if(addShader(vertexShader, ODIN_VERTEX_SHADER) && addShader(tessControlShader, ODIN_TESS_CONTROL_SHADER) && addShader(tessEvaluationShader, ODIN_TESS_EVALUATION_SHADER) && addShader(geometryShader, ODIN_GEOMETRY_SHADER) && addShader(fragmentShader, ODIN_FRAGMENT_SHADER)) { // link program render::lib::linkProgram(m_program); if (!checkLinkErrors(m_program)) { render::lib::deleteProgram(m_program); m_program = 0; } success = true; } return success; }
int cellMsgDialogOpen2(u32 type, mem_list_ptr_t<u8> msgString, mem_func_ptr_t<CellMsgDialogCallback> callback, u32 userData, u32 extParam) { cellSysutil->Warning("cellMsgDialogOpen2(type=0x%x, msgString_addr=0x%x, callback_addr=0x%x, userData=0x%x, extParam=0x%x)", type, msgString.GetAddr(), callback.GetAddr(), userData, extParam); if (!msgString.IsGood() || !callback.IsGood()) { return CELL_EFAULT; } //type |= CELL_MSGDIALOG_TYPE_PROGRESSBAR_SINGLE; //type |= CELL_MSGDIALOG_TYPE_BUTTON_TYPE_YESNO; MsgDialogState old = msgDialogNone; if (!g_msg_dialog_state.compare_exchange_strong(old, msgDialogOpen)) { return CELL_SYSUTIL_ERROR_BUSY; } thread t("MsgDialog thread", [=]() { switch (type & CELL_MSGDIALOG_TYPE_SE_TYPE) { case CELL_MSGDIALOG_TYPE_SE_TYPE_NORMAL: LOG_WARNING(Log::HLE, "%s", msgString.GetString()); break; case CELL_MSGDIALOG_TYPE_SE_TYPE_ERROR: LOG_ERROR(Log::HLE, "%s", msgString.GetString()); break; } switch (type & CELL_MSGDIALOG_TYPE_SE_MUTE) // TODO { case CELL_MSGDIALOG_TYPE_SE_MUTE_OFF: break; case CELL_MSGDIALOG_TYPE_SE_MUTE_ON: break; } switch (type & CELL_MSGDIALOG_TYPE_BG) // TODO { case CELL_MSGDIALOG_TYPE_BG_INVISIBLE: break; case CELL_MSGDIALOG_TYPE_BG_VISIBLE: break; } switch (type & CELL_MSGDIALOG_TYPE_DEFAULT_CURSOR) // TODO { case CELL_MSGDIALOG_TYPE_DEFAULT_CURSOR_NO: break; default: break; } u64 status = CELL_MSGDIALOG_BUTTON_NONE; volatile bool m_signal = false; wxGetApp().CallAfter([&]() { wxWindow* parent = nullptr; // TODO: align it better m_gauge1 = nullptr; m_gauge2 = nullptr; m_text1 = nullptr; m_text2 = nullptr; wxButton* m_button_ok = nullptr; wxButton* m_button_yes = nullptr; wxButton* m_button_no = nullptr; g_msg_dialog = new wxDialog(parent, wxID_ANY, type & CELL_MSGDIALOG_TYPE_SE_TYPE ? "" : "Error", wxDefaultPosition, wxDefaultSize); g_msg_dialog->SetExtraStyle(g_msg_dialog->GetExtraStyle() | wxWS_EX_TRANSIENT); wxSizer* sizer1 = new wxBoxSizer(wxVERTICAL); wxStaticText* m_text = new wxStaticText(g_msg_dialog, wxID_ANY, wxString(msgString.GetString(), wxConvUTF8)); sizer1->Add(m_text, 0, wxALIGN_CENTER_HORIZONTAL | wxLEFT | wxRIGHT | wxTOP, 16); switch (type & CELL_MSGDIALOG_TYPE_PROGRESSBAR) { case CELL_MSGDIALOG_TYPE_PROGRESSBAR_DOUBLE: m_gauge2 = new wxGauge(g_msg_dialog, wxID_ANY, 100, wxDefaultPosition, wxSize(300, -1), wxGA_HORIZONTAL | wxGA_SMOOTH); m_text2 = new wxStaticText(g_msg_dialog, wxID_ANY, ""); m_text2->SetAutoLayout(true); case CELL_MSGDIALOG_TYPE_PROGRESSBAR_SINGLE: m_gauge1 = new wxGauge(g_msg_dialog, wxID_ANY, 100, wxDefaultPosition, wxSize(300, -1), wxGA_HORIZONTAL | wxGA_SMOOTH); m_text1 = new wxStaticText(g_msg_dialog, wxID_ANY, ""); m_text1->SetAutoLayout(true); case CELL_MSGDIALOG_TYPE_PROGRESSBAR_NONE: break; } if (m_gauge1) { sizer1->Add(m_text1, 0, wxALIGN_CENTER_HORIZONTAL | wxLEFT | wxRIGHT | wxTOP, 8); sizer1->Add(m_gauge1, 0, wxALIGN_CENTER_HORIZONTAL | wxLEFT | wxRIGHT, 16); m_gauge1->SetValue(0); } if (m_gauge2) { sizer1->Add(m_text2, 0, wxALIGN_CENTER_HORIZONTAL | wxLEFT | wxRIGHT | wxTOP, 8); sizer1->Add(m_gauge2, 0, wxALIGN_CENTER_HORIZONTAL | wxLEFT | wxRIGHT, 16); m_gauge2->SetValue(0); } wxBoxSizer* buttons = new wxBoxSizer(wxHORIZONTAL); switch (type & CELL_MSGDIALOG_TYPE_BUTTON_TYPE) { case CELL_MSGDIALOG_TYPE_BUTTON_TYPE_NONE: break; case CELL_MSGDIALOG_TYPE_BUTTON_TYPE_YESNO: m_button_yes = new wxButton(g_msg_dialog, wxID_YES); buttons->Add(m_button_yes, 0, wxALIGN_CENTER_HORIZONTAL | wxRIGHT, 8); m_button_no = new wxButton(g_msg_dialog, wxID_NO); buttons->Add(m_button_no, 0, wxALIGN_CENTER_HORIZONTAL, 16); sizer1->Add(buttons, 0, wxALIGN_CENTER_HORIZONTAL | wxLEFT | wxRIGHT | wxTOP, 16); break; case CELL_MSGDIALOG_TYPE_BUTTON_TYPE_OK: m_button_ok = new wxButton(g_msg_dialog, wxID_OK); buttons->Add(m_button_ok, 0, wxALIGN_CENTER_HORIZONTAL, 16); sizer1->Add(buttons, 0, wxALIGN_CENTER_HORIZONTAL | wxLEFT | wxRIGHT | wxTOP, 16); break; } sizer1->AddSpacer(16); g_msg_dialog->SetSizerAndFit(sizer1); g_msg_dialog->Centre(wxBOTH); g_msg_dialog->Show(); g_msg_dialog->Enable(); g_msg_dialog->Bind(wxEVT_BUTTON, [&](wxCommandEvent& event) { status = (event.GetId() == wxID_NO) ? CELL_MSGDIALOG_BUTTON_NO : CELL_MSGDIALOG_BUTTON_YES /* OK */; g_msg_dialog->Hide(); m_wait_until = get_system_time(); g_msg_dialog_state = msgDialogClose; }); g_msg_dialog->Bind(wxEVT_CLOSE_WINDOW, [&](wxCloseEvent& event) { if (type & CELL_MSGDIALOG_TYPE_DISABLE_CANCEL) { } else { status = CELL_MSGDIALOG_BUTTON_ESCAPE; g_msg_dialog->Hide(); m_wait_until = get_system_time(); g_msg_dialog_state = msgDialogClose; } }); m_signal = true; }); while (!m_signal) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } while (g_msg_dialog_state == msgDialogOpen || get_system_time() < m_wait_until) { if (Emu.IsStopped()) { g_msg_dialog_state = msgDialogAbort; break; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } if (callback && (g_msg_dialog_state != msgDialogAbort)) callback.async(status, userData); wxGetApp().CallAfter([&]() { delete g_msg_dialog; g_msg_dialog = nullptr; }); g_msg_dialog_state = msgDialogNone; }); t.detach(); return CELL_OK; }
pj_status_t init_stack(const std::string& system_name, const std::string& sas_address, int pcscf_trusted_port, int pcscf_untrusted_port, int scscf_port, int icscf_port, const std::string& local_host, const std::string& public_host, const std::string& home_domain, const std::string& additional_home_domains, const std::string& scscf_uri, const std::string& alias_hosts, SIPResolver* sipresolver, int num_pjsip_threads, int record_routing_model, const int default_session_expires, const int max_session_expires, QuiescingManager *quiescing_mgr_arg, const std::string& cdf_domain) { pj_status_t status; pj_sockaddr pri_addr; pj_sockaddr addr_list[16]; unsigned addr_cnt = PJ_ARRAY_SIZE(addr_list); unsigned i; // Set up the vectors of threads. The threads don't get created until // start_pjsip_threads is called. pjsip_threads.resize(num_pjsip_threads); // Get ports and host names specified on options. If local host was not // specified, use the host name returned by pj_gethostname. char* local_host_cstr = strdup(local_host.c_str()); char* public_host_cstr = strdup(public_host.c_str()); char* home_domain_cstr = strdup(home_domain.c_str()); char* scscf_uri_cstr; if (scscf_uri.empty()) { // Create a default S-CSCF URI using the localhost and S-CSCF port. std::string tmp_scscf_uri = "sip:" + local_host + ":" + std::to_string(scscf_port) + ";transport=TCP"; scscf_uri_cstr = strdup(tmp_scscf_uri.c_str()); } else { // Use the specified URI. scscf_uri_cstr = strdup(scscf_uri.c_str()); } // This is only set on Bono nodes (it's the empty string otherwise) char* cdf_domain_cstr = strdup(cdf_domain.c_str()); // Copy port numbers to stack data. stack_data.pcscf_trusted_port = pcscf_trusted_port; stack_data.pcscf_untrusted_port = pcscf_untrusted_port; stack_data.scscf_port = scscf_port; stack_data.icscf_port = icscf_port; stack_data.sipresolver = sipresolver; // Copy other functional options to stack data. stack_data.default_session_expires = default_session_expires; stack_data.max_session_expires = max_session_expires; // Work out local and public hostnames and cluster domain names. stack_data.local_host = (local_host != "") ? pj_str(local_host_cstr) : *pj_gethostname(); stack_data.public_host = (public_host != "") ? pj_str(public_host_cstr) : stack_data.local_host; stack_data.default_home_domain = (home_domain != "") ? pj_str(home_domain_cstr) : stack_data.local_host; stack_data.scscf_uri = pj_str(scscf_uri_cstr); stack_data.cdf_domain = pj_str(cdf_domain_cstr); // Build a set of home domains stack_data.home_domains = std::unordered_set<std::string>(); stack_data.home_domains.insert(PJUtils::pj_str_to_string(&stack_data.default_home_domain)); if (additional_home_domains != "") { std::list<std::string> domains; Utils::split_string(additional_home_domains, ',', domains, 0, true); stack_data.home_domains.insert(domains.begin(), domains.end()); } // Set up the default address family. This is IPv4 unless our local host is an IPv6 address. stack_data.addr_family = AF_INET; struct in6_addr dummy_addr; if (inet_pton(AF_INET6, local_host_cstr, &dummy_addr) == 1) { LOG_DEBUG("Local host is an IPv6 address - enabling IPv6 mode"); stack_data.addr_family = AF_INET6; } stack_data.record_route_on_every_hop = false; stack_data.record_route_on_initiation_of_originating = false; stack_data.record_route_on_initiation_of_terminating = false; stack_data.record_route_on_completion_of_originating = false; stack_data.record_route_on_completion_of_terminating = false; stack_data.record_route_on_diversion = false; if (scscf_port != 0) { switch (record_routing_model) { case 1: stack_data.record_route_on_initiation_of_originating = true; stack_data.record_route_on_completion_of_terminating = true; break; case 2: stack_data.record_route_on_initiation_of_originating = true; stack_data.record_route_on_initiation_of_terminating = true; stack_data.record_route_on_completion_of_originating = true; stack_data.record_route_on_completion_of_terminating = true; stack_data.record_route_on_diversion = true; break; case 3: stack_data.record_route_on_every_hop = true; stack_data.record_route_on_initiation_of_originating = true; stack_data.record_route_on_initiation_of_terminating = true; stack_data.record_route_on_completion_of_originating = true; stack_data.record_route_on_completion_of_terminating = true; stack_data.record_route_on_diversion = true; break; default: LOG_ERROR("Record-Route setting should be 1, 2, or 3, is %d. Defaulting to Record-Route on every hop.", record_routing_model); stack_data.record_route_on_every_hop = true; } } std::string system_name_sas = system_name; std::string system_type_sas = (pcscf_trusted_port != 0) ? "bono" : "sprout"; // Initialize SAS logging. if (system_name_sas == "") { system_name_sas = std::string(stack_data.local_host.ptr, stack_data.local_host.slen); } SAS::init(system_name, system_type_sas, SASEvent::CURRENT_RESOURCE_BUNDLE, sas_address, sas_write); // Initialise PJSIP and all the associated resources. status = init_pjsip(); // Initialize the PJUtils module. PJUtils::init(); // Create listening transports for the ports whichtrusted and untrusted ports. stack_data.pcscf_trusted_tcp_factory = NULL; if (stack_data.pcscf_trusted_port != 0) { status = start_transports(stack_data.pcscf_trusted_port, stack_data.local_host, &stack_data.pcscf_trusted_tcp_factory); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); } stack_data.pcscf_untrusted_tcp_factory = NULL; if (stack_data.pcscf_untrusted_port != 0) { status = start_transports(stack_data.pcscf_untrusted_port, stack_data.public_host, &stack_data.pcscf_untrusted_tcp_factory); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); } stack_data.scscf_tcp_factory = NULL; if (stack_data.scscf_port != 0) { status = start_transports(stack_data.scscf_port, stack_data.public_host, &stack_data.scscf_tcp_factory); if (status == PJ_SUCCESS) { CL_SPROUT_S_CSCF_AVAIL.log(stack_data.scscf_port); } else { CL_SPROUT_S_CSCF_INIT_FAIL2.log(stack_data.scscf_port); } PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); } stack_data.icscf_tcp_factory = NULL; if (stack_data.icscf_port != 0) { status = start_transports(stack_data.icscf_port, stack_data.public_host, &stack_data.icscf_tcp_factory); if (status == PJ_SUCCESS) { CL_SPROUT_I_CSCF_AVAIL.log(stack_data.icscf_port); } else { CL_SPROUT_I_CSCF_INIT_FAIL2.log(stack_data.icscf_port); } PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); } // List all names matching local endpoint. // Note that PJLIB version 0.6 and newer has a function to // enumerate local IP interface (pj_enum_ip_interface()), so // by using it would be possible to list all IP interfaces in // this host. // The first address is important since this would be the one // to be added in Record-Route. stack_data.name[stack_data.name_cnt] = stack_data.local_host; stack_data.name_cnt++; if (strcmp(local_host_cstr, public_host_cstr)) { stack_data.name[stack_data.name_cnt] = stack_data.public_host; stack_data.name_cnt++; } if ((scscf_port != 0) && (!scscf_uri.empty())) { // S-CSCF enabled with a specified URI, so add host name from the URI to hostnames. pjsip_sip_uri* uri = (pjsip_sip_uri*)PJUtils::uri_from_string(scscf_uri, stack_data.pool); if (uri != NULL) { stack_data.name[stack_data.name_cnt] = uri->host; stack_data.name_cnt++; } } if (pj_gethostip(pj_AF_INET(), &pri_addr) == PJ_SUCCESS) { pj_strdup2(stack_data.pool, &stack_data.name[stack_data.name_cnt], pj_inet_ntoa(pri_addr.ipv4.sin_addr)); stack_data.name_cnt++; } // Get the rest of IP interfaces. if (pj_enum_ip_interface(pj_AF_INET(), &addr_cnt, addr_list) == PJ_SUCCESS) { for (i = 0; i < addr_cnt; ++i) { if (addr_list[i].ipv4.sin_addr.s_addr == pri_addr.ipv4.sin_addr.s_addr) { continue; } pj_strdup2(stack_data.pool, &stack_data.name[stack_data.name_cnt], pj_inet_ntoa(addr_list[i].ipv4.sin_addr)); stack_data.name_cnt++; } } // Note that we no longer consider 127.0.0.1 and localhost as aliases. // Parse the list of alias host names. stack_data.aliases = std::unordered_set<std::string>(); if (alias_hosts != "") { std::list<std::string> aliases; Utils::split_string(alias_hosts, ',', aliases, 0, true); stack_data.aliases.insert(aliases.begin(), aliases.end()); for (std::unordered_set<std::string>::iterator it = stack_data.aliases.begin(); it != stack_data.aliases.end(); ++it) { pj_strdup2(stack_data.pool, &stack_data.name[stack_data.name_cnt], it->c_str()); stack_data.name_cnt++; } } LOG_STATUS("Local host aliases:"); for (i = 0; i < stack_data.name_cnt; ++i) { LOG_STATUS(" %.*s", (int)stack_data.name[i].slen, stack_data.name[i].ptr); } // Set up the Last Value Cache, accumulators and counters. std::string process_name; if ((stack_data.pcscf_trusted_port != 0) && (stack_data.pcscf_untrusted_port != 0)) { process_name = "bono"; } else { process_name = "sprout"; } stack_data.stats_aggregator = new LastValueCache(num_known_stats, known_statnames, process_name); if (quiescing_mgr_arg != NULL) { quiescing_mgr = quiescing_mgr_arg; // Create an instance of the stack quiesce handler. This acts as a glue // class between the stack modulem connections tracker, and the quiescing // manager. stack_quiesce_handler = new StackQuiesceHandler(); // Create a new connection tracker, and register the quiesce handler with // it. connection_tracker = new ConnectionTracker(stack_quiesce_handler); // Register the quiesce handler with the quiescing manager (the former // implements the connection handling interface). quiescing_mgr->register_conns_handler(stack_quiesce_handler); pjsip_endpt_register_module(stack_data.endpt, &mod_connection_tracking); } return status; }
/* Generic function to compute L3Geom (with colinear points), used for {sphere,facet,wall}+sphere contacts now */ void Ig2_Sphere_Sphere_L3Geom::handleSpheresLikeContact(const shared_ptr<Interaction>& I, const State& state1, const State& state2, const Vector3r& shift2, bool is6Dof, const Vector3r& normal, const Vector3r& contPt, Real uN, Real r1, Real r2){ // create geometry if(!I->geom){ if(is6Dof) I->geom=shared_ptr<L6Geom>(new L6Geom); else I->geom=shared_ptr<L3Geom>(new L3Geom); L3Geom& g(I->geom->cast<L3Geom>()); g.contactPoint=contPt; g.refR1=r1; g.refR2=r2; g.normal=normal; // g.trsf.setFromTwoVectors(Vector3r::UnitX(),g.normal); // quaternion just from the X-axis; does not seem to work for some reason?! const Vector3r& locX(g.normal); // initial local y-axis orientation, in the xz or xy plane, depending on which component is larger to avoid singularities Vector3r locY=normal.cross(abs(normal[1])<abs(normal[2])?Vector3r::UnitY():Vector3r::UnitZ()); locY-=locX*locY.dot(locX); locY.normalize(); Vector3r locZ=normal.cross(locY); #ifdef L3_TRSF_QUATERNION Matrix3r trsf; trsf.row(0)=locX; trsf.row(1)=locY; trsf.row(2)=locZ; g.trsf=Quaternionr(trsf); // from transformation matrix #else g.trsf.row(0)=locX; g.trsf.row(1)=locY; g.trsf.row(2)=locZ; #endif g.u=Vector3r(uN,0,0); // zero shear displacement if(distFactor<0) g.u0[0]=uN; // L6Geom::phi is initialized to Vector3r::Zero() automatically //cerr<<"Init trsf=\n"<<g.trsf<<endl<<"locX="<<locX<<", locY="<<locY<<", locZ="<<locZ<<endl; return; } // update geometry /* motion of the conctact consists in rigid motion (normRotVec, normTwistVec) and mutual motion (relShearDu); they are used to update trsf and u */ L3Geom& g(I->geom->cast<L3Geom>()); const Vector3r& currNormal(normal); const Vector3r& prevNormal(g.normal); // normal rotation vector, between last steps Vector3r normRotVec=prevNormal.cross(currNormal); // contrary to what ScGeom::precompute does now (r2486), we take average normal, i.e. .5*(prevNormal+currNormal), // so that all terms in the equation are in the previous mid-step // the re-normalization might not be necessary for very small increments, but better do it Vector3r avgNormal=(approxMask&APPROX_NO_MID_NORMAL) ? prevNormal : .5*(prevNormal+currNormal); if(!(approxMask&APPROX_NO_RENORM_MID_NORMAL) && !(approxMask&APPROX_NO_MID_NORMAL)) avgNormal.normalize(); // normalize only if used and if requested via approxMask // twist vector of the normal from the last step Vector3r normTwistVec=avgNormal*scene->dt*.5*avgNormal.dot(state1.angVel+state2.angVel); // compute relative velocity // noRatch: take radius or current distance as the branch vector; see discussion in ScGeom::precompute (avoidGranularRatcheting) Vector3r c1x=((noRatch && !r1>0) ? ( r1*normal).eval() : (contPt-state1.pos).eval()); // used only for sphere-sphere Vector3r c2x=(noRatch ? (-r2*normal).eval() : (contPt-state2.pos+shift2).eval()); //Vector3r state2velCorrected=state2.vel+(scene->isPeriodic?scene->cell->intrShiftVel(I->cellDist):Vector3r::Zero()); // velocity of the second particle, corrected with meanfield velocity if necessary //cerr<<"correction "<<(scene->isPeriodic?scene->cell->intrShiftVel(I->cellDist):Vector3r::Zero())<<endl; Vector3r relShearVel=(state2.vel+state2.angVel.cross(c2x))-(state1.vel+state1.angVel.cross(c1x)); // account for relative velocity of particles in different cell periods if(scene->isPeriodic) relShearVel+=scene->cell->intrShiftVel(I->cellDist); relShearVel-=avgNormal.dot(relShearVel)*avgNormal; Vector3r relShearDu=relShearVel*scene->dt; /* Update of quantities in global coords consists in adding 3 increments we have computed; in global coords (a is any vector) 1. +relShearVel*scene->dt; // mutual motion of the contact 2. -a.cross(normRotVec); // rigid rotation perpendicular to the normal 3. -a.cross(normTwistVec); // rigid rotation parallel to the normal */ // compute current transformation, by updating previous axes // the X axis can be prescribed directly (copy of normal) // the mutual motion on the contact does not change transformation #ifdef L3_TRSF_QUATERNION const Matrix3r prevTrsf(g.trsf.toRotationMatrix()); Quaternionr prevTrsfQ(g.trsf); #else const Matrix3r prevTrsf(g.trsf); // could be reference perhaps, but we need it to compute midTrsf (if applicable) #endif Matrix3r currTrsf; currTrsf.row(0)=currNormal; for(int i=1; i<3; i++){ currTrsf.row(i)=prevTrsf.row(i)-prevTrsf.row(i).cross(normRotVec)-prevTrsf.row(i).cross(normTwistVec); } #ifdef L3_TRSF_QUATERNION Quaternionr currTrsfQ(currTrsf); if((scene->iter % trsfRenorm)==0 && trsfRenorm>0) currTrsfQ.normalize(); #else if((scene->iter % trsfRenorm)==0 && trsfRenorm>0){ #if 1 currTrsf.row(0).normalize(); currTrsf.row(1)-=currTrsf.row(0)*currTrsf.row(1).dot(currTrsf.row(0)); // take away y projected on x, to stabilize numerically currTrsf.row(1).normalize(); currTrsf.row(2)=currTrsf.row(0).cross(currTrsf.row(1)); currTrsf.row(2).normalize(); #else currTrsf=Matrix3r(Quaternionr(currTrsf).normalized()); #endif #ifdef YADE_DEBUG if(abs(currTrsf.determinant()-1)>.05){ LOG_ERROR("##"<<I->getId1()<<"+"<<I->getId2()<<", |trsf|="<<currTrsf.determinant()); g.trsf=currTrsf; throw runtime_error("Transformation matrix far from orthonormal."); } #endif } #endif /* Previous local trsf u'⁻ must be updated to current u'⁰. We have transformation T⁻ and T⁰, δ(a) denotes increment of a as defined above. Two possibilities: 1. convert to global, update, convert back: T⁰(T⁻*(u'⁻)+δ(T⁻*(u'⁻))). Quite heavy. 2. update u'⁻ straight, using relShearVel in local coords; since relShearVel is computed at (t-Δt/2), we would have to find intermediary transformation (same axis, half angle; the same as slerp at t=.5 between the two). This could be perhaps simplified by using T⁰ or T⁻ since they will not differ much, but it would have to be verified somehow. */ // if requested via approxMask, just use prevTrsf #ifdef L3_TRSF_QUATERNION Quaternionr midTrsf=(approxMask&APPROX_NO_MID_TRSF) ? prevTrsfQ : prevTrsfQ.slerp(.5,currTrsfQ); #else Quaternionr midTrsf=(approxMask&APPROX_NO_MID_TRSF) ? Quaternionr(prevTrsf) : Quaternionr(prevTrsf).slerp(.5,Quaternionr(currTrsf)); #endif //cerr<<"prevTrsf=\n"<<prevTrsf<<", currTrsf=\n"<<currTrsf<<", midTrsf=\n"<<Matrix3r(midTrsf)<<endl; // updates of geom here // midTrsf*relShearVel should have the 0-th component (approximately) zero -- to be checked g.u+=midTrsf*relShearDu; //cerr<<"midTrsf=\n"<<midTrsf<<",relShearDu="<<relShearDu<<", transformed "<<midTrsf*relShearDu<<endl; g.u[0]=uN; // this does not have to be computed incrementally #ifdef L3_TRSF_QUATERNION g.trsf=currTrsfQ; #else g.trsf=currTrsf; #endif // GenericSpheresContact g.refR1=r1; g.refR2=r2; g.normal=currNormal; g.contactPoint=contPt; if(is6Dof){ // update phi, from the difference of angular velocities // the difference is transformed to local coord using the midTrsf transformation // perhaps not consistent when spheres have different radii (depends how bending moment is computed) I->geom->cast<L6Geom>().phi+=midTrsf*(scene->dt*(state2.angVel-state1.angVel)); } };
static int stmsmi_probe(struct flash_bank *bank) { struct target *target = bank->target; struct stmsmi_flash_bank *stmsmi_info = bank->driver_priv; uint32_t io_base; struct flash_sector *sectors; uint32_t id = 0; /* silence uninitialized warning */ struct stmsmi_target *target_device; int retval; if (stmsmi_info->probed) free(bank->sectors); stmsmi_info->probed = 0; for (target_device=target_devices ; target_device->name ; ++target_device) if (target_device->tap_idcode == target->tap->idcode) break; if (!target_device->name) { LOG_ERROR("Device ID 0x%" PRIx32 " is not known as SMI capable", target->tap->idcode); return ERROR_FAIL; } switch (bank->base - target_device->smi_base) { case 0: stmsmi_info->bank_num = SMI_SEL_BANK0; break; case SMI_BANK_SIZE: stmsmi_info->bank_num = SMI_SEL_BANK1; break; case 2*SMI_BANK_SIZE: stmsmi_info->bank_num = SMI_SEL_BANK2; break; case 3*SMI_BANK_SIZE: stmsmi_info->bank_num = SMI_SEL_BANK3; break; default: LOG_ERROR("Invalid SMI base address 0x%" PRIx32, bank->base); return ERROR_FAIL; } io_base = target_device->io_base; stmsmi_info->io_base = io_base; LOG_DEBUG("Valid SMI on device %s at address 0x%" PRIx32, target_device->name, bank->base); /* read and decode flash ID; returns in SW mode */ retval = read_flash_id(bank, &id); SMI_SET_HW_MODE(); if (retval != ERROR_OK) return retval; stmsmi_info->dev = NULL; for (struct flash_device *p = flash_devices; p->name ; p++) if (p->device_id == id) { stmsmi_info->dev = p; break; } if (!stmsmi_info->dev) { LOG_ERROR("Unknown flash device (ID 0x%08" PRIx32 ")", id); return ERROR_FAIL; } LOG_INFO("Found flash device \'%s\' (ID 0x%08" PRIx32 ")", stmsmi_info->dev->name, stmsmi_info->dev->device_id); /* Set correct size value */ bank->size = stmsmi_info->dev->size_in_bytes; /* create and fill sectors array */ bank->num_sectors = stmsmi_info->dev->size_in_bytes / stmsmi_info->dev->sectorsize; sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors); if (sectors == NULL) { LOG_ERROR("not enough memory"); return ERROR_FAIL; } for (int sector = 0; sector < bank->num_sectors; sector++) { sectors[sector].offset = sector * stmsmi_info->dev->sectorsize; sectors[sector].size = stmsmi_info->dev->sectorsize; sectors[sector].is_erased = -1; sectors[sector].is_protected = 1; } bank->sectors = sectors; stmsmi_info->probed = 1; return ERROR_OK; }
/** * Save processor state. This is called after a HALT instruction * succeeds, and on other occasions the processor enters debug mode * (breakpoint, watchpoint, etc). Caller has updated arm11->dscr. */ static int arm11_debug_entry(struct arm11_common *arm11) { int retval; arm11->arm.target->state = TARGET_HALTED; arm_dpm_report_dscr(arm11->arm.dpm, arm11->dscr); /* REVISIT entire cache should already be invalid !!! */ register_cache_invalidate(arm11->arm.core_cache); /* See e.g. ARM1136 TRM, "14.8.4 Entering Debug state" */ /* maybe save wDTR (pending DCC write to debug SW, e.g. libdcc) */ arm11->is_wdtr_saved = !!(arm11->dscr & DSCR_DTR_TX_FULL); if (arm11->is_wdtr_saved) { arm11_add_debug_SCAN_N(arm11, 0x05, ARM11_TAP_DEFAULT); arm11_add_IR(arm11, ARM11_INTEST, ARM11_TAP_DEFAULT); struct scan_field chain5_fields[3]; arm11_setup_field(arm11, 32, NULL, &arm11->saved_wdtr, chain5_fields + 0); arm11_setup_field(arm11, 1, NULL, NULL, chain5_fields + 1); arm11_setup_field(arm11, 1, NULL, NULL, chain5_fields + 2); arm11_add_dr_scan_vc(ARRAY_SIZE(chain5_fields), chain5_fields, TAP_DRPAUSE); } /* DSCR: set the Execute ARM instruction enable bit. * * ARM1176 spec says this is needed only for wDTR/rDTR's "ITR mode", * but not to issue ITRs(?). The ARMv7 arch spec says it's required * for executing instructions via ITR. */ arm11_write_DSCR(arm11, DSCR_ITR_EN | arm11->dscr); /* From the spec: Before executing any instruction in debug state you have to drain the write buffer. This ensures that no imprecise Data Aborts can return at a later point:*/ /** \todo TODO: Test drain write buffer. */ #if 0 while (1) { /* MRC p14,0,R0,c5,c10,0 */ // arm11_run_instr_no_data1(arm11, /*0xee150e1a*/0xe320f000); /* mcr 15, 0, r0, cr7, cr10, {4} */ arm11_run_instr_no_data1(arm11, 0xee070f9a); uint32_t dscr = arm11_read_DSCR(arm11); LOG_DEBUG("DRAIN, DSCR %08x", dscr); if (dscr & ARM11_DSCR_STICKY_IMPRECISE_DATA_ABORT) { arm11_run_instr_no_data1(arm11, 0xe320f000); dscr = arm11_read_DSCR(arm11); LOG_DEBUG("DRAIN, DSCR %08x (DONE)", dscr); break; } } #endif /* Save registers. * * NOTE: ARM1136 TRM suggests saving just R0 here now, then * CPSR and PC after the rDTR stuff. We do it all at once. */ retval = arm_dpm_read_current_registers(&arm11->dpm); if (retval != ERROR_OK) LOG_ERROR("DPM REG READ -- fail %d", retval); retval = arm11_run_instr_data_prepare(arm11); if (retval != ERROR_OK) return retval; /* maybe save rDTR (pending DCC read from debug SW, e.g. libdcc) */ arm11->is_rdtr_saved = !!(arm11->dscr & DSCR_DTR_RX_FULL); if (arm11->is_rdtr_saved) { /* MRC p14,0,R0,c0,c5,0 (move rDTR -> r0 (-> wDTR -> local var)) */ retval = arm11_run_instr_data_from_core_via_r0(arm11, 0xEE100E15, &arm11->saved_rdtr); if (retval != ERROR_OK) return retval; } /* REVISIT Now that we've saved core state, there's may also * be MMU and cache state to care about ... */ if (arm11->simulate_reset_on_next_halt) { arm11->simulate_reset_on_next_halt = false; LOG_DEBUG("Reset c1 Control Register"); /* Write 0 (reset value) to Control register 0 to disable MMU/Cache etc. */ /* MCR p15,0,R0,c1,c0,0 */ retval = arm11_run_instr_data_to_core_via_r0(arm11, 0xee010f10, 0); if (retval != ERROR_OK) return retval; } if (arm11->arm.target->debug_reason == DBG_REASON_WATCHPOINT) { uint32_t wfar; /* MRC p15, 0, <Rd>, c6, c0, 1 ; Read WFAR */ retval = arm11_run_instr_data_from_core_via_r0(arm11, ARMV4_5_MRC(15, 0, 0, 6, 0, 1), &wfar); if (retval != ERROR_OK) return retval; arm_dpm_report_wfar(arm11->arm.dpm, wfar); } retval = arm11_run_instr_data_finish(arm11); if (retval != ERROR_OK) return retval; return ERROR_OK; }
SocketServer::SocketServer( int port, bool blocking, bool broadcast, OnConnect onConnect, OnDisconnect onDisconnect, OnNetworkMessage onData) : m_port{ port } , m_broadcasting{ broadcast } , m_alive{ true } , m_onConnect{ onConnect } , m_onDisconnect{ onDisconnect } , m_onData{ onData } , m_serverSocketParser{ m_onData } { // initialize networking SocketSystemInitialization::instance().initialize(); m_serverSocket = Socket::createSocket(port, "", !broadcast ? SocketType::TCP : SocketType::UDP); if (m_serverSocket->m_socket == INVALID_SOCKET) { LOG_ERROR("Could not open socket"); return; } m_serverSocket->enableSocketReuse(); m_serverSocket->enableNoDelay(); if(!blocking) m_serverSocket->enableNonBlockingSocket(); auto res = m_serverSocket->bind(); if (res == SOCKET_ERROR) { LOG_ERROR("Could not bind socket"); return; } listen(m_serverSocket->m_socket, 1024); LOG_INFO("SocketServer started on host: %s, ip: %s", Socket::localHostname().c_str(), Socket::localIp().c_str()); if (!blocking) { m_work = std::move(std::unique_ptr<std::thread, std::function<void(std::thread*)>>(new std::thread( // task [&]() { run(m_mutex); }), // deleter [&](std::thread* ptr) { { std::lock_guard<std::mutex> m(m_mutex); m_alive = false; } ptr->join(); delete ptr; })); if (!SetThreadPriority(m_work->native_handle(), THREAD_PRIORITY_HIGHEST)) { LOG_ERROR("Could not set thread priority"); } } else run(m_mutex); m_closingDownMessage = std::unique_ptr<char, std::function<void(char*)>>(new char(), [](char* ptr) { LOG_INFO("SocketServer stopped"); delete ptr; }); }
/* talk to the target and set things up */ static int arm11_examine(struct target *target) { int retval; char *type; struct arm11_common *arm11 = target_to_arm11(target); uint32_t didr, device_id; uint8_t implementor; /* FIXME split into do-first-time and do-every-time logic ... */ /* check IDCODE */ arm11_add_IR(arm11, ARM11_IDCODE, ARM11_TAP_DEFAULT); struct scan_field idcode_field; arm11_setup_field(arm11, 32, NULL, &device_id, &idcode_field); arm11_add_dr_scan_vc(1, &idcode_field, TAP_DRPAUSE); /* check DIDR */ arm11_add_debug_SCAN_N(arm11, 0x00, ARM11_TAP_DEFAULT); arm11_add_IR(arm11, ARM11_INTEST, ARM11_TAP_DEFAULT); struct scan_field chain0_fields[2]; arm11_setup_field(arm11, 32, NULL, &didr, chain0_fields + 0); arm11_setup_field(arm11, 8, NULL, &implementor, chain0_fields + 1); arm11_add_dr_scan_vc(ARRAY_SIZE(chain0_fields), chain0_fields, TAP_IDLE); CHECK_RETVAL(jtag_execute_queue()); /* assume the manufacturer id is ok; check the part # */ switch ((device_id >> 12) & 0xFFFF) { case 0x7B36: type = "ARM1136"; break; case 0x7B37: type = "ARM11 MPCore"; break; case 0x7B56: type = "ARM1156"; break; case 0x7B76: arm11->arm.core_type = ARM_MODE_MON; type = "ARM1176"; break; default: LOG_ERROR("unexpected ARM11 ID code"); return ERROR_FAIL; } LOG_INFO("found %s", type); /* unlikely this could ever fail, but ... */ switch ((didr >> 16) & 0x0F) { case ARM11_DEBUG_V6: case ARM11_DEBUG_V61: /* supports security extensions */ break; default: LOG_ERROR("Only ARM v6 and v6.1 debug supported."); return ERROR_FAIL; } arm11->brp = ((didr >> 24) & 0x0F) + 1; /** \todo TODO: reserve one brp slot if we allow breakpoints during step */ arm11->free_brps = arm11->brp; LOG_DEBUG("IDCODE %08" PRIx32 " IMPLEMENTOR %02x DIDR %08" PRIx32, device_id, implementor, didr); /* as a side-effect this reads DSCR and thus * clears the ARM11_DSCR_STICKY_PRECISE_DATA_ABORT / Sticky Precise Data Abort Flag * as suggested by the spec. */ retval = arm11_check_init(arm11); if (retval != ERROR_OK) return retval; /* Build register cache "late", after target_init(), since we * want to know if this core supports Secure Monitor mode. */ if (!target_was_examined(target)) retval = arm11_dpm_init(arm11, didr); /* ETM on ARM11 still uses original scanchain 6 access mode */ if (arm11->arm.etm && !target_was_examined(target)) { *register_get_last_cache_p(&target->reg_cache) = etm_build_reg_cache(target, &arm11->jtag_info, arm11->arm.etm); retval = etm_setup(target); } target_set_examined(target); return ERROR_OK; }
PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getSVGPropertyCSSValue(int propertyID, EUpdateLayout updateLayout) const { Node* node = m_node.get(); if (!node) return 0; // Make sure our layout is up to date before we allow a query on these attributes. if (updateLayout) node->document()->updateLayout(); RenderStyle* style = node->computedStyle(); if (!style) return 0; const SVGRenderStyle* svgStyle = style->svgStyle(); if (!svgStyle) return 0; switch (static_cast<CSSPropertyID>(propertyID)) { case CSSPropertyClipRule: return CSSPrimitiveValue::create(svgStyle->clipRule()); case CSSPropertyFloodOpacity: return CSSPrimitiveValue::create(svgStyle->floodOpacity(), CSSPrimitiveValue::CSS_NUMBER); case CSSPropertyStopOpacity: return CSSPrimitiveValue::create(svgStyle->stopOpacity(), CSSPrimitiveValue::CSS_NUMBER); case CSSPropertyColorInterpolation: return CSSPrimitiveValue::create(svgStyle->colorInterpolation()); case CSSPropertyColorInterpolationFilters: return CSSPrimitiveValue::create(svgStyle->colorInterpolationFilters()); case CSSPropertyFillOpacity: return CSSPrimitiveValue::create(svgStyle->fillOpacity(), CSSPrimitiveValue::CSS_NUMBER); case CSSPropertyFillRule: return CSSPrimitiveValue::create(svgStyle->fillRule()); case CSSPropertyColorRendering: return CSSPrimitiveValue::create(svgStyle->colorRendering()); case CSSPropertyImageRendering: return CSSPrimitiveValue::create(svgStyle->imageRendering()); case CSSPropertyShapeRendering: return CSSPrimitiveValue::create(svgStyle->shapeRendering()); case CSSPropertyStrokeLinecap: return CSSPrimitiveValue::create(svgStyle->capStyle()); case CSSPropertyStrokeLinejoin: return CSSPrimitiveValue::create(svgStyle->joinStyle()); case CSSPropertyStrokeMiterlimit: return CSSPrimitiveValue::create(svgStyle->strokeMiterLimit(), CSSPrimitiveValue::CSS_NUMBER); case CSSPropertyStrokeOpacity: return CSSPrimitiveValue::create(svgStyle->strokeOpacity(), CSSPrimitiveValue::CSS_NUMBER); case CSSPropertyAlignmentBaseline: return CSSPrimitiveValue::create(svgStyle->alignmentBaseline()); case CSSPropertyDominantBaseline: return CSSPrimitiveValue::create(svgStyle->dominantBaseline()); case CSSPropertyTextAnchor: return CSSPrimitiveValue::create(svgStyle->textAnchor()); case CSSPropertyWritingMode: return CSSPrimitiveValue::create(svgStyle->writingMode()); case CSSPropertyClipPath: if (!svgStyle->clipPath().isEmpty()) return CSSPrimitiveValue::create(svgStyle->clipPath(), CSSPrimitiveValue::CSS_URI); return CSSPrimitiveValue::createIdentifier(CSSValueNone); case CSSPropertyMask: if (!svgStyle->maskElement().isEmpty()) return CSSPrimitiveValue::create(svgStyle->maskElement(), CSSPrimitiveValue::CSS_URI); return CSSPrimitiveValue::createIdentifier(CSSValueNone); case CSSPropertyFilter: if (!svgStyle->filter().isEmpty()) return CSSPrimitiveValue::create(svgStyle->filter(), CSSPrimitiveValue::CSS_URI); return CSSPrimitiveValue::createIdentifier(CSSValueNone); case CSSPropertyFloodColor: return CSSPrimitiveValue::createColor(svgStyle->floodColor().rgb()); case CSSPropertyLightingColor: return CSSPrimitiveValue::createColor(svgStyle->lightingColor().rgb()); case CSSPropertyStopColor: return CSSPrimitiveValue::createColor(svgStyle->stopColor().rgb()); case CSSPropertyFill: return svgStyle->fillPaint(); case CSSPropertyKerning: return svgStyle->kerning(); case CSSPropertyMarkerEnd: if (!svgStyle->endMarker().isEmpty()) return CSSPrimitiveValue::create(svgStyle->endMarker(), CSSPrimitiveValue::CSS_URI); return CSSPrimitiveValue::createIdentifier(CSSValueNone); case CSSPropertyMarkerMid: if (!svgStyle->midMarker().isEmpty()) return CSSPrimitiveValue::create(svgStyle->midMarker(), CSSPrimitiveValue::CSS_URI); return CSSPrimitiveValue::createIdentifier(CSSValueNone); case CSSPropertyMarkerStart: if (!svgStyle->startMarker().isEmpty()) return CSSPrimitiveValue::create(svgStyle->startMarker(), CSSPrimitiveValue::CSS_URI); return CSSPrimitiveValue::createIdentifier(CSSValueNone); case CSSPropertyStroke: return svgStyle->strokePaint(); case CSSPropertyStrokeDasharray: return svgStyle->strokeDashArray(); case CSSPropertyStrokeDashoffset: return svgStyle->strokeDashOffset(); case CSSPropertyStrokeWidth: return svgStyle->strokeWidth(); case CSSPropertyBaselineShift: { switch (svgStyle->baselineShift()) { case BS_BASELINE: return CSSPrimitiveValue::createIdentifier(CSSValueBaseline); case BS_SUPER: return CSSPrimitiveValue::createIdentifier(CSSValueSuper); case BS_SUB: return CSSPrimitiveValue::createIdentifier(CSSValueSub); case BS_LENGTH: return svgStyle->baselineShiftValue(); } } case CSSPropertyGlyphOrientationHorizontal: return glyphOrientationToCSSPrimitiveValue(svgStyle->glyphOrientationHorizontal()); case CSSPropertyGlyphOrientationVertical: { if (RefPtr<CSSPrimitiveValue> value = glyphOrientationToCSSPrimitiveValue(svgStyle->glyphOrientationVertical())) return value.release(); if (svgStyle->glyphOrientationVertical() == GO_AUTO) return CSSPrimitiveValue::createIdentifier(CSSValueAuto); return 0; } case CSSPropertyWebkitSvgShadow: return valueForShadow(svgStyle->shadow(), propertyID); case CSSPropertyMarker: case CSSPropertyEnableBackground: case CSSPropertyColorProfile: // the above properties are not yet implemented in the engine break; default: // If you crash here, it's because you added a css property and are not handling it // in either this switch statement or the one in CSSComputedStyleDelcaration::getPropertyCSSValue ASSERT_WITH_MESSAGE(0, "unimplemented propertyID: %d", propertyID); } LOG_ERROR("unimplemented propertyID: %d", propertyID); return 0; }
bool rConsoleRead(const std::string& prompt, bool addToHistory, rstudio::r::session::RConsoleInput* pConsoleInput) { // this is an invalid state in a forked (multicore) process if (main_process::wasForked()) { LOG_WARNING_MESSAGE("rConsoleRead called in forked processs"); return false; } // r is not processing input setExecuting(false); if (!s_consoleInputBuffer.empty()) { *pConsoleInput = s_consoleInputBuffer.front(); s_consoleInputBuffer.pop(); } // otherwise prompt and wait for console_input from the client else { // fire console_prompt event (unless we are just starting up, in which // case we will either prompt as part of the response to client_init or // we shouldn't prompt at all because we are resuming a suspended session) if (init::isSessionInitialized()) consolePrompt(prompt, addToHistory); // wait for console_input json::JsonRpcRequest request ; bool succeeded = http_methods::waitForMethod( kConsoleInput, boost::bind(consolePrompt, prompt, addToHistory), boost::bind(canSuspend, prompt), &request); // exit process if we failed if (!succeeded) return false; // extract console input. if there is an error during extraction we log it // but still return and empty string and true (returning false will cause R // to abort) Error error = extractConsoleInput(request); if (error) { LOG_ERROR(error); *pConsoleInput = rstudio::r::session::RConsoleInput("", ""); } *pConsoleInput = s_consoleInputBuffer.front(); s_consoleInputBuffer.pop(); } // fire onBeforeExecute and onConsoleInput events if this isn't a cancel if (!pConsoleInput->cancel) { module_context::events().onBeforeExecute(); module_context::events().onConsoleInput(pConsoleInput->text); } // we are about to return input to r so set the flag indicating that state setExecuting(true); // ensure that output resulting from this input goes to the correct console if (clientEventQueue().setActiveConsole(pConsoleInput->console)) { module_context::events().onActiveConsoleChanged(pConsoleInput->console, pConsoleInput->text); } ClientEvent promptEvent(client_events::kConsoleWritePrompt, prompt); clientEventQueue().add(promptEvent); enqueueConsoleInput(*pConsoleInput); // always return true (returning false causes the process to exit) return true; }