void v_participantFree( v_participant p) { v_message builtinMsg; v_participant found; v_entity e; v_kernel kernel; /* Not clear yet why builtin subscriber lock and participant lock are not taken now? * Also not clear why observer lock is not taken but is freed at the end! */ if (p != NULL) { assert(C_TYPECHECK(p,v_participant)); kernel = v_objectKernel(p); if (!v_observableRemoveObserver(v_observable(kernel),v_observer(p), NULL)) { if (v_participantName(p) != NULL) { OS_REPORT_1(OS_WARNING,"v_participantFree",0, "Participant '%s' cannot disconnect from Kernel events", v_participantName(p)); } else { OS_REPORT(OS_WARNING,"v_participantFree",0, "Participant cannot disconnect from Kernel events"); } } builtinMsg = v_builtinCreateParticipantInfo(kernel->builtin,p); v_writeDisposeBuiltinTopic(kernel, V_PARTICIPANTINFO_ID, builtinMsg); c_free(builtinMsg); builtinMsg = v_builtinCreateParticipantInfo(kernel->builtin,p); v_unregisterBuiltinTopic(kernel, V_PARTICIPANTINFO_ID, builtinMsg); c_free(builtinMsg); if (p->builtinSubscriber) { v_subscriberFree(p->builtinSubscriber); p->builtinSubscriber = NULL; } while ((e = c_take(p->entities)) != NULL) { switch (v_objectKind(e)) { case K_PUBLISHER: v_publisherFree(v_publisher(e)); break; case K_SUBSCRIBER: v_subscriberFree(v_subscriber(e)); break; case K_WAITSET: v_waitsetFree(v_waitset(e)); break; default: OS_REPORT_1(OS_WARNING,"Kernel Participant",0, "Illegal contained object (%s)", v_participantName(p)); break; } c_free(e); /* deref o since c_take will not */ } found = v_removeParticipant(kernel,p); assert(found == p); c_free(found); v_observerFree(v_observer(p)); } }
// static int net_close( lua_State* L, const char* mt ); // Lua: net.delete( socket/server ) // call close() first // server: disconnect server, unref everything // socket: unref everything static int net_delete( lua_State* L, const char* mt ) { NODE_DBG("net_delete is called.\n"); bool isserver = false; if (mt!=NULL && c_strcmp(mt, "net.server")==0) isserver = true; else if (mt!=NULL && c_strcmp(mt, "net.socket")==0) isserver = false; else { NODE_DBG("wrong metatable for net_delete.\n"); return 0; } // net_close( L, mt ); // close it first lnet_userdata *nud = (lnet_userdata *)luaL_checkudata(L, 1, mt); luaL_argcheck(L, nud, 1, "Server/Socket expected"); if(nud==NULL){ NODE_DBG("userdata is nil.\n"); return 0; } if(nud->pesp_conn){ // for client connected to tcp server, this should set NULL in disconnect cb nud->pesp_conn->reverse = NULL; if(!isserver) // socket is freed here { if(nud->pesp_conn->type == ESPCONN_UDP){ if(nud->pesp_conn->proto.udp) c_free(nud->pesp_conn->proto.udp); nud->pesp_conn->proto.udp = NULL; } else if (nud->pesp_conn->type == ESPCONN_TCP) { if(nud->pesp_conn->proto.tcp) c_free(nud->pesp_conn->proto.tcp); nud->pesp_conn->proto.tcp = NULL; } c_free(nud->pesp_conn); } nud->pesp_conn = NULL; // for socket, it will free this when disconnected } // free (unref) callback ref if(LUA_NOREF!=nud->cb_connect_ref){ luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_connect_ref); nud->cb_connect_ref = LUA_NOREF; } if(LUA_NOREF!=nud->cb_reconnect_ref){ luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_reconnect_ref); nud->cb_reconnect_ref = LUA_NOREF; } if(LUA_NOREF!=nud->cb_disconnect_ref){ luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_disconnect_ref); nud->cb_disconnect_ref = LUA_NOREF; } if(LUA_NOREF!=nud->cb_receive_ref){ luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_receive_ref); nud->cb_receive_ref = LUA_NOREF; } if(LUA_NOREF!=nud->cb_send_ref){ luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_send_ref); nud->cb_send_ref = LUA_NOREF; } if(LUA_NOREF!=nud->cb_dns_found_ref){ luaL_unref(L, LUA_REGISTRYINDEX, nud->cb_dns_found_ref); nud->cb_dns_found_ref = LUA_NOREF; } lua_gc(gL, LUA_GCSTOP, 0); if(LUA_NOREF!=nud->self_ref){ luaL_unref(L, LUA_REGISTRYINDEX, nud->self_ref); nud->self_ref = LUA_NOREF; } lua_gc(gL, LUA_GCRESTART, 0); return 0; }
v_networkQueue v_networkQueueNew( c_base base, c_ulong queueSize, c_ulong priority, c_bool reliable, c_bool P2P, c_time resolution, v_networkQueueStatistics statistics) { v_networkQueue result = NULL; c_type type; c_equality equality; c_bool hasChanged; c_time now; type = c_resolve(base, "kernelModule::v_networkQueue"); assert(type); result = v_networkQueue(c_new(type)); c_free(type); if (result) { /* Queue properties */ result->maxMsgCount = queueSize; result->currentMsgCount = 0; /* Cached type */ result->statusMarkerType = c_resolve(base, "kernelModule::v_networkStatusMarker"); assert(result->statusMarkerType != NULL); result->sampleType = c_resolve(base, "kernelModule::v_networkQueueSample"); assert(result->sampleType != NULL); /* Linked list of in-use marker items */ result->firstStatusMarker = NULL; result->lastStatusMarker = NULL; /* Linked list of free marker and message items */ result->freeStatusMarkers = NULL; result->freeSamples = NULL; /* Init cv stuff */ c_mutexInit(&result->mutex, SHARED_MUTEX); c_condInit(&result->cv, &result->mutex, SHARED_COND); /* Currently no differentiation wrt qos */ result->priority = priority; result->reliable = reliable; result->P2P = P2P; result->statistics = statistics; equality = c_timeCompare(C_TIME_ZERO, resolution); if (equality == C_EQ) { result->periodic = FALSE; result->resolution = C_TIME_INFINITE; result->msecsResolution = 0xFFFFFFFF; result->phaseMilliSeconds = 0; result->nextWakeup = C_TIME_INFINITE; } else { assert(equality == C_LT); result->periodic = TRUE; result->resolution = resolution; TIME_TO_MSEC(resolution, result->msecsResolution); /* A semi-random phase to avoid wake-ups at the same time */ now = v_timeGet(); result->phaseMilliSeconds = ((c_ulong)(now.nanoseconds/1000000 * 1.618)) % result->msecsResolution; v_networkQueueUpdateNextWakeup(result, &hasChanged); assert(hasChanged); } result->threadWaiting = FALSE; } else { OS_REPORT(OS_ERROR, "v_networkQueueNew",0, "Failed to allocate network queue."); } return result; }
void v_networkReaderEntryFree( v_networkReaderEntry e) { c_free(c_object(e)); }
void v_leaseRenew( v_lease lease, v_duration* leaseDuration /* may be NULL */) { c_iter observers = NULL; v_leaseManager observer; c_time newExpiryTime; c_equality cmp; if (lease != NULL) { assert(C_TYPECHECK(lease, v_lease)); v_leaseLock(lease); /* Is a new lease duration provided, if so replace the current lease * duration with the new one */ if(leaseDuration != NULL) { lease->duration = *leaseDuration; } /* else do nothing */ /* Calculate the new expiry time */ newExpiryTime = c_timeAdd(v_timeGet(), lease->duration); /* Is the new expiryTime earlier then the current expiryTime? */ cmp = c_timeCompare(newExpiryTime, lease->expiryTime); /* Always replace the current expiry time with the new expiryTime */ lease->expiryTime = newExpiryTime; /* If the new expiryTime is earlier then the previous expiryTime. Then * this means the observers must be notified so they can take the * earlier expiryTime into account */ if (cmp == C_LT) { /* Collect all observers, so they can be notified of the lease change * Must do a seperate collect as the lease mutex is 'lower' then the * leaseManager mutex. So to prevent deadlock we can not directly notify * the lease manager as we walk the collection */ if(lease->observers) { c_walk(lease->observers, v_leaseCollectObservers, &observers); } v_leaseUnlock(lease); if(observers) { observer = v_leaseManager(c_iterTakeFirst(observers)); while (observer != NULL) { v_leaseManagerNotify( observer, lease, V_EVENT_LEASE_RENEWED); c_free(observer); observer = v_leaseManager(c_iterTakeFirst(observers)); } c_iterFree(observers); } } else { /* No need to notify observers, the new expiryTime is not earlier * then what it was before. */ v_leaseUnlock(lease); } } }
void v_networkQueueStatisticsDeinit(v_networkQueueStatistics nqs) { assert(nqs != NULL); assert(C_TYPECHECK(nqs, v_networkQueueStatistics)); c_free(nqs->name); }
static c_bool createMessageKeyList( c_type messageType, const c_char *topicKeyExpr, c_array *keyListRef) { c_array keyList; c_type fieldType; c_field field; c_iter splitNames, newNames; c_char *name, *newName; c_long i,length,sres; assert(keyListRef != NULL); *keyListRef = NULL; if (topicKeyExpr == NULL) { return TRUE; } newNames = NULL; splitNames = c_splitString(topicKeyExpr,", \t"); while ((name = c_iterTakeFirst(splitNames)) != NULL) { #define PATH_SEPARATOR "." #define PREFIX "userData" length = strlen(PREFIX) + sizeof(PATH_SEPARATOR) + strlen(name); newName = (char *)os_malloc(length); sres = snprintf(newName,length,"%s"PATH_SEPARATOR"%s",PREFIX, name); assert(sres == (length-1)); #undef PREFIX #undef PATH_SEPARATOR os_free(name); newNames = c_iterAppend(newNames,newName); } c_iterFree(splitNames); length = c_iterLength(newNames); if (length == 0) { return TRUE; } fieldType = c_field_t(c_getBase(messageType)); keyList = c_arrayNew(fieldType,length); c_free(fieldType); i=0; while ((name = c_iterTakeFirst(newNames)) != NULL) { field = c_fieldNew(messageType,name); if (field == NULL) { OS_REPORT_1(OS_API_INFO, "create message key list failed", 21, "specified key field name %s not found", name); os_free(name); c_iterFree(newNames); c_free(keyList); return FALSE; } keyList[i++] = field; os_free(name); } c_iterFree(newNames); *keyListRef = keyList; return TRUE; }
void v_lifespanAdminRemove( v_lifespanAdmin admin, v_lifespanSample sample) { c_equality eq; assert(C_TYPECHECK(admin,v_lifespanAdmin)); assert(C_TYPECHECK(sample,v_lifespanSample)); eq = c_timeCompare(sample->expiryTime, C_TIME_INFINITE); if (eq == C_EQ) { return; /* no insert, since sample never expires! */ } CHECK_ADMIN(admin, sample); if (sample == admin->head) { assert(sample->prev == NULL); if (sample == admin->tail) { assert(c_refCount(sample) > 2); assert(sample->next == NULL); c_free(sample); /* free tail reference */ admin->head = NULL; admin->tail = NULL; } else { assert(c_refCount(sample) > 1); admin->head = sample->next; /* transfer refcount */ if (sample->next) { sample->next = NULL; admin->head->prev = NULL; /* or sample->next->prev = NULL */ } } c_free(sample); /* free head reference */ admin->sampleCount--; } else { if (sample == admin->tail) { assert(sample->prev); assert(c_refCount(sample) > 2); /* Both tail and next field from prev sample. */ assert(sample->next == NULL); c_free(admin->tail); admin->tail = c_keep(sample->prev); sample->prev = NULL; c_free(admin->tail->next); /* admin->tail->next == sample */ admin->tail->next = NULL; admin->sampleCount--; } else { if ((sample->next != NULL) && (sample->prev != NULL)) { assert(c_refCount(sample) > 1); assert(admin->sampleCount > 0); v_lifespanSample(sample->prev)->next = sample->next; /* transfer refcount */ sample->next->prev = sample->prev; sample->next = NULL; sample->prev = NULL; c_free(sample); admin->sampleCount--; } /* else sample not in admin, so no removing needed */ } } CHECK_ADMIN(admin, sample); }
void v_groupStreamNotify( v_groupStream stream, v_event e, c_voidp userData) { struct groupConnected data; c_iter partitions; c_bool interested; v_partition partition, found; OS_UNUSED_ARG(userData); assert(stream != NULL); assert(C_TYPECHECK(stream,v_groupStream)); if (e) { if (e->kind == V_EVENT_NEW_GROUP) { v_observerLock(v_observer(stream)); /* * Check if group fits interest. This extra steps are needed because * the groupActionStream does not create the groups that match the * subscriber qos partition expression on creation. It only needs to * connect to new groups once they are created. This is a different * approach then for a data reader. */ partition = v_group(e->userData)->partition; /* * Because already existing partitions are created and added to the * subscriber of the groupActionStream at creation time, these * partitions can be resolved from the subscriber. This is necessary to * determine whether the groupActionStream should connect to the new * group or if it is already connected. */ partitions = v_subscriberLookupPartitions(v_reader(stream)->subscriber, v_partitionName(partition)); interested = FALSE; found = v_partition(c_iterTakeFirst(partitions)); while(found){ if(interested == FALSE){ if(strcmp(v_partitionName(partition), v_partitionName(found)) == 0){ interested = TRUE; } } c_free(found); found = v_partition(c_iterTakeFirst(partitions)); } c_iterFree(partitions); if(interested == TRUE){ /* * This means the group is interesting for this * groupActionStream. Now I have to check if the stream is already * connected to this group, because we wouldn't want to connect * multiple times to one single group. */ data.connected = FALSE; data.group = v_group(e->userData); c_walk(stream->groups, (c_action)isGroupConnected, &data); if(data.connected == FALSE){ /* * The stream is not connected to the group yet, so connect now. */ v_groupStreamSubscribeGroup(stream, v_group(e->userData)); } } v_observerUnlock(v_observer(stream)); } } return; }
static void nw_channelWriterMain( v_entity e, c_voidp arg) { v_networkReader reader; nw_channelWriter channelWriter; c_bool newGroupAvailable; v_networkQueue qosQueue; v_networkReaderWaitResult waitResult; c_long bytesWritten; /* Total number of messages sent to the network */ c_ulong writtenCountMessages; /* Total number of bytes sent to the network */ c_ulong writtenCountBytes; /* Total number of bytes sent to the network during one burst */ c_ulong writtenCountBytesThisBurst; /* Number of message sent to the network after last report */ c_ulong writtenCountMessagesReport; v_message message; v_networkReaderEntry entry; c_ulong sequenceNumber; v_gid sender; c_bool sendTo; v_gid receiver; c_time sendBefore; c_ulong priority; c_bool more = TRUE; c_bool slowingDown; c_ulong timeoutCount; nw_signedLength credits; v_networking n; NW_STRUCT(plugSendStatistics) pss = {0,0,0,0,0,0,0,0,0,0, {0, {{0,0}, 0}, {{0,0}, 0}, {0.0,0}}, {0, {{0,0}, 0}, {{0,0}, 0}, {0.0,0}}, 0,0,0}; v_fullCounterInit(&(pss.adminQueueAcks)); v_fullCounterInit(&(pss.adminQueueData)); reader = v_networkReader(e); channelWriter = (nw_channelWriter)arg; /* This line is needed as long as the discovery channel is not yet implemented */ writtenCountBytesThisBurst = 0; writtenCountMessages = 0; writtenCountBytes = 0; writtenCountMessagesReport = 0; slowingDown = FALSE; timeoutCount = 0; credits = 0; while (!(int)nw_runnableTerminationRequested((nw_runnable)channelWriter)) { /* Wait for data on the reader */ if (!slowingDown) { waitResult = v_networkReaderWait(reader, channelWriter->queueId, &qosQueue); } else { waitResult = v_networkReaderWaitDelayed(reader, channelWriter->queueId, &qosQueue); NW_CONFIDENCE(waitResult & (V_WAITRESULT_TIMEOUT | V_WAITRESULT_TRIGGERED)); } if ((waitResult & V_WAITRESULT_TRIGGERED) && (!nw_runnableTerminationRequested((nw_runnable)channelWriter))) { /* If necessary, check if any new groups need to be added */ newGroupAvailable = nw_channelUserRetrieveNewGroup( (nw_channelUser)channelWriter, &entry); while (newGroupAvailable) { /* Create a new channel on the network */ /* No, do not call any function. With the new design, * a channelWriter does not need to know anything about this * new group. Maybe at a later stage. */ /* nw_channelAddGroup((nw_channel)channelWriter->sendChannel, entry); */ /* And notify we are connected */ v_networkReaderEntryNotifyConnected(entry,channelWriter->serviceName); newGroupAvailable = nw_channelUserRetrieveNewGroup( (nw_channelUser)channelWriter, &entry); } } /* Resend data should also obey max_burst_size * Each clocktick, the remaining credits of the last period and a * third of the new max_burst_size budget may be used for resend data. * The rest of the budget is assigned after that, and can be used to * flush stored buffers of send fresh data. */ if (waitResult & V_WAITRESULT_TIMEOUT) { /* * The periodic action is needed for every clocktick. * This will also update the credits, for the amount of bandwidth * available in the coming period. */ /*stat update routine */ n = v_networking(v_subscriber(v_reader(reader)->subscriber)->participant); /* update statistics */ if (v_entity(n)->statistics) { if (!pss.enabled) { pss.enabled =1; } /* sync plug stats */ nw_updatePlugSendStatistics(&pss,channelWriter); nw_SendChannelUpdate(v_networkingStatistics(v_entity(n)->statistics)->channels[channelWriter->stat_channel_id],channelWriter->scs); } nw_sendChannelPeriodicAction(channelWriter->sendChannel,&credits,&pss); /*struc call*/ /* A flush is needed if we are slowing down. */ if (slowingDown) { /* The return value is true is all data has been sent. * Afterwards, credits will contain the new amount of allowed * bytes. * We are using a special flush function here that flushes full * buffers only */ slowingDown = !nw_sendChannelFlush(channelWriter->sendChannel, FALSE, &credits, &pss); } } if ((waitResult & V_WAITRESULT_MSGWAITING) && !slowingDown) { /* Messages are waiting... */ writtenCountBytesThisBurst = 0; more= TRUE; while (more && ((nw_signedLength)writtenCountBytesThisBurst <= credits)) { /* Take any new messages */ v_networkQueueTakeFirst(qosQueue, &message, &entry, &sequenceNumber, &sender, &sendTo, &receiver, &sendBefore, &priority, &more); NW_CONFIDENCE(message != NULL); NW_CONFIDENCE(entry != NULL); if (!(NW_SECURITY_CHECK_FOR_PUBLISH_PERMISSION_OF_SENDER_ON_SENDER_SIDE(entry))) { bytesWritten = 0; /* indicates that nothing has been written */ NW_REPORT_WARNING_2( "nw_channelWriterMain", "Channel \"%s\" could not deliver message 0x%x : message dropped!", ((nw_runnable)channelWriter)->name, message); } else { bytesWritten = nw_sendChannelWrite(channelWriter->sendChannel, entry, message, &credits ,&pss); /* stat struc plug vars */ if (bytesWritten == 0) { NW_REPORT_WARNING_2( "nw_channelWriterMain", "Channel \"%s\" could not deliver message 0x%x : message dropped!", ((nw_runnable)channelWriter)->name, message); } /*numberOfMessagesSent stats*/ if (pss.enabled) { channelWriter->scs->numberOfMessagesSent++; } assert( bytesWritten > 0); /* if permission grantedm the value must be greater 0 */ } writtenCountBytesThisBurst += bytesWritten; #define NW_IS_BUILTIN_DOMAINNAME(name) ((int)(name)[0] == (int)'_') /* Do not trace for internal partitions */ if (bytesWritten>0 && /* might be 0 if access control refuses write permission */ !NW_IS_BUILTIN_DOMAINNAME( v_partitionName(v_groupPartition(entry->group)))) { #undef NW_IS_BUILTIN_DOMAINNAME writtenCountBytes += bytesWritten; writtenCountMessages++; writtenCountMessagesReport++; if (writtenCountMessagesReport == channelWriter->reportInterval) { NW_TRACE_3(Send, 3, "Channel %s: %u messages (%u bytes) " "taken from queue and written to network", ((nw_runnable)channelWriter)->name, writtenCountMessages, writtenCountBytes); writtenCountMessagesReport = 0; } NW_TRACE_3(Send, 4, "Channel %s: data message taken from queue, " "and written to network (partition = %s, topic = %s)", ((nw_runnable)channelWriter)->name, v_partitionName(v_groupPartition(entry->group)), v_topicName(v_groupTopic(entry->group))); } c_free(message); c_free(entry); } slowingDown = !nw_sendChannelFlush(channelWriter->sendChannel, TRUE, &credits, &pss); } } NW_TRACE_3(Send, 2, "Channel %s: %u messages (%u bytes) taken from queue and " "written to network", ((nw_runnable)channelWriter)->name, writtenCountMessages, writtenCountBytes); }
u_group u_groupNew( u_participant participant, const c_char *partitionName, const c_char *topicName, v_duration timeout) { u_result r; v_participant kparticipant; v_kernel kernel; v_topic ktopic; v_partition kpartition; v_group kgroup; c_iter topics; os_time delay; u_group group = NULL; if ((partitionName != NULL) && (topicName != NULL)) { if (participant != NULL) { r = u_entityWriteClaim(u_entity(participant), (v_entity*)(&kparticipant)); if (r == U_RESULT_OK){ assert(kparticipant); kernel = v_objectKernel(kparticipant); topics = v_resolveTopics(kernel,topicName); if (c_iterLength(topics) == 0) { c_iterFree(topics); delay.tv_sec = timeout.seconds; delay.tv_nsec = timeout.nanoseconds; os_nanoSleep(delay); topics = v_resolveTopics(v_objectKernel(kparticipant), topicName); } if (c_iterLength(topics) > 1) { OS_REPORT_1(OS_WARNING, "u_groupNew", 0, "Internal error: " "Multiple topics found with name = <%s>.", topicName); } ktopic = c_iterTakeFirst(topics); /* If ktopic == NULL, the topic definition is unknown. * This is not critical since it may become known in the near future. * In that case the caller is responsible for retrying to create this group, * and log something if, eventually, the group still cannot be created. */ if (ktopic != NULL) { kpartition = v_partitionNew(kernel, partitionName, NULL); if (kpartition != NULL) { kgroup = v_groupSetCreate(kernel->groupSet, kpartition, ktopic); if (kgroup != NULL) { group = u_groupCreate(kgroup, participant); if (group == NULL) { OS_REPORT_2(OS_ERROR,"u_groupNew",0, "Create proxy failed. " "For Partition <%s> and Topic <%s>.", partitionName, topicName); } c_free(kgroup); } else { OS_REPORT_2(OS_ERROR,"u_groupNew",0, "Create kernel entity failed. " "For Partition <%s> and Topic <%s>.", partitionName, topicName); } c_free(kpartition); } else { OS_REPORT_2(OS_ERROR,"u_groupNew", 0, "Failed to create partition. " "For Partition <%s> and Topic <%s>.", partitionName, topicName); } c_free(ktopic); } ktopic = c_iterTakeFirst(topics); while (ktopic != NULL) { c_free(ktopic); ktopic = c_iterTakeFirst(topics); } c_iterFree(topics); r = u_entityRelease(u_entity(participant)); } else { OS_REPORT_2(OS_ERROR,"u_groupNew",0, "Claim kernel participant failed." "For Partition <%s> and Topic <%s>.", partitionName, topicName); } } else { OS_REPORT_2(OS_ERROR,"u_groupNew",0, "No participant specified. " "For Partition <%s> and Topic <%s>.", partitionName, topicName); } } else { OS_REPORT_2(OS_ERROR,"u_groupNew",0, "Illegal parameter." "partitionName = <0x%x>, topicName = <0x%x>.", partitionName, topicName); } return group; }
int sircc_highlighter_init_escape_sequences(struct sircc_highlighter *highlighter, const char *str, size_t sz) { const char *and; const char *ptr; size_t len; size_t nb_sequences; nb_sequences = sizeof(sircc_highlighting_sequences) / sizeof(sircc_highlighting_sequences[0]); ptr = str; len = sz; while (len > 0) { const char *sequence; size_t toklen; and = memchr(ptr, '&', len); if (and) { toklen = (size_t)(and - ptr); } else { toklen = len; } sequence = NULL; for (size_t i = 0; i < nb_sequences; i++) { const char *name; name = sircc_highlighting_sequences[i].name; if (toklen == strlen(name) && memcmp(ptr, name, toklen) == 0) { sequence = sircc_highlighting_sequences[i].sequence; break; } } if (!sequence) { char tmp[toklen + 1]; c_strlcpy(tmp, ptr, toklen + 1); c_set_error("unknown display attribute '%s'", tmp); return -1; } if (highlighter->sequence) { char *tmp; c_asprintf(&tmp, "%s%s", highlighter->sequence, sequence); c_free(highlighter->sequence); highlighter->sequence = tmp; } else { highlighter->sequence = strdup(sequence); } ptr += toklen; len -= toklen; if (and) { ptr++; len--; } } return 0; }
v_historyResult v_readerWaitForHistoricalDataWithCondition( v_reader _this, c_char* filter, c_char* params[], c_ulong paramsLength, c_time minSourceTime, c_time maxSourceTime, struct v_resourcePolicy *resourceLimits, c_time timeout) { c_iter entries; c_object e; v_historyResult result; v_historicalDataRequest request; c_bool doRequest, doWait; struct historicalWaitArg arg; C_STRUCT(v_event) event; arg._expire_time = c_timeAdd(v_timeGet(), timeout); arg._status = TRUE; request = v_historicalDataRequestNew(v_objectKernel(_this), filter, params, paramsLength, minSourceTime, maxSourceTime, resourceLimits); if(request){ V_READER_LOCK(_this); if(_this->historicalDataRequest) { /* Historical data request already in progress or complete, check * whether request is equal to the original one. */ doRequest = FALSE; if(v_historicalDataRequestEquals(request, _this->historicalDataRequest)){ /* Request is equal to original request*/ result = V_HISTORY_RESULT_OK; if(_this->historicalDataComplete){ /* Request has already been fulfilled. Consider this call * a no-operation. */ doWait = FALSE; } else { /* Request is still in progress, wait for data to arrive*/ doWait = TRUE; } } else { /* The requested parameters are not equal to the originally * requested set. Return a precondition not met. */ doWait = FALSE; result = V_HISTORY_RESULT_PRE_NOT_MET; } c_free(request); } else { /* No active request, so validate it now.*/ if(v_historicalDataRequestIsValid(request, _this)){ /* This request is valid, so request data.*/ doRequest = TRUE; doWait = TRUE; result = V_HISTORY_RESULT_OK; _this->historicalDataRequest = request; } else { /* Request is not valid, so return bad parameter.*/ doRequest = FALSE; doWait = FALSE; result = V_HISTORY_RESULT_BAD_PARAM; c_free(request); } } V_READER_UNLOCK(_this); } else { doRequest = FALSE; doWait = FALSE; result = V_HISTORY_RESULT_ERROR; } if(doWait){ v_readerEntrySetLock(_this); entries = c_select(_this->entrySet.entries, 0); v_readerEntrySetUnlock(_this); if(doRequest){ /* Historical data must be requested, since this is the first time * the operation is called and the request is valid. */ if (_this->qos->durability.kind == V_DURABILITY_VOLATILE) { /* If reader is volatile, the historical data from the * group(s) has/have not been retrieved yet, so do it now. */ e = c_iterTakeFirst(entries); while (e != NULL) { getHistoricalData(e, _this->historicalDataRequest); c_free(e); e = c_iterTakeFirst(entries); } c_iterFree(entries); } event.kind = V_EVENT_HISTORY_REQUEST; event.source = v_publicHandle(v_public(_this)); event.userData = _this->historicalDataRequest; v_observableNotify(v_observable(v_objectKernel(_this)),&event); } V_READER_LOCK(_this); if(!_this->historicalDataComplete){ if (c_timeCompare(timeout, C_TIME_INFINITE) != C_EQ) { if (c_condTimedWait(&_this->historicalDataCondition, &V_READER_GET_LOCK(_this), timeout) != SYNC_RESULT_SUCCESS) { result = V_HISTORY_RESULT_TIMEOUT; } } else if (c_condWait(&_this->historicalDataCondition, &V_READER_GET_LOCK(_this)) != SYNC_RESULT_SUCCESS) { result = V_HISTORY_RESULT_TIMEOUT; } assert( (result == V_HISTORY_RESULT_OK) == _this->historicalDataComplete); } V_READER_UNLOCK(_this); } return result; }
void pcre_c_free(void *p) { //fprintf(stderr, "pcre_c_free %p\n", p); c_free(p); }
txMachine* fxCloneMachine(txCreation* theCreation, txMachine* theMachine, txString theName, void* theContext) { txMachine* the = (txMachine *)c_calloc(sizeof(txMachine), 1); if (the) { txJump aJump; aJump.nextJump = C_NULL; aJump.stack = C_NULL; aJump.scope = C_NULL; aJump.frame = C_NULL; aJump.code = C_NULL; aJump.flag = 0; the->firstJump = &aJump; if (c_setjmp(aJump.buffer) == 0) { txInteger anIndex; txSlot* aSlot; txSlot** aSlotAddress; txSlot* aSharedSlot; txSlot* aTemporarySlot; txID anID; #if __FSK_LAYER__ FskInstrumentedItemNew(the, theName, &gXSTypeInstrumentation); #endif #ifdef mxDebug the->echoSize = 1 * 1024; the->echoBuffer = (txString)c_malloc(the->echoSize); if (!the->echoBuffer) fxJump(the); //fxConnect(the); the->name = theName; the->sorter = (txSlot**)c_malloc(theCreation->keyCount * sizeof(txSlot*)); if (!the->sorter) fxJump(the); the->breakOnExceptionFlag = 1; #endif #ifdef mxProfile the->profileID = theMachine->profileID; the->profileBottom = c_malloc(XS_PROFILE_COUNT * sizeof(txProfileRecord)); if (!the->profileBottom) fxJump(the); the->profileCurrent = the->profileBottom; the->profileTop = the->profileBottom + XS_PROFILE_COUNT; #endif the->archive = theMachine->archive; the->dtoa = fxNew_dtoa(); if (!the->dtoa) fxJump(the); theCreation->keyCount = theMachine->keyCount; theCreation->nameModulo = theMachine->nameModulo; theCreation->symbolModulo = theMachine->symbolModulo; fxAllocate(the, theCreation); the->sharedMachine = theMachine; c_memcpy(the->nameTable, theMachine->nameTable, the->nameModulo * sizeof(txSlot *)); c_memcpy(the->symbolTable, theMachine->symbolTable, the->symbolModulo * sizeof(txSlot *)); c_memcpy(the->keyArray, theMachine->keyArray, the->keyCount * sizeof(txSlot *)); the->keyIndex = theMachine->keyIndex; the->keyOffset = the->keyIndex; the->aliasCount = theMachine->aliasCount; the->aliasArray = (txSlot **)c_calloc(the->aliasCount, sizeof(txSlot*)); if (!the->aliasArray) fxJump(the); /* mxGlobal */ fxNewInstance(the); aSlot = the->stack->value.reference; aSlot->flag = XS_VALUE_FLAG; aSlot->next = fxNewSlot(the); aSlot = aSlot->next; aSlot->value.table.address = (txSlot**)fxNewChunk(the, theCreation->keyCount * sizeof(txSlot*)); aSlot->value.table.length = theCreation->keyCount; aSlot->kind = XS_GLOBAL_KIND; c_memset(aSlot->value.table.address, 0, theCreation->keyCount * sizeof(txSlot*)); aSlotAddress = aSlot->value.table.address; aSharedSlot = theMachine->stackTop[-1].value.reference->next->next; while (aSharedSlot) { aSlot->next = aTemporarySlot = fxDuplicateSlot(the, aSharedSlot); anID = aTemporarySlot->ID & 0x7FFF; aSlotAddress[anID] = aTemporarySlot; aSharedSlot = aSharedSlot->next; aSlot = aSlot->next; } /* mxException */ mxPushUndefined(); for (anIndex = mxObjectPrototypeStackIndex; anIndex < mxModulePathsStackIndex; anIndex++) *(--the->stack) = theMachine->stackTop[-1 - anIndex]; /* mxModulePaths */ mxPushUndefined(); /* mxImportingModules */ fxNewInstance(the); /* mxLoadingModules */ fxNewInstance(the); /* mxLoadedModules */ fxNewInstance(the); /* mxResolvingModules */ fxNewInstance(the); /* mxRunningModules */ fxNewInstance(the); /* mxRequiredModules */ fxNewInstance(the); /* mxModules */ mxPushUndefined(); /* mxPendingJobs */ fxNewInstance(the); /* mxRunningJobs */ fxNewInstance(the); /* mxFiles */ mxPushList(); #ifdef mxDebug aSharedSlot = theMachine->stackTop[-1 - mxFilesStackIndex].value.list.first; aSlotAddress = &(the->stack->value.list.first); while (aSharedSlot) { *aSlotAddress = fxDuplicateSlot(the, aSharedSlot); aSharedSlot = aSharedSlot->next; aSlotAddress = &((*aSlotAddress)->next); } #endif /* mxBreakpoints */ mxPushList(); /* shared */ for (anIndex = mxHostsStackIndex; anIndex < mxStackIndexCount; anIndex++) *(--the->stack) = theMachine->stackTop[-1 - anIndex]; mxPush(mxSetPrototype); fxNewSetInstance(the); mxPull(mxModulePaths); mxPush(mxObjectPrototype); fxNewWeakSetInstance(the); mxPull(mxModules); the->collectFlag = XS_COLLECTING_FLAG; the->context = theContext; #ifdef mxDebug if (fxGetAutomatic(the)) fxLogin(the); #endif the->firstJump = C_NULL; } else { #if __FSK_LAYER__ FskInstrumentedItemDispose(the); #endif fxFree(the); c_free(the); the = NULL; } } return the; }
c_ulong v_networkReaderCreateQueue( v_networkReader reader, c_ulong queueSize, c_ulong priority, c_bool reliable, c_bool P2P, c_time resolution, c_bool useAsDefault, const c_char *name) { c_ulong result = 0; v_networkQueue queue; v_networkReaderStatistics s; v_networkQueueStatistics nqs; v_networkingStatistics nws; v_networkChannelStatistics ncs; v_kernel kernel; v_networking n; v_participant p; kernel = v_objectKernel(reader); if (reader->nofQueues < NW_MAX_NOF_QUEUES) { p = v_participant(v_subscriber(v_reader(reader)->subscriber)->participant); if ((v_objectKind(p) == K_NETWORKING) && (v_isEnabledStatistics(kernel, V_STATCAT_NETWORKING))) { nqs = v_networkQueueStatisticsNew(kernel,name); ncs = v_networkChannelStatisticsNew(kernel,name); } else { nqs = NULL; ncs = NULL; } queue = v_networkQueueNew(c_getBase((c_object)reader), queueSize, priority, reliable, P2P, resolution, nqs); if (queue != NULL) { reader->queues[reader->nofQueues] = queue; reader->nofQueues++; result = reader->nofQueues; /* insert statistics */ if (nqs != NULL) { s = v_networkReaderStatistics(v_entityStatistics(v_entity(reader))); if (s != NULL) { s->queues[s->queuesCount]=nqs; s->queuesCount++; } } if ((useAsDefault) || (reader->defaultQueue == NULL)){ c_free(reader->defaultQueue); reader->defaultQueue = c_keep(queue); } if (ncs != NULL) { /* add channel to the networking statistics also */ n = v_networking(p); nws = (v_networkingStatistics)v_entity(n)->statistics; nws->channels[nws->channelsCount]=ncs; nws->channelsCount++; } } } else { OS_REPORT_1(OS_ERROR, "v_networkReaderCreateQueue", 0, "Maximum number of network queues (%d) exceeded, " "new queue not created", NW_MAX_NOF_QUEUES); } return result; }
void cmx_readerSnapshotNewAction( v_entity e, c_voidp args) { v_dataReader reader; c_iter instances; v_dataReaderInstance instance; v_dataReaderSample sample, newer; v_query query; c_bool release; sd_serializer ser; sd_serializedData data; struct cmx_readerSnapshotArg* arg; release = FALSE; arg = (struct cmx_readerSnapshotArg*)args; reader = NULL; instances = NULL; ser = NULL; switch(v_object(e)->kind){ case K_DATAREADER: reader = v_dataReader(e); arg->success = TRUE; arg->snapshot = cmx_readerSnapshot(os_malloc(C_SIZEOF(cmx_readerSnapshot))); v_observerLock(v_observer(reader)); if(reader->index->objects){ instances = c_select(reader->index->notEmptyList, 0); } break; case K_QUERY: case K_DATAREADERQUERY: query = v_query(e); reader = v_dataReader(v_querySource(query)); if(reader != NULL){ release = TRUE; arg->success = TRUE; arg->snapshot = cmx_readerSnapshot(os_malloc(C_SIZEOF(cmx_readerSnapshot))); v_observerLock(v_observer(reader)); switch(v_object(query)->kind){ case K_DATAREADERQUERY: if(v_dataReaderQuery(query)->instanceQ){ instances = c_select((c_collection)(v_dataReaderQuery(query)->instanceQ), 0); } break; default: OS_REPORT_1(OS_ERROR, CM_XML_CONTEXT, 0, "cmx_readerSnapshotNewAction unknown kind (%d).", v_object(query)->kind); break; } } break; default: break; } if(arg->success == TRUE){ arg->snapshot->samples = c_iterNew(NULL); } if(instances != NULL){ instance = v_dataReaderInstance(c_iterTakeFirst(instances)); while(instance != NULL){ sample = c_keep(v_dataReaderInstanceOldest(instance)); if(sample != NULL){ newer = sample->newer; sample->newer = NULL; if(ser == NULL){ ser = sd_serializerXMLNewTyped(c_getType(c_object(sample))); } data = sd_serializerSerialize(ser, c_object(sample)); arg->snapshot->samples = c_iterInsert(arg->snapshot->samples, sd_serializerToString(ser, data)); sd_serializedDataFree(data); sample->newer = newer; c_free(sample); } c_free(instance); instance = v_dataReaderInstance(c_iterTakeFirst(instances)); } c_iterFree(instances); } if(reader != NULL){ v_observerUnlock(v_observer(reader)); if(release == TRUE){ c_free(reader); } } if(ser != NULL){ sd_serializerFree(ser); } }
static v_networkQueue v_networkReaderSelectBestQueueByReliability( v_networkReader reader, v_messageQos qos, c_bool requiresP2P, const char *partitionName, const char *topicName) { unsigned int n; v_networkQueue currentQueue; v_networkQueue bestQueue = NULL; v_networkQueue possiblyBestQueue = NULL; v_networkQueue bestAlternativeQueue = NULL; c_bool reliabilityMatches = FALSE; c_bool P2PMatches = FALSE; c_bool reliable; c_ulong prio,queuePrio; assert(reader != NULL); assert(C_TYPECHECK(reader, v_networkReader)); assert(qos != NULL); assert(partitionName != NULL); assert(topicName != NULL); /* Transform kernel prio to networking prio */ prio = v_messageQos_getTransportPriority(qos); reliable = v_messageQos_isReliable(qos); /* First select the best queue */ if (prio < NW_MAX_QUEUE_CACHE_PRIO) { if (reliable) { bestQueue = reader->queueCache[prio+NW_MAX_QUEUE_CACHE_PRIO]; } else { bestQueue = reader->queueCache[prio]; } } if (!bestQueue) { for (n=0; (n<reader->nofQueues) && (bestQueue == NULL); n++) { currentQueue = reader->queues[n]; /* Check on reliability */ if (reliable) { reliabilityMatches = v_networkQueueReliable(currentQueue); } else { reliabilityMatches = !v_networkQueueReliable(currentQueue); } P2PMatches = (requiresP2P == v_networkQueueP2P(currentQueue)); if (reliabilityMatches && P2PMatches) { queuePrio = v_networkQueuePriority(currentQueue); if (prio == queuePrio) { /* An exact match! Stop here */ bestQueue = currentQueue; } else { if (prio < queuePrio) { /* This queue might be the best fit, it offers higher prio * than requested */ if (possiblyBestQueue != NULL) { if (queuePrio < possiblyBestQueue->priority) { possiblyBestQueue = currentQueue; } } else { possiblyBestQueue = currentQueue; } } if (possiblyBestQueue == NULL) { /* No queue fits until now, but this queue * might be the best alternative if no queue * offers the requested prio at all */ if (bestAlternativeQueue != NULL) { if (queuePrio > bestAlternativeQueue->priority) { bestAlternativeQueue = currentQueue; } } else { bestAlternativeQueue = currentQueue; } } } } } if (bestQueue == NULL) { bestQueue = possiblyBestQueue; } if (bestQueue == NULL) { bestQueue = bestAlternativeQueue; } if (bestQueue == NULL) { OS_REPORT_2(OS_WARNING, "v_networkReaderSelectBestQueue", 0, "Unable to select best fitting queue for partition \"%s\", " "topic \"%s\". Switching to default", partitionName, topicName); bestQueue = reader->defaultQueue; } if (prio < NW_MAX_QUEUE_CACHE_PRIO) { /* Store found bestQueue in the cache, while maintaining * correct reference counts on the Queues */ if (reliable) { c_free(reader->queueCache[prio+NW_MAX_QUEUE_CACHE_PRIO]); reader->queueCache[prio+NW_MAX_QUEUE_CACHE_PRIO] = c_keep(bestQueue); } else { c_free(reader->queueCache[prio]); reader->queueCache[prio] = c_keep(bestQueue); } } } return bestQueue; }
static void _cg_memory_sub_stack_free(cg_memory_sub_stack_t *sub_stack) { c_free(sub_stack->data); c_slice_free(cg_memory_sub_stack_t, sub_stack); }
/* * Check if each usage of a char array as a key has a corresponding * "#pragma cats" declaration. */ static c_bool idl_checkCatsUsage( c_base base, const char* filename) { char errorBuffer [IDL_MAX_ERRORSIZE]; idl_keyDef keyDef = idl_keyDefDefGet(); c_long keyMapIdx; idl_keyMap keyMap; c_type type; c_structure structure; c_iter keysList; os_uint32 keysListSize; os_uint32 keyIdx; c_char* keyName; os_uint32 i; c_iter keyNameList; os_uint32 keyNameListSize; c_structure tmpStructure; c_specifier sp; c_type subType; c_string typeName; c_type spType; if (keyDef != NULL) { /* check all key definition list elements */ for (keyMapIdx = 0; keyMapIdx < c_iterLength(keyDef->keyList); keyMapIdx++) { keyMap = c_iterObject(keyDef->keyList, keyMapIdx); /* if a keylist is defined for the type */ if (keyMap->keyList && strlen(keyMap->keyList) > 0) { /* find meteobject for the type */ type = c_type(c_metaResolveType(keyMap->scope, keyMap->typeName)); if (!type) { snprintf(errorBuffer, IDL_MAX_ERRORSIZE-1, errorText[idl_UndeclaredIdentifier], keyMap->typeName); idl_printError(filename, errorBuffer); return OS_FALSE; } /* type can be a typedef. Determine the actual type. */ type = c_typeActualType(type); /* type should be a structure */ if (c_baseObject(type)->kind != M_STRUCTURE) { snprintf(errorBuffer, IDL_MAX_ERRORSIZE-1, errorText[idl_IllegalKeyFields]); idl_printError(filename, errorBuffer); return OS_FALSE; } structure = c_structure(type); /* for each key in keyList, check if type is a char array */ keysList = c_splitString(keyMap->keyList, ","); keysListSize = c_iterLength(keysList); for(keyIdx = 0; keyIdx < keysListSize; keyIdx++) { keyName = c_iterTakeFirst(keysList); /* We might be dealing with a field of a field definition in * the keylist, so let's split this up */ keyNameList = c_splitString(keyName, "."); keyNameListSize = c_iterLength(keyNameList); tmpStructure = structure; for(i = 0; i < keyNameListSize; i++) { keyName = c_iterTakeFirst(keyNameList); /* Now get the actual member defined by the name */ sp = c_specifier(c_metaFindByName( c_metaObject(tmpStructure), keyName, CQ_FIXEDSCOPE | CQ_MEMBER | CQ_CASEINSENSITIVE)); if(sp) { spType = c_typeActualType(sp->type); /* If the member is a structure, we need to * recurse deeper. */ if(c_baseObject(spType)->kind == M_STRUCTURE) { tmpStructure = c_structure(spType); } /* If the member is a collection then we need to * ensure it is not a character array, but if it * is we need to ensure a corresponding CATS pragma * can be located */ else if(c_baseObject(spType)->kind == M_COLLECTION && c_collectionType(spType)->kind == C_ARRAY) { subType = c_typeActualType(c_collectionType(spType)->subType); if(c_baseObject(subType)->kind == M_PRIMITIVE && c_primitive(subType)->kind == P_CHAR) { typeName = c_metaName(c_metaObject(tmpStructure)); /* check if there is corresponding catsDef */ if (!idl_isCatsDefFor(c_metaObject(tmpStructure)->definedIn, typeName, keyName)) { snprintf( errorBuffer, IDL_MAX_ERRORSIZE-1, errorText[idl_NoCorrespondingCats], c_metaObject(structure)->name, keyName); idl_printError(filename, errorBuffer); return OS_FALSE; } c_free(typeName); } } } } } } } } return OS_TRUE; }
d_topicInfo d_topicInfoNew( d_storeMMFKernel kernel, const v_topic vtopic) { d_topicInfo topic; c_base base, ddsBase; c_type type, srcDataType; c_string name; if(kernel && vtopic){ base = c_getBase(kernel); ddsBase = c_getBase(vtopic); type = c_resolve(base,"durabilityModule2::d_topicInfo"); if(type){ topic = c_new(type); c_free(type); if(topic){ topic->name = c_stringNew(base, v_entity(vtopic)->name); srcDataType = v_topicDataType(vtopic); name = c_metaScopedName(c_metaObject(srcDataType)); topic->typeName = c_stringNew(base, name); assert(topic->typeName); os_free(name); topic->dataType = cloneType(ddsBase, base, srcDataType); assert(topic->dataType); topic->keyExpr = c_stringNew(base, vtopic->keyExpr); assert(topic->keyExpr); topic->messageType = messageTypeNew(base, topic->typeName); assert(topic->messageType); topic->keyType = createTopicKeyType(topic->messageType, topic->keyExpr); assert(topic->keyType); topic->instanceKeyExpr = createInstanceKeyExpr(base, vtopic); topic->sampleType = createSampleType( topic->messageType, topic->name); assert(topic->sampleType); topic->instanceType = createInstanceType( topic->messageType, topic); assert(topic->instanceType); topic->qos = cloneObject(ddsBase, base, vtopic->qos); assert(topic->qos); } } else { OS_REPORT(OS_ERROR, "d_topicInfoNew",0, "Failed to allocate d_topicInfo."); topic = NULL; } } else { OS_REPORT(OS_ERROR, "d_topicInfoNew",0, "Illegal constructor parameter."); topic = NULL; } return topic; }
void xs_infoset_scan(xsMachine* the) { int c = xsToInteger(xsArgc); Scanner scanner; Scanner* self; xsVars(COUNT); xsTry { self = &scanner; c_memset(self, 0, sizeof(Scanner)); if (c < 1) xsSyntaxError("no buffer"); self->expat = XML_ParserCreate(NULL); xsThrowIfNULL(self->expat); XML_SetUserData(self->expat, self); XML_SetElementHandler(self->expat, scanStartTag, scanStopTag); XML_SetCdataSectionHandler(self->expat, scanStartCdata, scanStopCdata); XML_SetCharacterDataHandler(self->expat, scanCharacter); XML_SetCommentHandler(self->expat, scanComment); XML_SetProcessingInstructionHandler(self->expat, scanProcessingInstruction); XML_SetUnknownEncodingHandler(self->expat, scanUnknownEncoding, NULL); XML_SetSkippedEntityHandler(self->expat, scanEntity); self->result = 1; self->textBuffer = c_malloc(8192); xsThrowIfNULL(self->textBuffer); self->textSize = 8192; self->the = the; xsVar(ATTRIBUTE_PROTOTYPE) = xsGet(xsThis, xsID_attribute); xsVar(CDATA_PROTOTYPE) = xsGet(xsThis, xsID_cdata); xsVar(COMMENT_PROTOTYPE) = xsGet(xsThis, xsID_comment); xsVar(DOCUMENT_PROTOTYPE) = xsGet(xsThis, xsID_document); xsVar(ELEMENT_PROTOTYPE) = xsGet(xsThis, xsID_element); xsVar(NO_NAMESPACE) = xsString(""); xsVar(NO_PREFIX) = xsString(""); xsVar(PATH) = (c > 1) ? xsArg(1) : xsUndefined; xsVar(PI_PROTOTYPE) = xsGet(xsThis, xsID_pi); xsVar(XML_NAMESPACE) = xsGet(xsThis, xsID_xmlnsNamespace); xsVar(XML_PREFIX) = xsGet(xsThis, xsID_xmlnsPrefix); xsResult = xsNewInstanceOf(xsVar(DOCUMENT_PROTOTYPE)); xsSet(xsResult, xsID_encoding, xsString("UTF-8")); xsSet(xsResult, xsID_version, xsString("1.0")); xsVar(CHILDREN) = xsNewInstanceOf(xsArrayPrototype); xsArrayCacheBegin(xsVar(CHILDREN)); xsSet(xsResult, xsID_children, xsVar(CHILDREN)); xsSet(xsResult, xsID_parent, xsNull); xsSet(xsResult, xsID_xmlnsAttributes, xsNull); if (xsIsInstanceOf(xsArg(0), xsChunkPrototype)) { xsStringValue buffer = xsGetHostData(xsArg(0)); xsIntegerValue size = xsToInteger(xsGet(xsArg(0), xsID_length)); self->result = XML_Parse(self->expat, (const char *)buffer, size, 1); } else if (xsTypeOf(xsArg(0)) == xsStringType) { xsStringValue string = xsToString(xsArg(0)); xsIntegerValue stringOffset = 0; xsIntegerValue stringSize = c_strlen(string); while (self->result && (stringOffset < stringSize)) { xsIntegerValue size = stringSize - stringOffset; xsStringValue buffer = (char *)XML_GetBuffer(self->expat, 1024); xsThrowIfNULL(buffer); if (size > 1024) size = 1024; c_memcpy(buffer, string + stringOffset, size); self->result = XML_ParseBuffer(self->expat, size, (size < 1024) ? 1 : 0); stringOffset += size; string = xsToString(xsArg(0)); // @@ gc } } else { xsStreamGetter* streamGetter = xsGetHostData(xsArg(0)); while (self->result) { xsIntegerValue i; xsStringValue p, buffer = (char *)XML_GetBuffer(self->expat, 1024); xsThrowIfNULL(buffer); for (i = 0, p = buffer; i < 1024; i++, p++) { int c = (*(streamGetter->getter))(streamGetter->stream); if (c == C_EOF) break; *p = (char)c; } self->result = XML_ParseBuffer(self->expat, i, (i < 1024) ? 1 : 0); if (i < 1024) break; } } xsDelete(xsResult, xsID_xmlnsAttributes); xsDelete(xsResult, xsID_parent); xsArrayCacheEnd(xsVar(CHILDREN)); if (!self->result) { xsVar(LINE) = xsInteger(XML_GetCurrentLineNumber(self->expat)); xsVar(VALUE) = xsString((char*)XML_ErrorString(XML_GetErrorCode(self->expat))); if (xsHas(xsThis, xsID_reportError)) xsCall3_noResult(xsThis, xsID_reportError, xsVar(PATH), xsVar(LINE), xsVar(VALUE)); xsThrow(xsNewInstanceOf(xsSyntaxErrorPrototype)); } c_free(self->textBuffer); self->textBuffer = NULL; XML_ParserFree(self->expat); self->expat = NULL; } xsCatch { if (self->textBuffer) c_free(self->textBuffer); if (self->expat) XML_ParserFree(self->expat); } }
void cmx_readerDataTypeAction( v_entity entity, c_voidp args) { sd_serializer ser; sd_serializedData data; c_type type; v_dataReader r; v_query query; v_topic topic; struct cmx_readerArg *arg; arg = (struct cmx_readerArg *)args; type = NULL; switch(v_object(entity)->kind){ case K_DATAREADER: r = v_dataReader(entity); v_observerLock(v_observer(r)); topic = v_dataReaderGetTopic(r); type = v_topicDataType(topic); c_free(topic); v_observerUnlock(v_observer(r)); break; case K_DATAREADERQUERY: query = v_query(entity); r = v_dataReader(v_querySource(query)); v_observerLock(v_observer(r)); topic = v_dataReaderGetTopic(r); type = v_topicDataType(topic); c_free(topic); v_observerUnlock(v_observer(r)); c_free(r); break; case K_NETWORKREADER: OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0, "Resolving data type of networkReader unsupported.\n"); assert(FALSE); break; case K_GROUPQUEUE: OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0, "Resolving data type of groupQueue unsupported.\n"); assert(FALSE); break; default: OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0, "Trying to resolve dataType of unknown reader type.\n"); assert(FALSE); break; } if(type != NULL){ ser = sd_serializerXMLMetadataNew(c_getBase(type)); data = sd_serializerSerialize(ser, type); arg->result = sd_serializerToString(ser, data); sd_serializedDataFree(data); sd_serializerFree(ser); } }
c_type idl_stacDefConvertStacApprovedMember( c_structure structure, c_type orgMemberType) { c_type dereffedOrgType; c_metaObject o = NULL; c_type newType; os_char buffer[1024]; c_metaObject found; memset(buffer, 0, 1024); dereffedOrgType = c_typeActualType(c_type(idl_stacDefResolveTypeDef(c_baseObject(orgMemberType)))); if(c_baseObject(dereffedOrgType)->kind == M_COLLECTION) { o = c_metaObject(c_metaDefine(c_metaObject(structure), M_COLLECTION)); /* Can be a string or an array or a sequence */ if(c_collectionType(dereffedOrgType)->kind == OSPL_C_STRING) { if((c_collectionType(dereffedOrgType)->maxSize != 0)) { c_collectionType(o)->kind = OSPL_C_ARRAY; c_collectionType(o)->subType = c_type(c_metaResolve(c_metaObject(structure), "c_char")); /* increase maxSize with 1 to accomodate the '\0' char found in strings */ c_collectionType(o)->maxSize = c_collectionType(dereffedOrgType)->maxSize + 1; os_sprintf( buffer, "C_ARRAY<%s,%d>", c_metaObject(c_collectionType(o)->subType)->name, c_collectionType(o)->maxSize/*use maxSize of new c_type, must be the same*/); } else { printf("FATAL ERROR | #pragma stac: Trying to apply stac algorithm to listed members of struct %s, but " "encountered an internal error. The conversion algorithm (idl_stacDefConvertStacApprovedMember) " "has become out of synch with the verification algorithm (idl_stacDefCanStacBeAppliedToMember).\n", c_metaScopedName(c_metaObject(structure))); assert(0); exit(-2); } } else if(c_collectionType(dereffedOrgType)->kind == OSPL_C_ARRAY) { c_collectionType(o)->kind = OSPL_C_ARRAY; /* increase maxSize with 1 to accomodate the '\0' char found in strings */ c_collectionType(o)->maxSize = c_collectionType(dereffedOrgType)->maxSize; c_collectionType(o)->subType = idl_stacDefConvertStacApprovedMember(structure, c_collectionType(dereffedOrgType)->subType); os_sprintf( buffer, "C_ARRAY<%s,%d>", c_metaObject(c_collectionType(o)->subType)->name, c_collectionType(o)->maxSize/*use maxSize of new c_type, must be the same*/); } else if(c_collectionType(dereffedOrgType)->kind == OSPL_C_SEQUENCE) { c_collectionType(o)->kind = OSPL_C_SEQUENCE; /* increase maxSize with 1 to accomodate the '\0' char found in strings */ c_collectionType(o)->maxSize = c_collectionType(dereffedOrgType)->maxSize; c_collectionType(o)->subType = idl_stacDefConvertStacApprovedMember(structure, c_collectionType(dereffedOrgType)->subType); os_sprintf( buffer, "C_SEQUENCE<%s,%d>", c_metaObject(c_collectionType(o)->subType)->name, c_collectionType(o)->maxSize/*use maxSize of new c_type, must be the same*/); } else { printf("FATAL ERROR | #pragma stac: Trying to apply stac algorithm to listed members of struct %s, but " "encountered an internal error. The conversion algorithm (idl_stacDefConvertStacApprovedMember) " "has become out of synch with the verification algorithm (idl_stacDefCanStacBeAppliedToMember).\n", c_metaScopedName(c_metaObject(structure))); assert(0); exit(-2); } } else { printf("FATAL ERROR | #pragma stac: Trying to apply stac algorithm to listed members of struct %s, but " "encountered an internal error. The conversion algorithm (idl_stacDefConvertStacApprovedMember) " "has become out of synch with the verification algorithm (idl_stacDefCanStacBeAppliedToMember).\n", c_metaScopedName(c_metaObject(structure))); assert(0); exit(-2); } if(o) { c_metaObject(o)->definedIn = c_metaObject(structure); c_metaFinalize(o); found = c_metaBind(c_metaObject(structure), &buffer[0], o); c_free(o); newType = c_type(found); } else { printf("FATAL ERROR | #pragma stac: Trying to apply stac algorithm to listed members of struct %s, but " "encountered an internal error. The conversion algorithm (idl_stacDefConvertStacApprovedMember) " "has become out of synch with the verification algorithm (idl_stacDefCanStacBeAppliedToMember).\n", c_metaScopedName(c_metaObject(structure))); assert(0); exit(-2); } return newType; }
// Lua: s = net.create(type, secure/timeout, function(conn)) static int net_create( lua_State* L, const char* mt ) { NODE_DBG("net_create is called.\n"); struct espconn *pesp_conn = NULL; lnet_userdata *nud, *temp = NULL; unsigned type; #ifdef CLIENT_SSL_ENABLE unsigned secure = 0; #endif uint8_t stack = 1; bool isserver = false; if (mt!=NULL && c_strcmp(mt, "net.server")==0) isserver = true; else if (mt!=NULL && c_strcmp(mt, "net.socket")==0) isserver = false; else { NODE_DBG("wrong metatable for net_create.\n"); return 0; } type = luaL_checkinteger( L, stack ); if ( type != ESPCONN_TCP && type != ESPCONN_UDP ) return luaL_error( L, "wrong arg type" ); stack++; #ifdef CLIENT_SSL_ENABLE if(!isserver){ if ( lua_isnumber(L, stack) ) { secure = lua_tointeger(L, stack); stack++; if ( secure != 0 && secure != 1 ){ return luaL_error( L, "wrong arg type" ); } } else { secure = 0; // default to 0 } } #endif if(isserver && type == ESPCONN_TCP){ if ( lua_isnumber(L, stack) ) { unsigned to = lua_tointeger(L, stack); stack++; if ( to < 1 || to > 28800 ){ return luaL_error( L, "wrong arg type" ); } tcp_server_timeover = (uint16_t)to; } else { tcp_server_timeover = 30; // default to 30 } } // create a object nud = (lnet_userdata *)lua_newuserdata(L, sizeof(lnet_userdata)); // pre-initialize it, in case of errors nud->self_ref = LUA_NOREF; nud->cb_connect_ref = LUA_NOREF; nud->cb_reconnect_ref = LUA_NOREF; nud->cb_disconnect_ref = LUA_NOREF; nud->cb_receive_ref = LUA_NOREF; nud->cb_send_ref = LUA_NOREF; nud->cb_dns_found_ref = LUA_NOREF; nud->pesp_conn = NULL; #ifdef CLIENT_SSL_ENABLE nud->secure = secure; #endif // set its metatable luaL_getmetatable(L, mt); lua_setmetatable(L, -2); // create the espconn struct if(isserver && type==ESPCONN_TCP && pTcpServer){ if(tcpserver_cb_connect_ref != LUA_NOREF){ // self_ref should be unref in close() lua_pop(L,1); return luaL_error(L, "only one tcp server allowed"); } pesp_conn = nud->pesp_conn = pTcpServer; } else if(isserver && type==ESPCONN_UDP && pUdpServer){ temp = (lnet_userdata *)pUdpServer->reverse; if(temp && temp->self_ref != LUA_NOREF){ lua_pop(L,1); return luaL_error(L, "only one udp server allowed"); } pesp_conn = nud->pesp_conn = pUdpServer; } else { pesp_conn = nud->pesp_conn = (struct espconn *)c_zalloc(sizeof(struct espconn)); if(!pesp_conn) return luaL_error(L, "not enough memory"); pesp_conn->proto.tcp = NULL; pesp_conn->proto.udp = NULL; pesp_conn->reverse = NULL; if( type==ESPCONN_TCP ) { pesp_conn->proto.tcp = (esp_tcp *)c_zalloc(sizeof(esp_tcp)); if(!pesp_conn->proto.tcp){ c_free(pesp_conn); pesp_conn = nud->pesp_conn = NULL; return luaL_error(L, "not enough memory"); } NODE_DBG("TCP server/socket is set.\n"); } else if( type==ESPCONN_UDP ) { pesp_conn->proto.udp = (esp_udp *)c_zalloc(sizeof(esp_udp)); if(!pesp_conn->proto.udp){ c_free(pesp_conn); pesp_conn = nud->pesp_conn = NULL; return luaL_error(L, "not enough memory"); } NODE_DBG("UDP server/socket is set.\n"); } } pesp_conn->type = type; pesp_conn->state = ESPCONN_NONE; // reverse is for the callback function pesp_conn->reverse = nud; if(isserver && type==ESPCONN_TCP && pTcpServer==NULL){ pTcpServer = pesp_conn; } else if(isserver && type==ESPCONN_UDP && pUdpServer==NULL){ pUdpServer = pesp_conn; } gL = L; // global L for net module. // if call back function is specified, call it with para userdata // luaL_checkanyfunction(L, 2); if (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION){ lua_pushvalue(L, stack); // copy argument (func) to the top of stack lua_pushvalue(L, -2); // copy the self_ref(userdata) to the top lua_call(L, 1, 0); } return 1; }
txMachine* fxCreateMachine(txCreation* theCreation, void* theArchive, txString theName, void* theContext) { txMachine* the = (txMachine* )c_calloc(sizeof(txMachine), 1); if (the) { txJump aJump; aJump.nextJump = C_NULL; aJump.stack = C_NULL; aJump.scope = C_NULL; aJump.frame = C_NULL; aJump.code = C_NULL; aJump.flag = 0; the->firstJump = &aJump; if (c_setjmp(aJump.buffer) == 0) { txInteger anIndex; #if __FSK_LAYER__ FskInstrumentedItemNew(the, NULL, &gXSTypeInstrumentation); #endif #ifdef mxDebug the->echoSize = 1 * 1024; the->echoBuffer = (txString)c_malloc(the->echoSize); if (!the->echoBuffer) fxJump(the); //fxConnect(the); the->connection = mxNoSocket; the->name = theName; the->sorter = (txSlot**)c_malloc(theCreation->keyCount * sizeof(txSlot*)); if (!the->sorter) fxJump(the); the->breakOnExceptionFlag = 1; #endif #ifdef mxProfile the->profileID = 1; the->profileBottom = c_malloc(XS_PROFILE_COUNT * sizeof(txProfileRecord)); if (!the->profileBottom) fxJump(the); the->profileCurrent = the->profileBottom; the->profileTop = the->profileBottom + XS_PROFILE_COUNT; #endif the->archive = theArchive; the->dtoa = fxNew_dtoa(); if (!the->dtoa) fxJump(the); fxAllocate(the, theCreation); /* mxGLobal */ mxPushUndefined(); /* mxException */ mxPushUndefined(); for (anIndex = mxObjectPrototypeStackIndex; anIndex < mxModulePathsStackIndex; anIndex++) mxPushUndefined(); /* mxModulePaths */ mxPushUndefined(); /* mxImportingModules */ fxNewInstance(the); /* mxLoadingModules */ fxNewInstance(the); /* mxLoadedModules */ fxNewInstance(the); /* mxResolvingModules */ fxNewInstance(the); /* mxRunningModules */ fxNewInstance(the); /* mxRequiredModules */ fxNewInstance(the); /* mxModules */ mxPushUndefined(); /* mxPendingJobs */ fxNewInstance(the); /* mxRunningJobs */ fxNewInstance(the); /* mxFiles */ mxPushList(); /* mxBreakpoints */ mxPushList(); /* mxHosts */ mxPushUndefined(); /* mxIDs */ mxPushUndefined(); /* mxEmptyCode */ mxPushUndefined(); the->stack->value.code = (txByte *)fxNewChunk(the, sizeof(gxNoCode)); c_memcpy(the->stack->value.code, gxNoCode, sizeof(gxNoCode)); the->stack->kind = XS_CODE_KIND; /* mxEmptyString */ mxPushStringC(""); /* mxBooleanString */ mxPushStringC("boolean"); /* mxDefaultString */ mxPushStringC("default"); /* mxFunctionString */ mxPushStringC("function"); /* mxNumberString */ mxPushStringC("number"); /* mxObjectString */ mxPushStringC("object"); /* mxStringString */ mxPushStringC("string"); /* mxSymbolString */ mxPushStringC("symbol"); /* mxUndefinedString */ mxPushStringC("undefined"); for (anIndex = mxGetArgumentFunctionStackIndex; anIndex < mxStackIndexCount; anIndex++) mxPushUndefined(); fxBuildKeys(the); fxBuildGlobal(the); fxBuildObject(the); fxBuildFunction(the); fxBuildGenerator(the); fxBuildArray(the); fxBuildString(the); fxBuildBoolean(the); fxBuildNumber(the); fxBuildDate(the); fxBuildMath(the); fxBuildRegExp(the); fxBuildError(the); fxBuildJSON(the); fxBuildDataView(the); fxBuildPromise(the); fxBuildSymbol(the); fxBuildProxy(the); fxBuildMapSet(the); fxBuildModule(the); fxBuildHost(the); mxPush(mxSetPrototype); fxNewSetInstance(the); mxPull(mxModulePaths); mxPush(mxObjectPrototype); fxNewWeakSetInstance(the); mxPull(mxModules); the->collectFlag = XS_COLLECTING_FLAG; /*{ int c = 32; while (--c) fxCollectGarbage(the); }*/ the->context = theContext; #ifdef mxDebug if (fxGetAutomatic(the)) fxLogin(the); #endif the->firstJump = C_NULL; } else { #if __FSK_LAYER__ FskInstrumentedItemDispose(the); #endif fxFree(the); c_free(the); the = NULL; } } return the; }
static void _cg_winsys_device_deinit(cg_device_t *dev) { c_free(dev->winsys); }
void fxDeleteMachine(txMachine* the) { txSlot* aSlot; txSlot* bSlot; txSlot* cSlot; if (!(the->shared)) { #ifdef mxProfile fxStopProfiling(the); #endif #ifdef mxFrequency fxReportFrequency(the); #endif #ifdef mxDebug fxLogout(the); //fxWriteBreakpoints(the); #endif } the->context = C_NULL; aSlot = the->cRoot; while (aSlot) { aSlot->flag |= XS_MARK_FLAG; aSlot = aSlot->next; } aSlot = the->firstHeap; while (aSlot) { bSlot = aSlot + 1; cSlot = aSlot->value.reference; while (bSlot < cSlot) { if ((bSlot->kind == XS_HOST_KIND) && (bSlot->value.host.variant.destructor)) { if (bSlot->flag & XS_HOST_HOOKS_FLAG) { if (bSlot->value.host.variant.hooks->destructor) (*(bSlot->value.host.variant.hooks->destructor))(bSlot->value.host.data); } else (*(bSlot->value.host.variant.destructor))(bSlot->value.host.data); } bSlot++; } aSlot = aSlot->next; } fxDelete_dtoa(the->dtoa); if (!(the->shared)) { #ifdef mxProfile if (the->profileBottom) { c_free(the->profileBottom); the->profileBottom = C_NULL; the->profileCurrent = C_NULL; the->profileTop = C_NULL; } if (the->profileDirectory) { c_free(the->profileDirectory); } #endif #ifdef mxDebug //fxDisconnect(the); if (the->sorter) { c_free(the->sorter); the->sorter = C_NULL; } if (the->echoBuffer) { c_free(the->echoBuffer); the->echoBuffer = C_NULL; } #endif } #if __FSK_LAYER__ FskInstrumentedItemDispose(the); #endif fxFree(the); c_free(the); }
c_char* cmx_dataReaderNew( const c_char* subscriber, const c_char* name, const c_char* view, const c_char* qos) { u_subscriber sub; u_dataReader rea; c_char* result; cmx_entityArg arg; u_result ur; cmx_entityKernelArg kernelArg; v_readerQos rqos; q_expr qexpr; result = NULL; sub = u_subscriber(cmx_entityUserEntity(subscriber)); if(sub != NULL){ kernelArg = cmx_entityKernelArg(os_malloc(C_SIZEOF(cmx_entityKernelArg))); u_entityAction(u_entity(sub), cmx_entityKernelAction, (c_voidp)kernelArg); if(qos != NULL){ rqos = v_readerQos(cmx_qosKernelQosFromKind(qos, K_DATAREADER, c_getBase(c_object(kernelArg->kernel)))); if(rqos == NULL){ rqos = v_readerQosNew(kernelArg->kernel, NULL); } } else { rqos = v_readerQosNew(kernelArg->kernel, NULL); } if(view != NULL){ qexpr = q_parse(view); if(qexpr != NULL){ rea = u_dataReaderNew(sub, name, qexpr, NULL, rqos, TRUE); q_dispose(qexpr); } else { rea = NULL; OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0, "cmx_dataReaderNew: invalid view expression."); } } else { rea = u_dataReaderNew(sub, name, NULL, NULL, rqos, TRUE); } c_free(rqos); os_free(kernelArg); if(rea != NULL){ cmx_registerEntity(u_entity(rea)); arg = cmx_entityArg(os_malloc((os_uint32)(C_SIZEOF(cmx_entityArg)))); arg->entity = u_entity(rea); arg->create = FALSE; arg->participant = NULL; arg->result = NULL; ur = u_entityAction(u_entity(rea), cmx_entityNewFromAction, (c_voidp)(arg)); if(ur == U_RESULT_OK){ result = arg->result; os_free(arg); } } } return result; }
void q_print( q_expr e, c_long i) { char llstr[36]; q_list l; c_long n,p; c_string name; c_string metaName; if (e == NULL) return; switch(e->kind) { case T_VAR: case T_INT: llstr[35] = '\0'; printf("%s",os_lltostr(e->info.integer, &llstr[35])); break; case T_DBL: printf("%f",e->info.real); break; case T_CHR: printf("\'%c\'",e->info.character); break; case T_STR: printf("%s",e->info.string); break; case T_ID: printf("%s",e->info.string); break; case T_FNC: if (e->info.function->tag == Q_EXPR_CALLBACK) { name = (c_char *)q_tagImage(e->info.function->tag); metaName = c_metaName(c_metaObject(q_getTyp(q_getPar(e,0)))); if (metaName != NULL) { printf("%s(<%s>,0x" PA_ADDRFMT,name,metaName,(c_address)q_getPar(e,1)); c_free(metaName); } else { printf("%s(<anonomous type>,0x" PA_ADDRFMT,name,(c_address)q_getPar(e,1)); } p = i+strlen(name)+1; printf(",\n"); for (n=0;n<p;n++) printf(" "); q_print(q_getPar(e,2),p); printf(")"); } else { name = (c_char *)q_tagImage(e->info.function->tag); printf("%s(",name); p = i+strlen(name)+1; l = e->info.function->params; if (l != NULL) { q_print(l->expr,p); l = l->next; } while (l != NULL) { printf(",\n"); for (n=0;n<p;n++) printf(" "); q_print(l->expr,p); l = l->next; } printf(")"); } break; case T_TYP: name = c_metaName(c_metaObject(e->info.type)); if (name == NULL) { printf("<unnamed type>"); } else { printf("%s",name); } c_free(name); break; case T_ERR: break; } }