/* * Class: org_imgsdk_core_NativeImageSdk * Method: setEffectCmd * Signature: (JLjava/lang/String;)V */ void JNICALL Java_org_imgsdk_core_NativeImageSdk_setEffectCmd (JNIEnv *env, jobject thiz, jlong ptr, jstring jcommand) { LOG_ENTRY; SdkEnv* sdk = (SdkEnv *)((intptr_t)ptr); if (NULL == sdk) { LogE("NULL pointer exception\n"); return; } if (NULL == jcommand) { LogE("NULL pointer exception\n"); return; } Log("setEffectCmd pthread self:%lx\n", pthread_self() ); Log("setEffectCmd gettid:%x\n", gettid() ); char *cmd = jstring2string(env, jcommand); if (NULL == cmd) { LogE("Effect cmd is NULL\n"); return; } Log("EffectCmd = %s\n", cmd); setEffectCmd (sdk, cmd); LOG_EXIT; }
/** * Read the text file to memory * Parameters: * path: file path * mem: [OUT] store file content * Return: * if OK return file's length * if ERROR return -1 * Notice: * space of mem is 1 more byte than file length */ int readFile(const char* path, char** mem) { VALIDATE_NOT_NULL2(path, mem); FILE *fp = fopen(path, "r"); if (NULL == fp) { return -1; } fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); if (NULL == *mem) { (*mem) = (char *)calloc(1, size + 1); if (NULL == *mem) { LogE("Failed calloc mem for shader file\n"); close (fp); return -1; } } if (fread(*mem, 1, size, fp) != size) { LogE("Failed read shader to mem\n"); close(fp); free (*mem); *mem = NULL; return -1; } return size; }
/* * Class: org_imgsdk_core_NativeImageSdk * Method: setOutputPath * Signature: (JLjava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_imgsdk_core_NativeImageSdk_setOutputPath (JNIEnv *env, jobject thiz, jlong ptr, jstring jpath) { LOG_ENTRY; SdkEnv* sdk = (SdkEnv *)((intptr_t)ptr); if (NULL == sdk) { LogE("NULL pointer exception\n"); return; } if (NULL == jpath) { LogE("NULL pointer exception\n"); return; } char *path = jstring2string(env, jpath); if (NULL == path) { LogE("output path is NULL\n"); return; } Log("output path:%s\n", path); setOutputImagePath(sdk, path); LOG_EXIT; }
/** * Minimum step <= current >= Maximum step */ static inline int getStartPoint(OFFSET * start, OFFSET * top_left, DrawDirection direc, int curr_step, int step_nr, SIZE * step_size) { if (NULL == start || NULL == top_left){ LogE("Wrong arguments"); return -1; } if (curr_step <= 0 || curr_step > step_nr) { // Don't need to draw anything if current == 0 return -1; } switch (direc) { case RIGHT_LEFT: LogE("Wrong direction definition"); break; case BOTTOM_UP: start->x = top_left->x; start->y = top_left->y + ((step_nr - curr_step) * step_size->height); break; case UP_BOTTOM: LogE("Wrong direction definition"); break; case LEFT_RIGHT: LogE("Wrong direction definition"); break; default: LogE("Wrong direction definition"); return -1; } return 0; }
/** * Poll relay server * Return: * 0 success * -1 failed */ int rs_loop(rscntxt_t *cntxt) { if (NULL == cntxt) { LogE("NULL Pointer"); return -1; } #define MAX_EVENTS 16 #define WAIT_TIMEOUT 10 struct epoll_event ev[MAX_EVENTS]; int ret = epoll_wait(cntxt->fd_epoll, ev, MAX_EVENTS, WAIT_TIMEOUT); int i; for (i = 0; i < ret; ++i) { if (ev[i].data.fd == cntxt->fd_srvr) { accept_connection(cntxt); continue; } int nread = read_client(ev[i].data.fd, cntxt); if (nread < 0) { LogE("Failed read client"); } } return 0; }
/** * Create a default SdkEnv instance */ static int attachShader(SdkEnv *env, const char *vertSource, const char *fragSource) { VALIDATE_NOT_NULL3(env, vertSource, fragSource); // log openGL information const GLubyte* version = glGetString(GL_VERSION); Log ("Version:%s\n", version); const GLubyte* renderer = glGetString(GL_RENDERER); Log ("Render:%s\n", renderer); const GLubyte* vendor = glGetString(GL_VENDOR); Log ("Vendor:%s\n", vendor); #if 0 const GLubyte* extension = glGetString (GL_EXTENSIONS); Log ("Extensions:\n%s\n\n", extension); #endif if(createProgram(env, vertSource, fragSource) < 0) { LogE("Failed createProgram\n"); return -1; } if (findShaderHandles(env) < 0) { LogE("Failed findShaderHandles\n"); return -1; } return 0; }
/** * Create a glsh shader * Parameters: * type: Just support GL_VERTEX_SHADER and GL_FRAGMENT_SHADER * source: shader source code * Return: * if failed, return 0 * if success, return the handle of shader */ static int loadShader(GLenum type, const char* source) { VALIDATE_NOT_NULL(source); GLuint shader = glCreateShader(type); if (!shader) { LogE("Invalid shader\n"); return 0; } GLint length = strlen(source); glShaderSource(shader, 1, &source, &length); glCompileShader(shader); int compiled, len; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { memset(sLogBuff, 0, LOG_BUFF_SIZE); glGetShaderInfoLog(shader, LOG_BUFF_SIZE, &len, sLogBuff); if (len > 0) { Log("compile error:%s\n", sLogBuff); } else { LogE("Failed get compile log\n"); } shader = 0; glDeleteShader(shader); } return shader; }
/** * Find all variables handle in shader */ static int findShaderHandles(SdkEnv *env) { if (NULL == env) { return -1; } if (0 == env->handle.program) { return -1; } env->handle.positionIdx = glGetAttribLocation(env->handle.program, "aPosition"); if (env->handle.positionIdx < 0) { LogE("Failed get aPosition location\n"); } env->handle.sampler2dIdx = glGetUniformLocation(env->handle.program, "uSampler2D"); if (env->handle.sampler2dIdx < 0) { LogE("Failed get uSampler2D location\n"); } env->handle.texCoordIdx = glGetAttribLocation(env->handle.program, "aTexCoord"); if (env->handle.texCoordIdx < 0) { LogE("Failed get aTexCoord location\n"); } env->handle.colorIdx = glGetAttribLocation(env->handle.program, "aColor"); if (env->handle.colorIdx < 0) { LogE("Failed get aColor location\n"); } return 0; }
/* * I've tried to pack all necessary functionality into this program without the * need of arguments so AndroSS only has to be su whitelisted once. Therefore, * this program's behavior is determined by the value of the envvar * ANDROSS_MODE. * case (TRUE): * return 0. (Useful for su tests and initial whitelisting.) * * case (FB_PARAMS): * This binary will query the framebuffer for the following information, * printing it in decimal in this order, separated by spaces: * horizontal resolution * vertical resolution * pixel depth * red offset * red length * green offset * green length * blue offset * blue length * alpha offset * alpha length * stride * * case (FB_DATA): * If this has a value, this binary will interpret it as the number of * bytes it should read from the framebuffer and write out. */ int writeFBParams(int output_fd, int fb_fd) { // Run the appropriate ioctls to find out what we're dealing with. struct fb_fix_screeninfo fb_fixinfo; struct fb_var_screeninfo fb_varinfo; if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &fb_fixinfo) < 0) { LogE("External: fixinfo ioctl failed."); close(fb_fd); return(1); } if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &fb_varinfo) < 0) { LogE("External: varinfo ioctl failed."); close(fb_fd); return(1); } char output_data[STRING_BUFFER_SIZE] = {0}; sprintf(output_data, "%u %u %u %u %u %u %u %u %u %u %u %u", fb_varinfo.xres, fb_varinfo.yres, fb_varinfo.bits_per_pixel, fb_varinfo.blue.offset, fb_varinfo.blue.length, fb_varinfo.green.offset, fb_varinfo.green.length, fb_varinfo.red.offset, fb_varinfo.red.length, fb_varinfo.transp.offset, fb_varinfo.transp.length, fb_fixinfo.line_length); write(output_fd, output_data, STRING_BUFFER_SIZE * sizeof(char)); return(0); }
static int read_client(int fd, rscntxt_t *cntxt) { if (NULL == cntxt) { return -1; } msgheader_t header; int nrecv = recv(fd, &header, sizeof(header), 0); if(nrecv < 0) { LogE("Failed recv msg header:%s", strerror(errno)); close(fd); return -1; } if (0 == nrecv) { struct sockaddr_in addr; int len = sizeof(addr); getpeername(fd, (struct sockaddr *)&addr, &len); Log("client %s disconnect\n", inet_ntoa(addr.sin_addr) ); if (epoll_ctl(cntxt->fd_epoll, EPOLL_CTL_DEL, fd, NULL) < 0) { LogE("Failed delete disconnected client fd"); } close(fd); connection_t conn; conn.conn_fd = fd; remove_list_elem(cntxt->conn_list, &conn, compare_conn); return 0; } if (validate_msgheader(&header) < 0) { LogE("Invalid msg header"); close(fd); return -1; } if (REQ_CONNECT == header.message_type && DEVICE_SLAVE == header.device_type) { if (proc_slave_connect(fd, cntxt) < 0) { LogE("Failed process slave device connect"); close(fd); return -1; } } else if (REQ_CONNECT == header.message_type && DEVICE_MASTER == header.device_type) { if (proc_master_connect(fd, ntohl(header.token), cntxt) < 0) { LogE("Failed process master device relay"); close(fd); return -1; } } else if (DEVICE_ADMIN == header.device_type) { proc_admin_connect(fd); } return 0; }
/* * Console application entry * Usage: * imgsdk input output * Notice: * 1. input & onput support *.jpg or *.png * 2. support input and output image type are not same * 3. vert.shdr & frag.shdr must be prepared */ int main(int argc, char **argv) { if (3 != argc) { Log("Usage:\n"); Log(" %s input output\n", argv[0]); return -1; } SdkEnv *env = newDefaultSdkEnv(); if (NULL == env) { LogE("Failed get SdkEnv instance\n"); } setInputImagePath (env, argv[1]); setOutputImagePath (env, argv[2]); sdkMain (env); setEffectCmd (env, "{\"effect\":\"Normal\"}"); onSdkDraw (env); Bitmap_t *img = (Bitmap_t *) env->userData.param; uint32_t begin_t = getCurrentTime(); glBindTexture(GL_TEXTURE, env->handle.texture2Idx); memset (img->base, 0, img->width * img->height * img->form); // copy pixels from GPU memory to CPU memory int x = 0; int y = 0; GLint fmt = GL_RGBA; if (IMAGE_JPG == env->userData.inputImageType) { fmt = GL_RGB; } glReadPixels(x, y, img->width, img->height, fmt, GL_UNSIGNED_BYTE, img->base); int errCode = glGetError (); if (GL_NO_ERROR != errCode ) { Log ("Failed read pixles, error code:0x%04x\n", errCode); } uint32_t finish_t = getCurrentTime(); LogD("Read pixel data cost %d ms\n", (finish_t - begin_t)); begin_t = getCurrentTime(); if (NULL != env->userData.outputPath) { if (saveImage (env->userData.outputPath, img) < 0) { LogE ("Failed saveImage\n"); } else { finish_t = getCurrentTime(); LogD("Save %s cost %d ms\n", env->userData.outputPath, (finish_t - begin_t)); } } freeSdkEnv(env); //onSdkDestroy(env); }
/** * @param argv - To be passed directly to execv. argv[0] must be the full path * to the binary you want to execute. * @param output_buf - The buffer in which to store the child process's output. * @param buf_len - To be passed to read(). Passing 0 for this and toss_bytes * will result in no accesses being made to output_buf, making it safe to * pass NULL. * @param fd - The fd on the child process from which to capture output. 1 and 2 * are probably the only values that make sense. * @param toss_bytes - Bytes to skip at the beginning of the child process's * output. It is unsafe for this to be greater than the size of your * buffer. */ static inline int execForOutput(char ** argv, uint8_t * output_buf, int buf_len, int fd, int toss_bytes) { int pipefd[2]; pipe(pipefd); LogD("NBridge: Reading fd %d from %s with args:", fd, argv[0]); char ** arg = argv + 1; while (*arg != NULL) { LogD("\t%s", *arg); ++arg; } int cpid = fork(); if (cpid == 0) { close(pipefd[0]); dup2(pipefd[1], fd); execv(argv[0], argv); } close(pipefd[1]); if (toss_bytes > 0) { int bytes_tossed = read(pipefd[0], output_buf, toss_bytes); if (bytes_tossed != toss_bytes) { LogE("NBridge: Error skipping junk! Only tossed %d bytes.", bytes_tossed); return -1; } else { LogD("NBridge: Skipped %d bytes.", bytes_tossed); } } int bytes_read = 0; int reads = 0; int child_status = -1; while (bytes_read < buf_len) { int bytes_read_this_time = read(pipefd[0], output_buf + bytes_read, buf_len - bytes_read); if (bytes_read_this_time < 0) { char * errmsg = strerror(errno); LogE("NBridge: Error while reading from subprocess:"); LogE(errmsg); return 255; } if (bytes_read_this_time == 0) { break; } bytes_read += bytes_read_this_time; reads++; } LogD("NBridge: Read %d of %d bytes from subprocess with %d reads.", bytes_read, buf_len, reads); close(pipefd[0]); return waitpid(cpid, &child_status, 0); }
bool SdlApp::createGLWindow(const char * title, int x, int y, int w, int h, Uint32 flags) { SDL_Init(SDL_INIT_VIDEO); // Initialize SDL2 mWindowWidth = w; mWindowHeight = h; uint32_t unWindowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | flags; SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); //SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY ); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); if (mDebugOpenGL) SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); mWindow = SDL_CreateWindow(title, x, y, mWindowWidth, mWindowHeight, unWindowFlags); if (mWindow == nullptr) { LogE("Window could not be created! SDL Error: %s\n", SDL_GetError()); return false; } mGlContext = SDL_GL_CreateContext(mWindow); if (mGlContext == nullptr) { LogE("OpenGL context could not be created! SDL Error: %s\n", SDL_GetError()); return false; } glewExperimental = GL_TRUE; GLenum nGlewError = glewInit(); if (nGlewError != GLEW_OK) { LogE("Error initializing GLEW! %s\n", glewGetErrorString(nGlewError)); return false; } glGetError(); // to clear the error caused deep in GLEW if (SDL_GL_SetSwapInterval(mVBlank ? 1 : 0) < 0) { LogE("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError()); return false; } return true; }
static int accept_connection(rscntxt_t *cntxt) { if (NULL == cntxt) { return -1; } struct sockaddr_in addr; int len = sizeof(addr); int fd = accept(cntxt->fd_srvr, (struct sockaddr *)&addr, &len); if (fd < 0) { Log("Failed accept client's connect"); return -1; } Log("accept %s:%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); struct epoll_event ev; ev.events = EPOLLIN; ev.data.fd = fd; if (epoll_ctl(cntxt->fd_epoll, EPOLL_CTL_ADD, fd, &ev) < 0) { LogE("Failed add fd to epoll"); return -1; } return 0; }
int main() { // Find and open the correct framebuffer device. int fb_fd = open(FB_PATH, O_RDONLY); if (fb_fd < 0) { char * errstr = strerror(errno); char * errmsg = (char *)calloc(ERR_BUFFER_SIZE, sizeof(char)); strncpy(errmsg, "External: Could not open framebuffer device: ", 45); strncpy(errmsg + 45, errstr, ERR_BUFFER_SIZE - 45); LogE(errmsg); return(1); } const char * mode_str = getenv("ANDROSS_MODE"); if (mode_str == NULL) { mode_str = ""; } int ret; if (strcmp(mode_str, "FB_PARAMS") == 0) { LogD("External: Running in Param mode."); ret = writeFBParams(FD_STDOUT, fb_fd); } else if (strcmp(mode_str, "FB_DATA") == 0) { LogD("External: Running in Data mode."); const char * fb_bytes_str = getenv("ANDROSS_FRAMEBUFFER_BYTES"); int fb_bytes = atoi(fb_bytes_str); ret = writeFBData(FD_STDOUT, fb_fd, fb_bytes); } else { LogD("External: Running in True mode."); ret = 0; } return ret; }
int Log::LogFmtE(const char * fmt_str, ...) { va_list args; va_start(args, fmt_str); int r = LogE(vastring_format(fmt_str,args)); va_end(args); return r; }
/* * Class: org_imgsdk_core_NativeImageSdk * Method: initSDK * Signature: ()J */ jlong JNICALL Java_org_imgsdk_core_NativeImageSdk_initSDK (JNIEnv *env, jobject thiz, jobject jcontext) { LOG_ENTRY; if (NULL == jcontext) { LogE("NULL pointer exception:context = NULL\n"); return 0; } Log("initSDK pthread self:%lx\n", pthread_self() ); Log("initSDK pthread gettid:%x\n", gettid() ); jclass cls = (*env)->GetObjectClass(env, jcontext); jmethodID mid = (*env)->GetMethodID(env, cls, "getAssets", "()Landroid/content/res/AssetManager;"); jobject jassetMgr = (*env)->CallObjectMethod(env, jcontext, mid); if (NULL == jassetMgr) { LogE("Failed get java asset manager\n"); return 0; } AAssetManager *assetMgr = AAssetManager_fromJava(env, jassetMgr); if (NULL == assetMgr) { LogE("Failed get native asset manager\n"); return 0; } SdkEnv *sdk = newBlankSdkEnv(PLATFORM_ANDROID); if (NULL == sdk) { LogE("Failed newBlankSdkEnv\n"); return 0; } setPlatformData(sdk, assetMgr); if (initSdkEnv (sdk) < 0) { LogE("Failed initSdkEnv \n"); freeSdkEnv (sdk); return 0; } jlong ptr = (jlong) ( (intptr_t)sdk ); LOG_EXIT; return ptr; }
/** * Create a blank SdkEnv instance * Parameters: * platform: Just support Android & iOS * Return: * if failed return NULL * otherwise return an valid pointer */ SdkEnv* newBlankSdkEnv(int platform) { if (platform <= PLATFORM_OLD || platform >= PLATFORM_NEW) { LogE("Invalid platform\n"); return NULL; } SdkEnv *env = (SdkEnv *)calloc(1, sizeof(SdkEnv)); return env; }
/* * Class: org_imgsdk_core_NativeImageSdk * Method: executeCmd * Signature: (J)V */ void JNICALL Java_org_imgsdk_core_NativeImageSdk_executeCmd (JNIEnv *env, jobject thiz, jlong ptr, jobject jlistener, jobject param) { LOG_ENTRY; SdkEnv *sdk = (SdkEnv *) ((intptr_t) ptr); if (NULL == sdk) { LogE("NULL pointer exception\n"); return; } Log("executeCmd pthread self:%lx\n", pthread_self() ); Log("executeCmd gettid :%x\n", gettid() ); swapEglBuffers(sdk); onSdkDraw (sdk); if (NULL != jlistener) { jclass cls = (jclass)(*env)->GetObjectClass(env, jlistener); if (NULL == cls) { LogE("Not found OnEditCompleteListener\n"); return; } jmethodID mid = (jmethodID)(*env)->GetMethodID(env, cls, "onSuccess", "(Ljava/lang/String;Ljava/lang/Object;)V"); if (mid == NULL) { LogE("Not found onSuccess(String, Object\n"); return; } char *path = getOutputImagePath(sdk); Log("output path:%s\n", path); jstring jpath = NULL; if (NULL != path) { jpath = string2jstring(env, path); } (*env)->CallVoidMethod(env, jlistener, mid, jpath, param); if (NULL != jpath) { (*env)->DeleteGlobalRef(env, jpath); } } LOG_EXIT; }
int writeFBData(int output_fd, int fb_fd, int fb_bytes) { void * bytes = malloc(fb_bytes); int bytes_read = read(fb_fd, bytes, fb_bytes); if (bytes_read < fb_bytes) { LogE("External: Only read %d bytes from framebuffer!", bytes_read); return 1; } LogD("External: read %u bytes from framebuffer.", bytes_read); int bytes_written = write(output_fd, bytes, fb_bytes); if (bytes_written < fb_bytes) { LogE("External: Only wrote %d bytes!", bytes_written); return 1; } LogD("External: wrote %u bytes.", bytes_written); return 0; }
/** * Save image * Parameters: * path: output path * mem: bitmap in memory * Return: * 0 OK * -1 ERROR */ int saveImage (const char *path, const Bitmap_t *mem) { VALIDATE_NOT_NULL2 (path, mem); const char const *postfix = getFilePostfix (path); if (NULL == postfix) { LogE ("Failed getFilePostfix in saveImage\n"); return -1; } if (strcasecmp (postfix, "jpg") == 0) { return write_jpeg (path, mem); } else if (strcasecmp (postfix, "png") == 0) { return write_png (path, mem); } else { LogE ("Invalid postfix name (%s) in saveImage\n", postfix); return -1; } }
int push_stack(stack_t *stack, int elem) { VALIDATE_NOT_NULL(stack); if (stack->top < stack->size) { stack->base[stack->top++] = elem; return 0; } else { LogE("stack top overflow"); return -1; } }
/** * dumplicate rscntxt */ void dump_context(rscntxt_t *cntxt) { if (NULL == cntxt) { LogE("NULL pointer"); return; } Log("port:%d\n", cntxt->port); Log("backlog:%d\n", cntxt->backlog); Log("heart beat:%d ms\n", cntxt->heartbeat_cycle); }
/** * Create a default SdkEnv instance */ SdkEnv* newDefaultSdkEnv() { SdkEnv *env = (SdkEnv *)calloc(1, sizeof(SdkEnv)); if (NULL == env){ return NULL; } if (initDefaultEGL(env) < 0) { LogE("Failed initDefaultEGL\n"); freeSdkEnv(env); return NULL; } chrbuf_t *userCmd = newChrbuf (USER_CMD_CAPABILITY); if (NULL == userCmd) { LogE ("Failed newChrbuf for userCmd\n"); freeSdkEnv (env); return NULL; } env->userCmd = userCmd; char *vertSource = NULL; int count = readFile(VERT_SHADER_FILE, &vertSource); if (count < 0) { LogE("Failed open vertex shader file:%s\n", VERT_SHADER_FILE); freeSdkEnv(env); return NULL; } Log("Read %s OK.\n", VERT_SHADER_FILE); env->userData.nVertSource = count; env->userData.vertSource = vertSource; char *fragSource = NULL; count = readFile(FRAG_SHADER_FILE, &fragSource); if (count < 0) { LogE("Failed read fragment shader file:%s\n", FRAG_SHADER_FILE); free (vertSource); freeSdkEnv(env); return NULL; } env->userData.nFragSource = count; env->userData.fragSource = fragSource; Log("Read %s OK.\n", FRAG_SHADER_FILE); if (attachShader(env, vertSource, fragSource) < 0) { LogE("Failed attachShader\n"); free (vertSource); free (fragSource); freeSdkEnv(env); return NULL; } if (initGlBuffers (env) < 0) { LogE ("Failed init OpenGL buffers.\n"); return NULL; } env->status = SDK_STATUS_OK; return env; }
Bool is_stack_empty(const stack_t *stack) { if (NULL == stack) { LogE("NULL pointer"); return False; } if (stack->top >= 1) { return True; } return False; }
/** * Read file in assets * Return * -1 ERROR * >= 0 file length */ static int readFileFromAssets(const SdkEnv *sdk, const char *fname, char **mem) { VALIDATE_NOT_NULL2(sdk, sdk->userData.platformData); VALIDATE_NOT_NULL2(fname, mem); AAssetManager *assetMgr = (AAssetManager *)(sdk->userData.platformData); AAsset *asset = AAssetManager_open(assetMgr, fname, AASSET_MODE_UNKNOWN); if (NULL == asset) { LogE("Failed open %s by asset manger\n", fname); return -1; } size_t size = AAsset_getLength(asset); if (size <= 0) { LogE("%s length is invalid (file length must > 0)\n", fname); AAsset_close (asset); return -1; } *mem = calloc(1, size + 1); if (NULL == *mem) { LogE("Failed calloc memory for %s\n", fname); AAsset_close (asset); return -1; } if (AAsset_read(asset, *mem, size) != size) { LogE("Failed read %s\n", fname); AAsset_close(asset); free (*mem); *mem = NULL; return -1; } AAsset_close(asset); return size + 1; }
static int proc_slave_connect( int fd, rscntxt_t *cntxt) { Log("proc slave connect\n"); msgheader_t header; header.message_type = RES_CONNECT; header.device_type = DEVICE_SLAVE; header.token = 0; ++cntxt->curr_max_token; uint32 token = cntxt->curr_max_token; connection_t *conn = new_connection(); if (NULL == conn) { LogE("Failed new connection"); return -1; } conn->token = token; conn->conn_fd = fd; if (add_list_elem(cntxt->conn_list, conn) < 0) { LogE("Failed add conn to conn_list"); free_connection(conn); conn = NULL; return -1; } header.token = htonl(conn->token); if (send(fd, &header, sizeof(header),0) != sizeof(header)) { LogE("Failed send RES_CONNECT to client"); return -1; } printf("token:%d\n", conn->token); return 0; }
int pop_stack(stack_t *stack, int *elem) { VALIDATE_NOT_NULL(stack); if (!is_stack_empty(stack)) { if (NULL != elem) { *elem = stack->base[--stack->top]; } else { --stack->top; } return 0; } else { LogE("stack bottom overflow"); return -1; } }
/** * Start relay server * Return: * 0 success * -1 failed */ int rs_start(rscntxt_t *cntxt) { if (NULL == cntxt) { LogE("NULL Pointer"); return -1; } dump_context(cntxt); cntxt->fd_srvr = prepare_tcp_server(cntxt->port, cntxt->backlog); if (cntxt->fd_srvr < 0) { LogE("Failed prepare tcp server"); return -1; } #define EPOLL_MAX_SIZE 32 cntxt->fd_epoll = epoll_create(EPOLL_MAX_SIZE); if (cntxt->fd_epoll < 0) { LogE("Failed epoll_create()"); return -1; } struct epoll_event ev; memset(&ev, 0, sizeof(ev)); ev.data.fd = cntxt->fd_srvr; ev.events = EPOLLIN; if (epoll_ctl(cntxt->fd_epoll, EPOLL_CTL_ADD, cntxt->fd_srvr, &ev) < 0) { LogE("Failed add fd_srvr to epoll:%s", strerror(errno)); return -1; } return 0; }
void ClientSession::HandleLoginRequest( LoginRequest& inPacket ) { m_RecvBuffer.Read( (char*)&inPacket, inPacket.m_Size ); int playerID = inPacket.m_PlayerId; if ( g_PidSessionTable.find( playerID ) != g_PidSessionTable.end() ) { LogE( "[Disconnected from:]ClientSession::HandleLoginRequest Already Login \n" ); Disconnect(); return; } /// 로그인은 DB 작업을 거쳐야 하기 때문에 DB 작업 요청한다. LoadPlayerDataContext* newDbJob = new LoadPlayerDataContext( m_Socket, playerID ); g_DatabaseJobManager->PushDatabaseJobRequest( newDbJob ); }