FileHelper fileHelperCreate(char *path) { FileHelperInternal *m = (FileHelperInternal *) memoryAlloc(sizeof(FileHelperInternal)); m->filePath = path; m->registryMap = hashmapCreate(SMALL_CONTAINER_SIZE); m->managers = hashmapCreate(SMALL_CONTAINER_SIZE); return m; }
ValidationManager validationManagerCreate(Registry registry){ ValidationManagerStruct*m=(ValidationManagerStruct*)memoryAlloc(sizeof(ValidationManagerStruct)); m->registry=registry; m->entitiesMap=hashmapCreate(SMALL_CONTAINER_SIZE); m->parentChildrenRelationEntities=hashmapCreate(SMALL_CONTAINER_SIZE); m->childrenParentRelationEntities=hashmapCreate(SMALL_CONTAINER_SIZE); m->deletedEntitiesMap=hashmapCreate(SMALL_CONTAINER_SIZE); return m; }
/** * AtomicOnlineSchema open;<p> * create new instance of commandsList which will contain all the transactional commands.<p> * create new instance of transactionEntities which will contain a list of the loked entities. */ Transaction transactionCreate(Core core,CommandExecuter commandExecutor,Registry registry,SchemaAdapter schemaAdapter,SessionMetaData sessionMetaData,long lockTimeout){ TransactionInternal*m=(TransactionInternal*)memoryAlloc(sizeof(TransactionInternal)); m->core=core; m->commandExecutor=commandExecutor; m->registry=registry; m->scheamAdapter=schemaAdapter; m->sessionMetaData=sessionMetaData; m->transactionEntities=hashmapCreate(SMALL_CONTAINER_SIZE); m->dirtySet=hashmapCreate(SMALL_CONTAINER_SIZE); m->commandList=arrayListCreate(); m->transaction=NULL; m->lockTimeout=lockTimeout; }
graph *graphCreate() { graph *ctx = (graph*) malloc(sizeof(graph)); if(!ctx) return NULL; ctx->GIDMap = hashmapCreate(0); ctx->CIDMap = hashmapCreate(0); ctx->srcMap = hashmapCreate(0); ctx->drnMap = hashmapCreate(0); ctx->nodes = fastlistCreate(CONN_LIST_SIZE); ctx->connections = fastlistCreate(CONN_LIST_SIZE); ctx->nodeCount = 0; return ctx; };
CommandContainer commandContainerCreate(){ CommandContainerInternal* m=(CommandContainerInternal*)memoryAlloc(sizeof(CommandContainerInternal)); m->versionMap=hashmapCreate(SMALL_CONTAINER_SIZE); m->versions=linkedListCreate(); m->atomicCommands=linkedListCreate(); m->lock=lockCreate(); return m; }
void startGame() { currentGame.playerTurn = PLAYER_A_TURN; currentGame.gameMap = hashmapCreate(); currentGame.currentRound = 1; currentGame.mapSize = DEFAULT_INITIAL_VALUE; currentGame.maxRound = DEFAULT_INITIAL_VALUE; currentGame.startingX1 = DEFAULT_INITIAL_VALUE; currentGame.startingX2 = DEFAULT_INITIAL_VALUE; currentGame.startingY1 = DEFAULT_INITIAL_VALUE; currentGame.startingY2 = DEFAULT_INITIAL_VALUE; currentGame.isInitialized = false; }
Properties propertiesCreate(char *filePath) { PropertiesInternal *m = (PropertiesInternal *) memoryAlloc(sizeof(PropertiesInternal)); m->map = hashmapCreate(SMALL_CONTAINER_SIZE); FILE *fp; long len; char *buf; fp = fopen(filePath, "rt"); if (fp == NULL) { printf("couldn't open the properties file"); }; fseek(fp, 0, SEEK_END); //go to end len = ftell(fp); //get position at end (length) fseek(fp, 0, SEEK_SET); //go to beg. buf = (char *) memoryAlloc(len + 1); //malloc buffer long result = fread(buf, (size_t) (len + 1), 1, fp); //read into buffer if (result < 0) { printf("Fail to read properties file ."); } fclose(fp); buf[len] = 0; char *key; char *value; const char newLineDelimiter[] = "\n"; const char spaseDelimiter[] = "="; char *token; token = strtok(buf, newLineDelimiter); LinkedList linkedList = linkedListCreate(); while (token != NULL) { linkedListAddFirst(linkedList, token); token = strtok(NULL, newLineDelimiter); } while (linkedListSize(linkedList) > 0) { char *token = (char *) linkedListRemoveFirst(linkedList); key = strtok(token, spaseDelimiter); value = strtok(NULL, spaseDelimiter); unsigned int keyId = stringTransformToInt(key, strlen(key)); hashmapPut(m->map, keyId, value); } linkedListFree(linkedList); return m; }
/* * Stream collector that will add Schedules to the standard full result json. * * This json contains a list of schedules in their entirety plus the * regular tiploc and activity lookup tables * */ int tt_schedule_result_index(Stream *s, CharBuffer *b, int stanox, int hour, bool filterHour) { struct ctx *ctx = malloc(sizeof (struct ctx)); if (ctx) { memset(ctx, 0, sizeof (struct ctx)); ctx->b = b; list_init(&ctx->list); ctx->stanox = stanox; ctx->hour = hour; ctx->filterHour = filterHour; ctx->tiploc = mapTiploc_new(); ctx->activity = hashmapCreate(10, hashmapStringHash, hashmapStringEquals); if (!stream_collect(s, NULL, next, finish, ctx, NULL)) return EXIT_SUCCESS; freeCtx(ctx); } return EXIT_FAILURE; }
/** * Creates the local peer. */ static Peer* peerCreate() { Peer* peer = calloc(1, sizeof(Peer)); if (peer == NULL) { LOG_ALWAYS_FATAL("malloc() error."); } peer->peerProxies = hashmapCreate(10, &pidHash, &pidEquals); peer->selector = selectorCreate(); pthread_mutexattr_t attributes; if (pthread_mutexattr_init(&attributes) != 0) { LOG_ALWAYS_FATAL("pthread_mutexattr_init() error."); } if (pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE) != 0) { LOG_ALWAYS_FATAL("pthread_mutexattr_settype() error."); } if (pthread_mutex_init(&peer->mutex, &attributes) != 0) { LOG_ALWAYS_FATAL("pthread_mutex_init() error."); } peer->pid = getpid(); return peer; }
int hashmap_test(void) { printf("Starting hashmap tests...\n\n"); hashmap* hmap = hashmapCreate(20); if (hashmapCount(hmap) != 0){ printf("\nTest failed. Hashmap does not initialize to empty."); return -1; } hashmapInsert(hmap, 1, 1); if (hashmapCount(hmap) != 1){ printf("\nTest failed. Hashmap does not have proper count of elements."); return -1; } int test = 0; test = (int *) hashmapGet(hmap, 1); if (test != 1){ printf("\nTest failed. Value found inside was actually %d ", test); return -1; } hashmapInsert(hmap, "Word", 2); char* word; word = (char*) hashmapGet(hmap, 2); if (strcmp(word, "Word") != 0){ printf("\nTest failed. The word found inside was actually %s", word); return -1; } test = (int*) hashmapRemove(hmap, 1); printf("\nTest 5: "); if (test == -1){ printf("\nTest failed. HASHMAPERROR returned."); return -1; } if (hashmapCount(hmap) != 1){ printf("\nTest failed. Hashmap value not actually removed"); return -1; } printf("\nTest 6: "); hashmapInsert(hmap, 2, 1); test = (int *) hashmapGet(hmap, 1); if (test != 2){ printf("\nTest failed. Value was not inserted."); return -1; } hashmapInsert(hmap, 7, 1); test = (int *) hashmapGet(hmap, 1); if (test != 7){ printf("\nTest failed. Value was not replaced."); return -1; } hashmapInsert(hmap, 'd', 13); char c = (char) hashmapGet(hmap, 13); if (c != 'd'){ printf("\nTest failed. Char 'd' was not properly inserted"); return -1; } hashmapInsert(hmap, 9, 4294967295); test = (int *) hashmapGet(hmap, 4294967295); if (test != 9){ printf("\nTest failed. 9 was not inserted"); return -1; } test = hashmapRemove(hmap, 11); if (test != -1){ printf("\nTest failed. ERROR should be returned."); return -1; } test = hashmapGet(hmap, 11); if (test != -1){ printf("\nTest failed. ERROR should be returned."); return -1; } hashmapDelete(hmap); hashmap* hmap2 = hashmapCreate(10); int x = 0; while(x < 200){ hashmapInsert(hmap2, x, x); int test2 = (int*) hashmapGet(hmap, x); if (test2 != x){ printf("\nTest failed. Improper value retrieved."); return -1; } x++; } x = 0; while (x< 200){ hashmapGet(hmap, 1); int test2 = (int*) hashmapGet(hmap, 1); if (test2 != 1){ printf("\nTest failed. Constant retrieval does not work."); return -1; } x++; } x = 0; while (x < 200){ int test2 = (int*) hashmapRemove(hmap, x); if (test2 == -1){ printf("\nTest failed. ERROR was thrown, when it shouldn't have been."); return -1; } x++; } printf("\n\nAll hashmap tests passed!\n"); hashmapDelete(hmap2); return 0; }
/* * Create the registry structure. */ Registry registryCreate(){ RegistryInternal* m = (RegistryInternal*) memoryAlloc(sizeof(RegistryInternal)); m->nodes=hashmapCreate(SMALL_CONTAINER_SIZE); return m; }
void massdns_scan(lookup_context_t *context) { memset(&stats, 0, sizeof(dns_stats_t)); size_t line_buflen = 4096; char *line = safe_malloc(line_buflen); size_t line_len = 0; struct sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = 0; int sock = socket(AF_INET, SOCK_DGRAM, 0); int socketbuf = 1024 * 1024 * 100; if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &socketbuf, sizeof(socketbuf)) != 0) { perror("Failed to adjust socket send buffer size."); } if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &socketbuf, sizeof(socketbuf)) != 0) { perror("Failed to adjust socket receive buffer size."); } bind(sock, (sockaddr_t *) &server_addr, sizeof(server_addr)); fcntl(sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK); if (sock < 0) { perror("Failed to create socket"); exit(1); } FILE *f; if(context->cmd_args.show_progress) { f = fopen(context->cmd_args.domains, "r"); if (f == NULL) { perror("Failed to open domain file"); exit(1); } while(!feof(f)) { if (0 <= getline(&line, &line_buflen, f)) { trim_end(line); strtolower(line); if (strcmp(line, "") != 0) { context->total_domains++; } } } fclose(f); } f = fopen(context->cmd_args.domains, "r"); if (f == NULL) { perror("Failed to open domain file"); exit(1); } if (geteuid() == 0) { fprintf(stderr, "You have started the program with root privileges.\n"); struct passwd *nobody = getpwnam(UNPRIVILEGED_USER); if (!context->cmd_args.root) { if (nobody && setuid(nobody->pw_uid) == 0) { fprintf(stderr, "Privileges have been dropped to \"%s\" for security reasons.\n\n", UNPRIVILEGED_USER); } else if (!context->cmd_args.root) { fprintf(stderr, "Privileges could not be dropped to \"%s\".\n" "For security reasons, this program will only run as root user when supplied with --root" "which is not recommended.\n" "It is better practice to run this program as a different user.\n", UNPRIVILEGED_USER); exit(1); } } else { fprintf(stderr, "[WARNING] Privileges were not dropped. This is not recommended.\n\n"); } } FILE *randomness = fopen("/dev/urandom", "r"); if (!randomness) { fprintf(stderr, "Failed to open /dev/urandom.\n"); exit(1); } context->current_rate = 0; context->sock = sock; context->resolvers = massdns_resolvers_from_file(context->cmd_args.resolvers); context->map = hashmapCreate(context->cmd_args.hashmap_size, hash_string, cmp_lookup); context->initial = true; gettimeofday(&context->start_time, NULL); context->next_update = context->start_time; while (true) { while (hashmapSize(context->map) < context->cmd_args.hashmap_size && !feof(f)) { if (0 <= getline(&line, &line_buflen, f)) { trim_end(line); line_len = strlen(line); strtolower(line); if(strcmp(line, "") == 0) { continue; } if (line_len > 0 && line[line_len - 1] == '.') { // Remove trailing dot from FQDN line[line_len] = 0; } lookup_t *lookup = hashmapGet(context->map, line); if (lookup == NULL) { char *value = safe_malloc(line_len + 1); strcpy(value, line); lookup = safe_malloc(sizeof(*lookup)); lookup->domain = value; lookup->tries = 0; if (fread(&lookup->transaction, 1, sizeof(lookup->transaction), randomness) != sizeof(lookup->transaction)) { fprintf(stderr, "Failed to get randomness for transaction id.\n"); exit(1); } gettimeofday(&lookup->next_lookup, NULL); hashmapPut(context->map, value, lookup); } } } if(!context->cooldown && hashmapSize(context->map) < context->cmd_args.hashmap_size) { context->cooldown = true; gettimeofday(&context->cooldown_time, NULL); } while (massdns_receive_packet(sock, massdns_handle_packet, context)); if (feof(f) && hashmapSize(context->map) == 0) { break; } hashmapForEach(context->map, handle_domain, context); } for (size_t i = 0; i < context->resolvers.len; i++) { free(((sockaddr_in_t **) context->resolvers.data)[i]); ((sockaddr_in_t **) context->resolvers.data)[i] = NULL; } free(line); free(context->resolvers.data); context->resolvers.data = NULL; print_stats(context); hashmapFree(context->map); context->map = NULL; fclose(f); fclose(randomness); }
void fileHelperLoad(FileHelper fileHelper) { FileHelperInternal *m = (FileHelperInternal *) fileHelper; fileHelperCheckCreate(m->filePath); int sizeOfInt = sizeof(int); struct direct **schemasIds = {0}; struct direct *schenaId; int size = scandir(m->filePath, &schemasIds, 0, alphasort); // loop all schemas int i; for (i = 0; i < size; i++) { schenaId = (struct direct *) schemasIds[i]; char *schemaIdString = schenaId->d_name; int schemaId = atoi(schemaIdString); if (schemaId != 0) { printf("schema %s\n", schenaId->d_name); struct direct **pagesIds = {0}; struct direct *pageStruct; char endOdString = '\0'; int pageDirLength = strlen(m->filePath); int schemaIdStringLength = strlen(schemaIdString); char slesh = '/'; char *pageDir = (char *) memoryAlloc(pageDirLength + 1 + schemaIdStringLength + 1); memcpy(pageDir, m->filePath, pageDirLength); memcpy(pageDir + pageDirLength, &slesh, 1); memcpy(pageDir + pageDirLength + 1, schemaIdString, schemaIdStringLength); memcpy(pageDir + pageDirLength + 1 + schemaIdStringLength, &endOdString, 1); // cleanBuffer(pageDir); // strcat(pageDir,m->filePath); // strcat(pageDir,"/"); // strcat(pageDir,schemaIdString); HashMap childrenRelations = hashmapCreate(SMALL_CONTAINER_SIZE); Registry registry = registryCreate(); hashmapPut(m->registryMap, schemaId, registry); PageManager pageManager = pageManagerCreate(schemaId, pageDir); hashmapPut(m->managers, schemaId, pageManager); int size = scandir(pageDir, &pagesIds, 0, alphasort); int h; //loop pages for (h = 0; h < size; h++) { //scandir (pageDir, &pagesIds, 0, alphasort); pageStruct = (struct direct *) pagesIds[h]; char *pageString = pageStruct->d_name; int pageId = atoi(pageString); if (pageId != 0) { printf("page %s\n", pageStruct->d_name); // create file path. //int i=0; int pageDirLength = strlen(pageDir); int pageStringLength = strlen(pageString); char slesh = '/'; char *filePath = (char *) memoryAlloc(pageDirLength + 1 + pageStringLength + 1); memcpy(filePath, pageDir, pageDirLength); memcpy(filePath + pageDirLength, &slesh, 1); memcpy(filePath + pageDirLength + 1, pageString, pageStringLength); memcpy(filePath + pageDirLength + 1 + pageStringLength, &endOdString, 1); FILE *fp; long len; // Create pointer to file. fp = fopen(filePath, "rb"); if (fp == NULL) { printf("couldn't open the properties file"); } fseek(fp, 0, SEEK_END); // Go to end len = ftell(fp); // Get position at end (length) // Read data to buffer char *buffer = memoryAlloc(sizeof(char) * len); // Create buffer char *pointerToFreeBuffer = buffer; fseek(fp, 0, SEEK_SET); // Go to the beginning. int result = fread(buffer, len, 1, fp); // Read into buffer if (result < 0) { printf("Fail to read file : %s", buffer); } fclose(fp); int order = 0; long index = 0; long step = 0; while (index < len) { char *start = buffer; int id; int schemaId; int numberOfAttributes; int childrenSize; int attributeSize; memcpy(&schemaId, buffer + SIZE_OF_INT * 0, SIZE_OF_INT); memcpy(&id, buffer + SIZE_OF_INT * 1, SIZE_OF_INT); memcpy(&numberOfAttributes, buffer + SIZE_OF_INT * 2, SIZE_OF_INT); buffer += SIZE_OF_INT * 3; Node node; nodeCreate(registry, id, schemaId, FALSE, &node); int h; for (h = 0; h < numberOfAttributes; h++) { memcpy(&attributeSize, buffer, SIZE_OF_INT); Attribute attribute = attributeDeserializeLocal(buffer); buffer += attributeSize; stringHashmapPut(node->attributes, attribute->name, attribute->nameLength, attribute); } memcpy(&childrenSize, buffer, SIZE_OF_INT); Array children = arrayCreate(childrenSize); hashmapPut(childrenRelations, id, children); int i; buffer += SIZE_OF_INT; int childrenIdBuffer; for (i = 0; i < childrenSize; i++) { memcpy(&childrenIdBuffer, buffer + SIZE_OF_INT, SIZE_OF_INT); void *bufferElement = memoryAlloc(childrenIdBuffer + SIZE_OF_INT * 2); memcpy(bufferElement, buffer, SIZE_OF_INT * 2 + childrenIdBuffer); arrayInsertObject(children, bufferElement); buffer += SIZE_OF_INT * 2 + childrenIdBuffer; } step = buffer - start; index += step; pageManagerRegister(pageManager, pageId, id, index - step, index, order, filePath); order++; } // Free the file buffer memoryFree(pointerToFreeBuffer); } } if (size > 0) { while (size) { size = size - 1; free(pagesIds[size]); } free(pagesIds); } hashmapIterate(childrenRelations, &updateChildren, registry); hashmapFree(childrenRelations); } } if (size > 0) { while (size) { size = size - 1; free(schemasIds[size]); } free(schemasIds); } }
/** Accepts a connection to the master peer. */ static void masterAcceptConnection(SelectableFd* listenerFd) { // Accept connection. int socket = accept(listenerFd->fd, NULL, NULL); if (socket == -1) { ALOGW("accept() error: %s", strerror(errno)); return; } ALOGD("Accepted connection as fd %d.", socket); // Get credentials. Credentials credentials; struct ucred ucredentials; socklen_t credentialsSize = sizeof(struct ucred); int result = getsockopt(socket, SOL_SOCKET, SO_PEERCRED, &ucredentials, &credentialsSize); // We might want to verify credentialsSize. if (result == -1) { ALOGW("getsockopt() error: %s", strerror(errno)); closeWithWarning(socket); return; } // Copy values into our own structure so we know we have the types right. credentials.pid = ucredentials.pid; credentials.uid = ucredentials.uid; credentials.gid = ucredentials.gid; ALOGI("Accepted connection from process %d.", credentials.pid); Peer* masterPeer = (Peer*) listenerFd->data; peerLock(masterPeer); // Make sure we don't already have a connection from that process. PeerProxy* peerProxy = hashmapGet(masterPeer->peerProxies, &credentials.pid); if (peerProxy != NULL) { peerUnlock(masterPeer); ALOGW("Alread connected to process %d.", credentials.pid); closeWithWarning(socket); return; } // Add connection to the selector. SelectableFd* socketFd = selectorAdd(masterPeer->selector, socket); if (socketFd == NULL) { peerUnlock(masterPeer); ALOGW("malloc() failed."); closeWithWarning(socket); return; } // Create a peer proxy. peerProxy = peerProxyCreate(masterPeer, credentials); peerUnlock(masterPeer); if (peerProxy == NULL) { ALOGW("malloc() failed."); socketFd->remove = true; closeWithWarning(socket); } peerProxy->connections = hashmapCreate(10, &pidHash, &pidEquals); peerProxySetFd(peerProxy, socketFd); }
static int load_config(const char *config) { struct config_parser *cp; char *value; int i; if (!config || strlen(config) == 0) cp = config_parser_init(TBOOT_CONFIG); else cp = config_parser_init(config); if (!cp) goto err; /* init config with default values */ tboot_config = hashmapCreate(array_size(tc_keys), strhash, strcompare); if (!tboot_config) goto err; for (i = 0; tc_keys[i]; i++) hashmapPut(tboot_config, (void *)tc_keys[i], (void *)tc_values[i]); /* parse config file */ value = config_parser_get(cp, UI_CONF_KEY); if (value) tboot_config_set(UI_CONF_KEY, value); value = config_parser_get(cp, DISK_CONFIG_KEY); if (value) tboot_config_set(DISK_CONFIG_KEY, value); value = config_parser_get(cp, PUSH_DIR_KEY); if (value) tboot_config_set(PUSH_DIR_KEY, value); value = config_parser_get(cp, ROOTFS_KEY); if (value) tboot_config_set(ROOTFS_KEY, value); value = config_parser_get(cp, ENABLE_NFS_KEY); if (value) tboot_config_set(ENABLE_NFS_KEY, value); value = config_parser_get(cp, NFSURL_KEY); if (value) tboot_config_set(NFSURL_KEY, value); value = config_parser_get(cp, DISK_FORCE_KEY); if (value) tboot_config_set(DISK_FORCE_KEY, value); value = config_parser_get(cp, BAT_THRESHOLD_KEY); if (value) tboot_config_set(BAT_THRESHOLD_KEY, value); value = config_parser_get(cp, LCD_DIM_TIMEOUT_KEY); if (value) tboot_config_set(LCD_DIM_TIMEOUT_KEY, value); value = config_parser_get(cp, LCD_OFF_TIMEOUT_KEY); if (value) tboot_config_set(LCD_OFF_TIMEOUT_KEY, value); value = config_parser_get(cp, LCD_DIM_BRIGHTNESS_KEY); if (value) tboot_config_set(LCD_DIM_BRIGHTNESS_KEY, value); config_parser_free(cp); tboot_config_dump(); return 0; err: if (cp) config_parser_free(cp); if (tboot_config) hashmapFree(tboot_config); return -1; }
struct texture_cache* texture_cache_new() { struct texture_cache* cache = STRUCT_NEW(texture_cache); cache->cache = hashmapCreate(32, hash_str, hash_equal); return cache; }
struct s2_touch_event * s2_touch_event_alloc() { struct s2_touch_event * event = s2_calloc(1, sizeof(struct s2_touch_event)); event->touches = hashmapCreate(1, s2_touch_event_hash, s2_touch_event_equal); return event; }
struct sprite_frame_cache* sprite_frame_cache_new() { struct sprite_frame_cache* c = STRUCT_NEW(sprite_frame_cache); c->cache = hashmapCreate(128, hash_str, hash_equal); c->nframes = 0; return c; }