bool GLShader::ValidateCompile(GLuint shader) { GLint compiled; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLsizei length; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); /*output shader log info*/ GLchar* log = new GLchar[length + 1]; glGetShaderInfoLog(shader, length, &length, log); #ifdef UNICODE std::string log_text(log); UConverter converter; UString log_string = converter.from_bytes(log_text); DebugPrintF(log_string.c_str()); std::cout << log << std::endl; #else DebugPrintF(VTEXT("Shader Log: %s\n"), log); #endif delete[] log; return false; } return true; }
static FILE *hsysGetRealFileHandle(hsys_state *stateptr, int fh, char *flags) { FILE *file_p = NULL; if (fh < 0 || fh >= HSYS_FOPEN_MAX) { stateptr->last_errno = EBADF; DebugPrintF(("\tfh %d out-of-bounds!\n", fh)); return NULL; } else { file_p = stateptr->OSptr->FileTable[fh]; if (file_p != NULL) { if (flags != NULL) *flags = stateptr->OSptr->FileFlags[fh]; } else { stateptr->last_errno = EBADF; DebugPrintF(("\tFileTable[%d] is NULL\n", fh)); } return file_p; } }
bool SDLGameWindow::VInit() { /* Initialize SDL */ if (SDL_Init(SDL_INIT_TIMER) != 0) { DebugPrintF(VTEXT("SDL Failed to Initialize")); return false; } /*Create the SDL_Window handle*/ #ifdef UNICODE UConverter convert; std::string title = convert.to_bytes(m_params.title); #else std::string title = m_params.title; #endif m_windowHandle = SDL_CreateWindow(title.c_str(), m_params.x <= 0 ? SDL_WINDOWPOS_CENTERED : m_params.x, m_params.y <= 0 ? SDL_WINDOWPOS_CENTERED : m_params.y, m_params.width, m_params.height, SDL_WINDOW_OPENGL); if (!m_windowHandle) { SDL_Quit(); DebugPrintF(VTEXT("Failed to created SDL_Window handle")); return false; } #ifdef VIX_SYS_WINDOWS SDL_SysWMinfo info; SDL_VERSION(&info.version); if (SDL_GetWindowWMInfo(m_windowHandle, &info)) { m_nativeHandle = info.info.win.window; if (m_renderer) m_renderer->VAttachNativeHandle(m_nativeHandle); } #endif #ifdef VIX_SYS_LINUX //for now SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); /*create OpenGL context*/ m_context = SDL_GL_CreateContext(m_windowHandle); if (!m_context) { SDL_Quit(); DebugPrintF(VTEXT("Failed to create SDL_GL_Context handle")); return false; } #endif if (m_renderer && !m_renderer->VInitialize()) { DebugPrintF(VTEXT("Renderer failed to initialize")); return false; } return true; }
bool SDLGameWindow::VInit() { /* Initialize SDL */ if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { DebugPrintF(VTEXT("SDL Failed to Initialize")); return false; } /*Create the SDL_Window handle*/ #ifdef UNICODE UConverter convert; std::string title = convert.to_bytes(m_params.title); #else std::string title = m_params.title; #endif m_windowHandle = SDL_CreateWindow(title.c_str(), m_params.x <= 0 ? SDL_WINDOWPOS_CENTERED : m_params.x, m_params.y <= 0 ? SDL_WINDOWPOS_CENTERED : m_params.y, m_params.width, m_params.height, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN); if (!m_windowHandle) { SDL_Quit(); DebugPrintF(VTEXT("Failed to created SDL_Window handle")); return false; } #ifdef VIX_SYS_WINDOWS SDL_SysWMinfo info; SDL_VERSION(&info.version); if (SDL_GetWindowWMInfo(m_windowHandle, &info)) { m_nativeHandle = info.info.win.window; } #endif #ifdef VIX_SYS_LINUX //for now SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); /*create OpenGL context*/ m_context = SDL_GL_CreateContext(m_windowHandle); if (!m_context) { SDL_Quit(); DebugPrintF(VTEXT("Failed to create SDL_GL_Context handle")); return false; } #endif m_mouseState = new SDLMouseState; m_keyboardState = new SDLKeyboardState; m_controllerState = new SDLControllerState; m_running = true; return true; }
void ResourceManager::PrintLoaded() { ResourceManager& _RM = ResourceManager::instance(); for (auto& asset : _RM.m_assetMap) { Asset* _asset = asset.second; if (_asset) { DebugPrintF(VTEXT("File: %s\n"), _asset->FileName().c_str()); DebugPrintF(VTEXT("RefCount: %d\n"), _asset->RefCount()); } } }
/* * Sends the real data in the current connection's virtual buffer */ void send() { uip_tcp_appstate_t *app = &(uip_conn->appstate); // Find the intersection of the virtual buffer and the real uip buffer int len = (int)app->cursor - app->ackedCount; len = len < 0 ? 0 : len; len = len > (int)uip_conn->mss ? (int)uip_conn->mss : len; #ifdef DEBUG DebugPrintFO(f_tx); // Serial.print("-->TX "); Serial.print(len); DebugPrintF (f_bytes); // Serial.print (" bytes"); Serial.print(app->ackedCount); DebugPrintFO(f_hyphen); // Serial.print(" - "); Serial.print(app->ackedCount + len - 1); DebugPrintFO(f_of); // Serial.print(" of "); Serial.print((int)app->cursor); DebugPrint((char *)""); #endif // DEBUG // Send the real bytes from the virtual buffer and record how many were sent uip_send(uip_appdata, len); app->sentCount = len; setTXPin(HIGH); }
void Server::init(pageServingFunction function) { #ifdef DEBUG DebugPrintF(f_wic); // "\nWiServer init called" #endif // DEBUG // Store the callback function for serving pages callbackFunc = function; }
bool GLShader::VInitFromFile(const UString& path) { /*grab source from file*/ const GLchar* source = ReadShader(path); if (!source) { DebugPrintF(VTEXT("Failed to parse shader source\n")); return false; } if (!LoadShader(source)) { DebugPrintF(VTEXT("Failed to init shader from file\n")); return false; } return true; }
BMFont* ContentManager::LoadFont(const UString& path) { if (path.empty()) { DebugPrintF(VTEXT("Error Loading [BMFont]")); return NULL; } UString _path = os_path(FONT_FOLDER_PATH + path); UString _texPath = os_path(FONT_FOLDER_PATH + TEX_FOLDER_PATH); ContentMap::iterator it = m_fonts.find(_path); if (it != m_fonts.end()) { return (BMFont*)it->second; } else { /*create new font*/ BMFont* font = new BMFont(_path); /*load textures for font*/ for (auto& page : font->FontFile().pages) { Texture* tex = LoadTexture(_texPath + page.file); if (tex) font->AddPageTexture(tex); } m_fonts[_path] = (IContent*)font; return font; } return NULL; }
const GLchar* GLShader::ReadShader(const UString& path) { FILE* file; #if defined VIX_SYS_WINDOWS && defined UNICODE _wfopen_s(&file, path.c_str(), VTEXT("rb")); #else file = fopen(path.c_str(), VTEXT("rb")); #endif if (!file) { DebugPrintF(VTEXT("Unabled to read shader: %s\n"), ErrCodeString(ErrCode::ERR_FAILURE).c_str()); return NULL; } /*seek end of file*/ fseek(file, 0, SEEK_END); /*cache length*/ size_t len = ftell(file); /*seek beg of file*/ fseek(file, 0, SEEK_SET); /*buffer source*/ GLchar* src = new GLchar[len + 1]; /*read file contents into buffer*/ fread(src, 1, len, file); /*close file after read*/ fclose(file); /*null terminate*/ src[len] = 0; return src; }
void ContentManager::DumpTextures() { for (auto& tex : m_textures) { Texture* _tex = (Texture*)tex.second; DebugPrintF(VTEXT("Texture [%s]\n"), _tex->name().c_str()); } }
void setup() { ExpatBase = OpenLibrary("expat.library", 4); IExpat = (struct ExpatIFace*)GetInterface(ExpatBase, "main", 1, NULL); if ( IExpat == 0 ) { DebugPrintF("Can't open expat.library\n"); } }
ErrCode LuaEngine::VExecuteFile(const UString& path) { ErrCode error = ErrCode::ERR_SUCCESS; if (path.empty()) { DebugPrintF(VTEXT("Failed to execute script file: NULL PATH")); return ErrCode::ERR_NULL_PATH; } /*try and execute script file*/ std::string _path = UStringToStd(path); int state = luaL_dofile(m_L, _path.c_str()); error = ReportScriptErrors(state); if (CheckError(error)) { DebugPrintF(VTEXT("Failed to execute script file")); } return error; }
bool LuaEngine::ExecuteExpression(UString expression) { LuaEngine& _engine = LuaEngine::instance(); if (expression.empty()) { DebugPrintF(VTEXT("SCRIPT EMPTY")); return false; } std::string _exp = UStringToStd(expression); int state = luaL_dostring(_engine.m_L, _exp.c_str()); if (!ReportScriptErrors(state)) { DebugPrintF(VTEXT("Failed to execute script expression")); return false; } return true; }
ErrCode LuaEngine::VExecuteExpression(const UString& expression) { ErrCode error = ErrCode::ERR_SUCCESS; if (expression.empty()) { DebugPrintF(VTEXT("SCRIPT EMPTY")); return ErrCode::ERR_NULL_PATH; } std::string _exp = UStringToStd(expression); int state = luaL_dostring(m_L, _exp.c_str()); error = ReportScriptErrors(state); if (CheckError(error)) { DebugPrintF(VTEXT("Failed to execute script expression")); } return error; }
void SDLGameWindow::OutputDisplayModes() { int numModes = SDL_GetNumDisplayModes(0); for (int i = 0; i < numModes; i++) { SDL_DisplayMode mode; SDL_GetDisplayMode(0, i, &mode); DebugPrintF(VTEXT("DisplayMode[%i]: <W: %i, H: %i>\n"), i, mode.w, mode.h); } }
bool LuaEngine::ExecuteFile(UString filePath) { LuaEngine& _engine = LuaEngine::instance(); if (filePath.empty()) { DebugPrintF(VTEXT("Failed to execute script file: NULL PATH")); return false; } /*try and execute script file*/ std::string _path = UStringToStd(filePath); int state = luaL_dofile(_engine.m_L, _path.c_str()); if (!LuaEngine::ReportScriptErrors(state)) { DebugPrintF(VTEXT("Failed to execute script file")); return false; } return true; }
GLTexture::GLTexture(const UString& filePath, GLenum target /* = GL_TEXTURE_2D */) { m_width = 0; m_height = 0; m_target = target; ErrCode error = InitFromFile(filePath); if (CheckError(error)) { DebugPrintF(VTEXT("Texture failed to initialize")); } }
ErrCode AudioManager::VShutDown() { ErrCode error = ErrCode::ERR_SUCCESS; DebugPrintF(VTEXT("AudioManager shutting down...")); /*close sound system*/ error = FMOD_CheckError(m_system->close()); /*release sound system*/ error = FMOD_CheckError(m_system->release()); return error; }
ErrCode LuaEngine::ReportScriptErrors(int state) { if (state != 0) { const char* err = lua_tostring(m_L, state); DebugPrintF(VTEXT("Lua Script Error: %s"), UStringFromCharArray(err).c_str()); lua_pop(m_L, 1); //remove error return ErrCode::ERR_FAILURE; } return ErrCode::ERR_SUCCESS; }
GLShader::GLShader(const ShaderInfo& info) { m_info = info; if (m_info.filePath.empty() && m_info.raw.empty()) { /*no file or raw contents avaliable for loading*/ DebugPrintF(VTEXT("Shader creation failed: %s\n"), VTEXT("No shader path or raw contents avaliable")); } /*determine if shader should load from file or raw contents*/ bool success; if (!m_info.filePath.empty()) { success = VInitFromFile(m_info.filePath); } else { success = VInitFromString(m_info.raw); } if (!success) { DebugPrintF(VTEXT("Shader creation failed\n")); } }
void Server::submitRequest(GETrequest *req) { // Check for an empty queue if (queue == NULL) { // Point to the new request queue = req; #ifdef DEBUG DebugPrintF(f_ngr); // JM - new GET/POSTrequest #endif } else { // Find the tail of the queue GETrequest* r = queue; while (r->next != NULL) { r = r->next; } // Append the new request r->next = req; #ifdef DEBUG DebugPrintF(f_qgr); // JM - queue GETrequest #endif } // Set the request as being active req->active = true; }
bool LuaEngine::ReportScriptErrors(int state) { LuaEngine& _engine = LuaEngine::instance(); if (state != 0) { const char* err = lua_tostring(_engine.m_L, state); if (err) { DebugPrintF(VTEXT("Lua Script Error: %s"), UStringFromCharArray(err).c_str()); lua_pop(_engine.m_L, 1); //remove error } return false; } return true; }
ErrCode AudioManager::VStartUp() { ErrCode error = ErrCode::ERR_SUCCESS; DebugPrintF(VTEXT("AudioManager starting up...")); /*create fmod sound system*/ error = FMOD_CheckError(FMOD::System_Create(&m_system)); if (CheckError(error)) return error; /*initialize fmod sound system*/ error = FMOD_CheckError(m_system->init(MAX_CHANNELS, FMOD_INIT_NORMAL, NULL)); if (CheckError(error)) return error; return error; }
bool GLShader::VInitFromString(const UString& path) { #if defined UNICODE && defined VIX_SYS_WINDOWS UConverter cv; std::string _source = cv.to_bytes(m_info.raw.c_str()); const GLchar* source = _source.c_str(); #else const GLchar* source = (const GLchar*)m_info.raw.c_str(); #endif if (!LoadShader(source)) { if (CheckError(error)) { DebugPrintF(VTEXT("Failed to init shader from source\n")); return true; } } return false; }
bool GLShader::LoadShader(const GLchar* source) { GLenum type = GLShaderType(m_info.type); if (type == GL_NONE) { DebugPrintF(VTEXT("Failed to Load Shader due to invalid type\n")); return false; } /*create shader object*/ m_shader = glCreateShader(type); /*put shader source into memory*/ glShaderSource(m_shader, 1, &source, NULL); /*cleanup allocated source*/ /*compile shader*/ glCompileShader(m_shader); return ValidateCompile(m_shader); }
void _DBPRINTF(const char *format, ...) { va_list args; va_start(args, format); { #if defined(__MORPHOS__) VNewRawDoFmt(format, (APTR)RAWFMTFUNC_SERIAL, NULL, args); #elif defined(__amigaos4__) static char buf[1024]; vsnprintf(buf, 1024, format, args); DebugPrintF("%s", buf); #elif defined(__AROS__) vkprintf(format, args); #else KPutFmt(format, args); #endif } va_end(args); }
Texture* ContentManager::LoadTexture(const UString& path) { if (path.empty()) { DebugPrintF(VTEXT("Error Loading [Texture]")); return NULL; } UString _path = os_path(TEX_FOLDER_PATH + path); ContentMap::iterator it = m_textures.find(_path); if (it != m_textures.end()) { return (Texture*)it->second; } else { /*create new texture*/ Texture* texture = new GLTexture(_path); m_textures[_path] = (IContent*)texture; return texture; } return NULL; }
/* * Attempts to send the requested page for the current connection */ void sendPage() { // Reset the virtual buffer cursor uip_conn->appstate.cursor = 0; // Start off with an HTTP OK response header and a blank line WiServer.println_P(httpOK); WiServer.println(); // Call the application's 'sendPage' function and ask it to // generate the requested page content. if (!callbackFunc((char*)uip_conn->appstate.request)) { // The URL is not recognized by the sketch // Reset the cursor and overwrite the HTTP OK header with a 404 message uip_conn->appstate.cursor = 0; WiServer.println_P(httpNotFound); WiServer.println(); #ifdef DEBUG DebugPrintF(f_unf); // "URL Not Found"; #endif // DEBUG } // Send the 'real' bytes in the buffer send(); }
int HandleSysMessage(Packet *packet, hsys_state *stateptr) { unsigned int reason_code, mode, len, c, nbytes, nbtotal, nbtogo = 0; long posn, fl; char character; int err; /* Note: We must not free the buffer passed in as the callback handler */ /* expects to do this. Freeing any other buffers we have malloced */ /* ourselves is acceptable */ unsigned char *buffp = ((unsigned char *)BUFFERDATA(packet->pk_buffer))+16; /* buffp points to the parameters*/ /* the invidual messages, excluding*/ /* standard SYS fields (debugID, */ /* osinfo and reasoncode) */ unsigned char *buffhead = (unsigned char *)(packet->pk_buffer); int DebugID, OSInfo1, OSInfo2, count; const char* fmode[] = {"r","rb","r+","r+b", "w","wb","w+","w+b", "a","ab","a+","a+b", "r","r","r","r"} /* last 4 are illegal */ ; FILEHANDLE fh; /* fh is used as an index to the real file handle * in OSptr */ FILE *fhreal; unpack_message(BUFFERDATA(buffhead), "%w%w%w%w", &reason_code, &DebugID, &OSInfo1, &OSInfo2); /* Extract reason code from buffer. */ reason_code &= 0xFFFF; /* Strip away direction bit, OSInfo and */ /* DebugInfo fields. Will want to do some */ /* sort of validation on this later. */ switch(reason_code) { case CL_WriteC: /* Write a character to the terminal. */ /* byte data -> word status */ { #ifdef DEBUG int c = (int)(*buffp); printf("CL_WriteC: [%02x]>%c<", c, isprint(c) ? c : '.'); #endif stateptr->hostif->writec(stateptr->hostif->hostosarg, (int)(*buffp)); DevSW_FreePacket(packet); return msgsend(CI_CLIB,"%w%w%w%w%w", CL_WriteC|HtoT, DebugID, OSInfo1, OSInfo2, NoError); } case CL_Write0: /* Write a null terminated string to the terminal. */ { unpack_message(buffp, "%w", &len); DebugCheckNullTermString("CL_Write0", TRUE, len, buffp+4); stateptr->hostif->write(stateptr->hostif->hostosarg, (char *) buffp+4, len); DevSW_FreePacket(packet); return msgsend(CI_CLIB, "%w%w%w%w%w", CL_Write0|HtoT, DebugID, OSInfo1, OSInfo2, NoError); } case CL_ReadC: /* Read a byte from the terminal */ { DebugPrintF(("CL_ReadC: ")); DevSW_FreePacket(packet); character = stateptr->hostif->readc(stateptr->hostif->hostosarg); DebugPrintF(("\nCL_ReadC returning [%02x]>%c<\n", character, isprint(character) ? character : '.')); return msgsend(CI_CLIB, "%w%w%w%w%w%b", CL_ReadC|HtoT, DebugID, OSInfo1, OSInfo2, NoError, character); } case CL_System: /* Pass NULL terminated string to the hosts command * interpreter. As it is nULL terminated we dont need * the length */ { unpack_message(buffp, "%w", &len); DebugCheckNullTermString("CL_System", TRUE, len, buffp+4); err = system((char *)buffp+4); /* Use the string in the buffer */ stateptr->last_errno = errno; DebugCheckErr("system", TRUE, err, stateptr->last_errno); err = msgsend(CI_CLIB, "%w%w%w%w%w%w", CL_System|HtoT, DebugID, OSInfo1, OSInfo2, NoError, err); DevSW_FreePacket(packet); return err; } case CL_GetCmdLine: /* Returns the command line used to call the program */ { /* Note: we reuse the packet here, this may not always be desirable */ /* /* TODO: Use long buffers if possible */ DebugPrintF(("CL_GetCmdLine: \"%s\"\n", *(stateptr->CommandLine))); if (buffhead!=NULL) { len = strlen(*(stateptr->CommandLine)); if (len > Armsd_BufferSize-24) len = Armsd_BufferSize-24; packet->pk_length = len + msgbuild(BUFFERDATA(buffhead), "%w%w%w%w%w%w", CL_GetCmdLine|HtoT, DebugID, OSInfo1, OSInfo2, NoError, len); strncpy((char *) BUFFERDATA(buffhead)+24,*(stateptr->CommandLine), len); Adp_ChannelWrite(CI_CLIB, packet);/* Send message. */ return 0; } else return -1; } case CL_Clock: /* Return the number of centiseconds since the support */ /* code started executing */ { time_t retTime = time(NULL); if (retTime == (time_t)-1) stateptr->last_errno = errno; else retTime *=100; DebugPrintF(("CL_Clock: %lu\n", retTime)); DebugCheckErr("time", TRUE, (retTime == (time_t)-1), stateptr->last_errno); DevSW_FreePacket(packet); return msgsend(CI_CLIB, "%w%w%w%w%w%w",CL_Clock|HtoT, DebugID, OSInfo1, OSInfo2, NoError, retTime); } case CL_Time: /* return time, in seconds since the start of 1970 */ { time_t retTime = time(NULL); if (retTime == (time_t)-1) stateptr->last_errno = errno; DebugPrintF(("CL_Time: %lu\n", retTime)); DebugCheckErr("time", TRUE, (retTime == (time_t)-1), stateptr->last_errno); DevSW_FreePacket(packet); return msgsend(CI_CLIB,"%w%w%w%w%w%w",CL_Time|HtoT, DebugID, OSInfo1, OSInfo2, NoError, retTime); } case CL_Remove: /* delete named in the null terminated string */ { /* Removing an open file will cause problems but once again * its not our problem, likely result is a tangled FileTable */ /* As the filename is passed with a null terminator we can use it * straight out of the buffer without copying it.*/ unpack_message(buffp, "%w", &len); DebugCheckNullTermString("CL_Remove", TRUE, len, buffp+4); err=remove((char *)buffp+4); stateptr->last_errno = errno; DevSW_FreePacket(packet); DebugCheckErr("remove", TRUE, err, stateptr->last_errno); return msgsend(CI_CLIB, "%w%w%w%w%w", CL_Remove|HtoT, DebugID, OSInfo1, OSInfo2, err?-1:NoError); } case CL_Rename: /* rename file */ { /* Rename(word nbytes, bytes oname, word nbytes, bytes nname) * return(byte status) */ unsigned int len2; unpack_message(buffp, "%w", &len); DebugCheckNullTermString("CL_Rename", FALSE, len, buffp+4); unpack_message(buffp+5+len, "%w", &len2); DebugCheckNullTermString("to", TRUE, len2, buffp+9+len); /* Both names are passed with null terminators so we can use them * directly from the buffer. */ err = rename((char *)buffp+4, (char *)buffp+9+len); stateptr->last_errno = errno; DebugCheckErr("rename", TRUE, err, stateptr->last_errno); DevSW_FreePacket(packet); return msgsend(CI_CLIB, "%w%w%w%w%w", CL_Rename|HtoT, DebugID, OSInfo1, OSInfo2, (err==0)? NoError : -1); } case CL_Open: /* open the file */ { /* Open(word nbytes, bytes name, byte mode) * return(word handle) */ unpack_message(buffp, "%w", &len); /* get the open mode */ unpack_message((buffp)+4+len+1, "%w", &mode); DebugCheckNullTermString("CL_Open", FALSE, len, buffp+4); DebugPrintF(("mode: %d\n", mode)); /* do some checking on the file first? */ /* check if its a tty */ if (strcmp((char *)buffp+4, ":tt")==0 && (mode==0||mode==1)) { /* opening tty "r" */ fhreal = stdin; stateptr->last_errno = errno; DebugPrintF(("\tstdin ")); } else if (strcmp((char *)buffp+4, ":tt")== 0 && (mode==4||mode==5)) { /* opening tty "w" */ fhreal = stdout; stateptr->last_errno = errno; DebugPrintF(("\tstdout ")); } else { fhreal = fopen((char *)buffp+4, fmode[mode&0xFF]); stateptr->last_errno = errno; DebugCheckNonNull("fopen", FALSE, fhreal, stateptr->last_errno); } DevSW_FreePacket(packet); c = NONHANDLE; if (fhreal != NULL) { /* update filetable */ for (c=3; c < HSYS_FOPEN_MAX; c++) { /* allow for stdin, stdout, stderr (!!! WHY? MJG) */ if (stateptr->OSptr->FileTable[c] == NULL) { stateptr->OSptr->FileTable[c]= fhreal; stateptr->OSptr->FileFlags[c]= mode & 1; DebugPrintF(("fh: %d\n", c)); break; } else if (c == HSYS_FOPEN_MAX) { /* no filehandles free */ DebugPrintF(("no free fh: %d\n", c)); stateptr->last_errno = EMFILE; } } } else { /* c = NULL;*/ DebugPrintF(("error fh: %d\n", c)); } (void) msgsend(CI_CLIB, "%w%w%w%w%w", CL_Open|HtoT, DebugID, OSInfo1, OSInfo2, c); return 0; } case CL_Close: /* close the file pointed to by the filehandle */ { unpack_message(buffp, "%w", &fh); DebugPrintF(("CL_Close: fh %d\n", fh)); DevSW_FreePacket(packet); fhreal = hsysGetRealFileHandle(stateptr, fh, NULL); if (fhreal == NULL) err = -1; else { if (fhreal == stdin || fhreal == stdout || fhreal == stderr) { stateptr->last_errno = errno; DebugPrintF(("\tskipping close of std*\n")); err = 0; } else { err = fclose(fhreal); if (err == 0) stateptr->OSptr->FileTable[fh]=NULL; stateptr->last_errno = errno; DebugCheckErr("fclose", TRUE, err, stateptr->last_errno); } } return msgsend(CI_CLIB,"%w%w%w%w%w", CL_Close|HtoT, DebugID, OSInfo1, OSInfo2, err); } case CL_Write: { /* Write(word handle, word nbtotal, word nbytes, bytes data) * return(word nbytes) * WriteX(word nbytes, bytes data) * return(word nbytes) */ unsigned char *rwdata = NULL, *rwhead = NULL; unsigned char *write_source = NULL; char flags; FILE *fhreal; unsigned int ack_reason = CL_Write; /* first ack is for CL_Write */ err = -1; /* err == 0 is fwrite() error indication */ unpack_message(buffp, "%w%w%w", &fh, &nbtotal, &nbytes); DebugPrintF(("CL_Write: fh %d nbtotal %u nbytes %u\n", fh, nbtotal, nbytes)); fhreal = hsysGetRealFileHandle(stateptr, fh, &flags); nbtogo = nbtotal; /* deal with the file handle */ if (fhreal == NULL) err = 0; else { if (flags & READOP) fseek(fhreal,0,SEEK_CUR); stateptr->OSptr->FileFlags[fh] = (flags & BINARY) | WRITEOP; nbtogo -= nbytes; if (nbtogo > 0) { write_source = rwdata = rwhead = (unsigned char *)malloc(nbtotal); if (rwhead == NULL) { fprintf(stderr, "OUT OF MEMORY at line %d in %s\n", __LINE__, __FILE__); return -1; } memcpy(rwdata, buffp+12, nbytes); rwdata += nbytes; } else write_source = buffp+12; } do { /* at least once!! */ if (nbtogo == 0 && err != 0) { /* Do the actual write! */ if (fhreal == stdout || fhreal == stderr) { stateptr->hostif->write(stateptr->hostif->hostosarg, (char *)write_source, nbtotal); } else err = fwrite(write_source, 1, nbtotal, fhreal); stateptr->last_errno = errno; DebugCheckErr("fwrite", TRUE, (err == 0), stateptr->last_errno); } DevSW_FreePacket(packet); if (msgsend(CI_CLIB,"%w%w%w%w%w%w", ack_reason|HtoT, DebugID, OSInfo1, OSInfo2, (err == 0), nbtogo)) { fprintf(stderr, "COULD NOT REPLY at line %d in %s\n", __LINE__, __FILE__); if (rwhead != NULL) free(rwhead); return -1; } if (nbtogo == 0 || err == 0) { DebugPrintF(("\twrite complete - returning\n")); if (rwhead != NULL) free(rwhead); return 0; } else { /* await extension */ ack_reason = CL_WriteX; packet = DevSW_AllocatePacket(Armsd_BufferSize); if (packet == NULL) { fprintf(stderr, "COULD NOT ALLOC PACKET at line %d in %s\n", __LINE__, __FILE__); if (rwhead != NULL) free(rwhead); return -1; } Adp_ChannelRegisterRead(CI_CLIB, NULL, NULL); Adp_ChannelRead(CI_CLIB, &packet); Adp_ChannelRegisterRead(CI_CLIB, (ChannelCallback)HandleSysMessage, stateptr); buffhead = packet->pk_buffer; unpack_message(BUFFERDATA(buffhead), "%w%w%w%w%w", &reason_code, &DebugID, &OSInfo1, &OSInfo2, &nbytes); if (reason_code != (CL_WriteX|TtoH)) { DevSW_FreePacket(packet); free(rwhead); fprintf(stderr, "EXPECTING CL_WriteX GOT %u at line %d in %s\n", reason_code, __LINE__, __FILE__); return -1; } DebugPrintF(("CL_WriteX: nbytes %u\n", nbytes)); memcpy(rwdata, BUFFERDATA(buffhead)+20, nbytes); rwdata += nbytes; nbtogo -= nbytes; } } while (TRUE); /* will return when done */ } case CL_WriteX: /* * NOTE: if we've got here something has gone wrong * CL_WriteX's should all be picked up within the * CL_Write loop, probably best to return an error here * do this for the moment just so we do actually return */ fprintf(stderr, "ERROR: unexpected CL_WriteX message received\n"); return -1; case CL_Read: { /* Read(word handle, word nbtotal) * return(word nbytes, word nbmore, bytes data) */ /* ReadX() * return(word nbytes, word nbmore, bytes data) */ unsigned char *rwdata, *rwhead; int gotlen; unsigned int max_data_in_buffer=Armsd_BufferSize-28; char flags; FILE *fhreal; unsigned int nbleft = 0, reason = CL_Read; err = NoError; unpack_message(buffp, "%w%w", &fh, &nbtotal); DebugPrintF(("CL_Read: fh %d, nbtotal %d: ", fh, nbtotal)); rwdata = rwhead = (unsigned char *)malloc(nbtotal); if (rwdata == NULL) { fprintf(stderr, "OUT OF MEMORY at line %d in %s\n", __LINE__, __FILE__); DevSW_FreePacket(packet); return -1; } /* perform the actual read */ fhreal = hsysGetRealFileHandle(stateptr, fh, &flags); if (fhreal == NULL) { /* bad file handle */ err = -1; nbytes = 0; gotlen = 0; } else { if (flags & WRITEOP) fseek(fhreal,0,SEEK_CUR); stateptr->OSptr->FileFlags[fh] = (flags & BINARY) | WRITEOP; if (isatty_(fhreal)) { /* reading from a tty, so do some nasty stuff, reading into rwdata */ if (angel_hostif->gets(stateptr->hostif->hostosarg, (char *)rwdata, nbtotal) != 0) gotlen = strlen((char *)rwdata); else gotlen = 0; stateptr->last_errno = errno; DebugPrintF(("ttyread %d\n", gotlen)); } else { /* not a tty, reading from a real file */ gotlen = fread(rwdata, 1, nbtotal, fhreal); stateptr->last_errno = errno; DebugCheckErr("fread", FALSE, (gotlen == 0), stateptr->last_errno); DebugPrintF(("(%d)\n", gotlen)); } } nbtogo = gotlen; do { /* at least once */ if ((unsigned int) nbtogo <= max_data_in_buffer) nbytes = nbtogo; else nbytes = max_data_in_buffer; nbtogo -= nbytes; /* last ReadX needs subtle adjustment to returned nbtogo */ if (nbtogo == 0 && err == NoError && reason == CL_ReadX) nbleft = nbtotal - gotlen; else nbleft = nbtogo; count = msgbuild(BUFFERDATA(buffhead), "%w%w%w%w%w%w%w", reason|HtoT, 0, ADP_HandleUnknown, ADP_HandleUnknown, err, nbytes, nbleft); if (err == NoError) { /* copy data into buffptr */ memcpy(BUFFERDATA(buffhead)+28, rwdata, nbytes); rwdata += nbytes; count += nbytes; } DebugPrintF(("\treplying err %d, nbytes %d, nbtogo %d\n", err, nbytes, nbtogo)); packet->pk_length = count; Adp_ChannelWrite(CI_CLIB, packet); if (nbtogo == 0 || err != NoError) { /* done */ free(rwhead); return 0; } else { /* await extension */ reason = CL_ReadX; packet = DevSW_AllocatePacket(Armsd_BufferSize); if (packet == NULL) { fprintf(stderr, "COULD NOT ALLOC PACKET at line %d in %s\n", __LINE__, __FILE__); free(rwhead); return -1; } Adp_ChannelRegisterRead(CI_CLIB, NULL, NULL); Adp_ChannelRead(CI_CLIB, &packet); Adp_ChannelRegisterRead(CI_CLIB, (ChannelCallback)HandleSysMessage, stateptr); buffhead = packet->pk_buffer; unpack_message(BUFFERDATA(buffhead),"%w", &reason_code); if (reason_code != (CL_ReadX|TtoH)) { fprintf(stderr, "EXPECTING CL_ReadX GOT %u at line %d in %s\n", reason_code, __LINE__, __FILE__); DevSW_FreePacket(packet); free(rwdata); return -1; } } } while (TRUE); /* will return above on error or when done */ } case CL_ReadX: /* If we're here something has probably gone wrong */ fprintf(stderr, "ERROR: Got unexpected CL_ReadX message\n"); return -1; case CL_Seek: { unpack_message(buffp, "%w%w", &fh, &posn); DebugPrintF(("CL_Seek: fh %d, posn %ld\n", fh, posn)); DevSW_FreePacket(packet); fhreal = hsysGetRealFileHandle(stateptr, fh, NULL); if (fhreal == NULL) err = -1; else { err = fseek(fhreal, posn, SEEK_SET); stateptr->last_errno = errno; DebugCheckErr("fseek", TRUE, err, stateptr->last_errno); } return msgsend(CI_CLIB, "%w%w%w%w%w", CL_Seek|HtoT, DebugID, OSInfo1, OSInfo2, err); } case CL_Flen: { unpack_message(buffp, "%w", &fh); DebugPrintF(("CL_Flen: fh %d ", fh)); DevSW_FreePacket(packet); fhreal = hsysGetRealFileHandle(stateptr, fh, NULL); if (fhreal == NULL) fl = -1; else { posn = ftell(fhreal); if (fseek(fhreal, 0L, SEEK_END) < 0) { fl=-1; } else { fl = ftell(fhreal); fseek(fhreal, posn, SEEK_SET); } stateptr->last_errno = errno; } DebugPrintF(("returning len %ld\n", fl)); return msgsend(CI_CLIB, "%w%w%w%w%w", CL_Flen|HtoT, DebugID, OSInfo1, OSInfo2, fl); } case CL_IsTTY: { int ttyOrNot; unpack_message(buffp, "%w", &fh); DebugPrintF(("CL_IsTTY: fh %d ", fh)); DevSW_FreePacket(packet); fhreal = hsysGetRealFileHandle(stateptr, fh, NULL); if (fhreal == NULL) ttyOrNot = FALSE; else { ttyOrNot = isatty_(fhreal); stateptr->last_errno = errno; } DebugPrintF(("returning %s\n", ttyOrNot ? "tty (1)" : "not (0)")); return msgsend(CI_CLIB, "%w%w%w%w%w",CL_IsTTY|HtoT, DebugID, OSInfo1, OSInfo2, ttyOrNot); } case CL_TmpNam: { char *name; unsigned int tnamelen, TargetID; unpack_message(buffp, "%w%w", &tnamelen, &TargetID); DebugPrintF(("CL_TmpNam: tnamelen %d TargetID %d: ", tnamelen, TargetID)); DevSW_FreePacket(packet); TargetID = TargetID & 0xFF; if (stateptr->OSptr->TempNames[TargetID] == NULL) { if ((stateptr->OSptr->TempNames[TargetID] = (char *)malloc(L_tmpnam)) == NULL) { fprintf(stderr, "OUT OF MEMORY at line %d in %s\n", __LINE__, __FILE__); return -1; } tmpnam(stateptr->OSptr->TempNames[TargetID]); } name = stateptr->OSptr->TempNames[TargetID]; len = strlen(name) + 1; packet = DevSW_AllocatePacket(Armsd_BufferSize); if (packet == NULL) { fprintf(stderr, "COULD NOT ALLOC PACKET at line %d in %s\n", __LINE__, __FILE__); return -1; } buffhead = packet->pk_buffer; if (len > tnamelen) { DebugPrintF(("TMPNAME TOO LONG!\n")); count = msgbuild(BUFFERDATA(buffhead), "%w%w%w%w%w", CL_TmpNam|HtoT, DebugID, OSInfo1, OSInfo2, -1); } else { DebugPrintF(("returning \"%s\"\n", name)); count = msgbuild(BUFFERDATA(buffhead), "%w%w%w%w%w%w", CL_TmpNam|HtoT, DebugID, OSInfo1, OSInfo2, 0, len); strcpy((char *)BUFFERDATA(buffhead)+count, name); count +=len+1; } packet->pk_length = count; Adp_ChannelWrite(CI_CLIB, packet);/* Send message. */ return 0; } case CL_Unrecognised: DebugPrintF(("CL_Unrecognised!!\n")); return 0; default: fprintf(stderr, "UNRECOGNISED CL code %08x\n", reason_code); break; /* Need some sort of error handling here. */ /* A call to CL_Unrecognised should suffice */ } return -1; /* Stop a potential compiler warning */ }