hw_reg_t *init(hw_config_t *config, hw_callbacks_t *callbacks) { hw_reg_t *uart_reg; uint16_t start; uint16_t end; uart_state_t *state; int ret; hardware_callbacks = callbacks; uart_reg = malloc(sizeof(hw_reg_t) + sizeof(mem_remap_t)); if(!uart_reg) { perror("malloc"); exit(1); } memset(uart_reg, 0, sizeof(uart_reg)); if(!config_get_uint16(config, "mem_start", &start)) return NULL; end = start + 3; uart_reg->hw_family = HW_FAMILY_SERIAL; uart_reg->memop = uart_memop; uart_reg->remapped_regions = 1; uart_reg->remap[0].mem_start = start; uart_reg->remap[0].mem_end = end; uart_reg->remap[0].readable = 1; uart_reg->remap[0].writable = 1; state = malloc(sizeof(uart_state_t)); if(!state) { perror("malloc"); exit(1); } /* init the state */ uart_reg->state = state; state->CTL = 0; state->CMD = 0x02; /* rx irq disabled */ state->SR = 0x10; /* tdr empty */ /* set up the pty */ state->pty = posix_openpt(O_RDWR); if(state->pty < 0) { perror("posix_openpt"); return NULL; } ret = grantpt(state->pty); if(ret) { perror("grantpt"); DEBUG("grantpt: %d", ret); return NULL; } ret = unlockpt(state->pty); if(ret) { perror("unlockpt"); return NULL; } INFO("Opened pty for 6551 uart at %s", ptsname(state->pty)); NOTIFY("Opened pty for 6551 uart at %s", ptsname(state->pty)); /* now, start up an async listener thread */ if(pthread_mutex_init(&state->state_lock, NULL) < 0) { perror("pthread_mutex_init"); return NULL; } if(pthread_create(&state->listener_tid, NULL, listener_proc, state) < 0) { perror("pthread_create"); return NULL; } return uart_reg; }
int main(int argc, char **argv) { PtpClock *ptpClock; Integer16 ret; TimingService *ts; startupInProgress = TRUE; memset(&timingDomain, 0, sizeof(timingDomain)); timingDomainSetup(&timingDomain); timingDomain.electionLeft = 10; /* Initialize run time options with command line arguments */ if (!(ptpClock = ptpdStartup(argc, argv, &ret, &rtOpts))) { if (ret != 0 && !rtOpts.checkConfigOnly) ERROR(USER_DESCRIPTION" startup failed\n"); return ret; } timingDomain.electionDelay = rtOpts.electionDelay; /* configure PTP TimeService */ timingDomain.services[0] = &ptpClock->timingService; ts = timingDomain.services[0]; strncpy(ts->id, "PTP0", TIMINGSERVICE_MAX_DESC); ts->dataSet.priority1 = rtOpts.preferNTP; ts->dataSet.type = TIMINGSERVICE_PTP; ts->config = &rtOpts; ts->controller = ptpClock; ts->timeout = rtOpts.idleTimeout; ts->updateInterval = 1; ts->holdTime = rtOpts.ntpOptions.failoverTimeout; timingDomain.serviceCount = 1; if (rtOpts.ntpOptions.enableEngine) { ntpSetup(&rtOpts, ptpClock); } else { timingDomain.serviceCount = 1; timingDomain.services[1] = NULL; } timingDomain.init(&timingDomain); timingDomain.updateInterval = 1; startupInProgress = FALSE; /* global variable for message(), please see comment on top of this file */ G_ptpClock = ptpClock; /* do the protocol engine */ protocol(&rtOpts, ptpClock); /* forever loop.. */ /* this also calls ptpd shutdown */ timingDomain.shutdown(&timingDomain); NOTIFY("Self shutdown\n"); return 1; }
/** * Reads filename into memory and populates * the config_t struct with the result. Uses * parse to ignore comments and empty lines. */ int read_cfg_file(LINES *l, char *filename) { /* file pointer */ FILE *file; HASH H; char *line; char *option; char *value; /* char array to hold contents */ /* make sure LINES has been initialized. */ if(!l){ printf("Structure not initialized!\n"); return -1; } if((file = fopen(filename, "r")) == NULL) { /* this is a fatal problem, but we want to enlighten the user before dying */ NOTIFY(WARNING, "unable to open file: %s", filename); display_help(); exit(EXIT_FAILURE); } line = xmalloc(BUFSIZE); memset(line, 0, BUFSIZE); H = new_hash(); l->index = 0; while (fgets(line, BUFSIZE, file) != NULL) { int num; char *p = strchr(line, '\n'); /** * if the line is longer than our buffer, we're * just going to chuck it rather then fsck with it. */ if(p) { *p = '\0'; } else { /** * Small fix by Gargoyle - 19/07/2006 * Check to see if we are at the end of the file. If so * keep the line, otherwise throw it away! */ if((num = fgetc(file)) != EOF) { while((num = fgetc(file)) != EOF && num != '\n'); line[0]='\0'; } } parse(line); chomp(line); if(strlen(line) == 0); else if(is_variable_line(line)){ char *tmp = line; option = tmp; while(*tmp && !ISSPACE((int)*tmp) && !ISSEPARATOR(*tmp)) tmp++; *tmp++=0; while(ISSPACE((int)*tmp) || ISSEPARATOR(*tmp)) tmp++; value = tmp; while(*tmp) tmp++; *tmp++=0; hash_add(H, option, value); } else { char *tmp = xstrdup(line); while(strstr(tmp, "$")){ tmp = evaluate(H, tmp); } l->line = (char**)realloc(l->line, sizeof(char *) * (l->index + 1)); l->line[l->index] = (char *)strdup(tmp); l->index++; free(tmp); } memset(line, 0, BUFSIZE); } fclose(file); xfree(line); hash_destroy(H); return l->index; }
static void handleTextFieldActionEvents(XEvent * event, void *data) { TextField *tPtr = (TextField *) data; static Time lastButtonReleasedEvent = 0; static Time lastButtonReleasedEvent2 = 0; Display *dpy = event->xany.display; CHECK_CLASS(data, WC_TextField); switch (event->type) { case KeyPress: if (tPtr->flags.waitingSelection) { return; } if (tPtr->flags.enabled && tPtr->flags.focused) { handleTextFieldKeyPress(tPtr, event); XDefineCursor(dpy, W_VIEW(tPtr)->window, W_VIEW(tPtr)->screen->invisibleCursor); tPtr->flags.pointerGrabbed = 1; } break; case MotionNotify: if (tPtr->flags.pointerGrabbed) { tPtr->flags.pointerGrabbed = 0; XDefineCursor(dpy, W_VIEW(tPtr)->window, W_VIEW(tPtr)->screen->textCursor); } if (tPtr->flags.waitingSelection) { return; } if (tPtr->flags.enabled && (event->xmotion.state & Button1Mask)) { if (tPtr->viewPosition < tPtr->textLen && event->xmotion.x > tPtr->usableWidth) { if (WMWidthOfString(tPtr->font, &(tPtr->text[tPtr->viewPosition]), tPtr->cursorPosition - tPtr->viewPosition) > tPtr->usableWidth) { tPtr->viewPosition += oneUTF8CharForward(&tPtr->text[tPtr->viewPosition], tPtr->textLen - tPtr->viewPosition); } } else if (tPtr->viewPosition > 0 && event->xmotion.x < 0) { paintCursor(tPtr); tPtr->viewPosition += oneUTF8CharBackward(&tPtr->text[tPtr->viewPosition], tPtr->viewPosition); } tPtr->cursorPosition = pointToCursorPosition(tPtr, event->xmotion.x); /* Do not allow text selection in secure textfields */ if (tPtr->flags.secure) { tPtr->selection.position = tPtr->cursorPosition; } tPtr->selection.count = tPtr->cursorPosition - tPtr->selection.position; paintCursor(tPtr); paintTextField(tPtr); } break; case ButtonPress: if (tPtr->flags.pointerGrabbed) { tPtr->flags.pointerGrabbed = 0; XDefineCursor(dpy, W_VIEW(tPtr)->window, W_VIEW(tPtr)->screen->textCursor); break; } if (tPtr->flags.waitingSelection) { break; } switch (tPtr->flags.alignment) { int textWidth; case WARight: textWidth = WMWidthOfString(tPtr->font, tPtr->text, tPtr->textLen); if (tPtr->flags.enabled && !tPtr->flags.focused) { WMSetFocusToWidget(tPtr); } if (tPtr->flags.focused) { tPtr->selection.position = tPtr->cursorPosition; tPtr->selection.count = 0; } if (textWidth < tPtr->usableWidth) { tPtr->cursorPosition = pointToCursorPosition(tPtr, event->xbutton.x - tPtr->usableWidth + textWidth); } else tPtr->cursorPosition = pointToCursorPosition(tPtr, event->xbutton.x); paintTextField(tPtr); break; case WALeft: if (tPtr->flags.enabled && !tPtr->flags.focused) { WMSetFocusToWidget(tPtr); } if (tPtr->flags.focused && event->xbutton.button == Button1) { tPtr->cursorPosition = pointToCursorPosition(tPtr, event->xbutton.x); tPtr->selection.position = tPtr->cursorPosition; tPtr->selection.count = 0; paintTextField(tPtr); } if (event->xbutton.button == Button2 && tPtr->flags.enabled) { char *text; int n; if (!WMRequestSelection(tPtr->view, XA_PRIMARY, XA_STRING, event->xbutton.time, pasteText, NULL)) { text = XFetchBuffer(tPtr->view->screen->display, &n, 0); if (text) { text[n] = 0; WMInsertTextFieldText(tPtr, text, tPtr->cursorPosition); XFree(text); NOTIFY(tPtr, didChange, WMTextDidChangeNotification, (void *)WMInsertTextEvent); } } else { tPtr->flags.waitingSelection = 1; } } break; default: break; } break; case ButtonRelease: if (tPtr->flags.pointerGrabbed) { tPtr->flags.pointerGrabbed = 0; XDefineCursor(dpy, W_VIEW(tPtr)->window, W_VIEW(tPtr)->screen->textCursor); } if (tPtr->flags.waitingSelection) { break; } if (!tPtr->flags.secure && tPtr->selection.count != 0) { int start, count; XRotateBuffers(dpy, 1); count = abs(tPtr->selection.count); if (tPtr->selection.count < 0) start = tPtr->selection.position - count; else start = tPtr->selection.position; XStoreBuffer(dpy, &tPtr->text[start], count, 0); } if (!tPtr->flags.secure && event->xbutton.time - lastButtonReleasedEvent <= WINGsConfiguration.doubleClickDelay) { if (event->xbutton.time - lastButtonReleasedEvent2 <= 2 * WINGsConfiguration.doubleClickDelay) { tPtr->selection.position = 0; tPtr->selection.count = tPtr->textLen; } else { int pos, cnt; char *txt; pos = tPtr->selection.position; cnt = tPtr->selection.count; txt = tPtr->text; while (pos >= 0) { if (txt[pos] == ' ' || txt[pos] == '\t') break; pos--; } pos++; while (pos + cnt < tPtr->textLen) { if (txt[pos + cnt] == ' ' || txt[pos + cnt] == '\t') break; cnt++; } tPtr->selection.position = pos; tPtr->selection.count = cnt; } paintTextField(tPtr); if (!tPtr->flags.ownsSelection) { tPtr->flags.ownsSelection = WMCreateSelectionHandler(tPtr->view, XA_PRIMARY, event->xbutton.time, &selectionHandler, NULL); } } else if (!tPtr->flags.secure && tPtr->selection.count != 0 && !tPtr->flags.ownsSelection) { tPtr->flags.ownsSelection = WMCreateSelectionHandler(tPtr->view, XA_PRIMARY, event->xbutton.time, &selectionHandler, NULL); } lastButtonReleasedEvent2 = lastButtonReleasedEvent; lastButtonReleasedEvent = event->xbutton.time; break; } }
int main(int argc, char *argv[]) { static const char file_contents[] = "abcdefg"; static char readbuff[sizeof(file_contents)]; if (argc < 2) { fprintf(stderr, "Usage: %s filename\n", argv[0]); exit(EXIT_FAILURE); } int fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, FILEMODE); if (fd < 0) { fprintf(stderr, "Couldn't open %s: %s\n", argv[1], strerror(errno)); exit(EXIT_FAILURE); } /* Activate mandatory locking on the file */ struct stat statbuf; if (fstat(fd, &statbuf) < 0) { fprintf(stderr, "stat(2) failed for file %s: %s\n", argv[1], strerror(errno)); exit(EXIT_FAILURE); } if (fchmod(fd, (statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0) { perror("Couldn't enable mandatory locking"); exit(EXIT_FAILURE); } if (write(fd, file_contents, sizeof(file_contents)-1) < 0) { perror("write(2) error"); exit(EXIT_FAILURE); } NOTIFY_INIT(); pid_t f; if ((f = fork()) < 0) { perror("fork(2) failed"); exit(EXIT_FAILURE); } if (f == 0) { /* Parent goes first */ WAIT_NOTIFY(); /* We need to change to nonblocking I/O to prevent read(2) from blocking waiting for * the lock to be released */ if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { perror("fcntl(2) failed"); exit(EXIT_FAILURE); } /* Let's see what error we get when we attempt to read-lock a file that is already * write-locked */ struct flock lock; lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; if (fcntl(fd, F_SETLK, &lock) < 0) { printf("Read lock denied, error = %d (%s)\n", errno, strerror(errno)); } else { fprintf(stderr, "Oops! Read lock acquired when parent process has write lock.. ?!\n"); exit(EXIT_FAILURE); } /* Now let's try to read without holding a lock */ if (lseek(fd, 0, SEEK_SET) < 0) { perror("lseek(2) failed"); exit(EXIT_FAILURE); } ssize_t r; if ((r = read(fd, readbuff, sizeof(readbuff)-1)) < 0) { printf("read(2) returned with error %d (%s); mandatory locking seems to work.\n", errno, strerror(errno)); } else { readbuff[r] = '\0'; printf("read(2) returned success: %s; mandatory locking doesn't work.\n", readbuff); } } else { /* Acquire write lock for the entire file */ struct flock lock; lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; if (fcntl(fd, F_SETLK, &lock) < 0) { perror("fcntl(2) failed"); NOTIFY(f); exit(EXIT_FAILURE); } NOTIFY(f); wait(NULL); } return 0; }
void write_to_log(int count, float elapsed, int bytes, float ttime, int code, int failed) { int fd; char entry[512]; #ifdef HAVE_LOCALTIME_R struct tm keepsake; #endif/*HAVE_LOCALTIME_R*/ struct tm *tmp; time_t now; size_t len = 0; char date[65]; now = time(NULL); #ifdef HAVE_LOCALTIME_R tmp = (struct tm *)localtime_r(&now, &keepsake); #else tmp = localtime(&now); #endif/*HAVE_LOCALTIME_R*/ setlocale(LC_TIME, "C"); len = strftime(date, sizeof date, "%Y-%m-%d %H:%M:%S", tmp); /* if the file does NOT exist then we'll create it. */ if (my.shlog) { printf("LOG FILE: %s\n", my.logfile ); printf("You can disable this log file notification by editing\n"); printf("%s/.siege/siege.conf ", getenv("HOME")); puts("and changing \'show-logfile\' to false." ); } if (!file_exists(my.logfile)) { if (!create_logfile(my.logfile)) { NOTIFY(ERROR, "unable to create log file: %s", my.logfile); return; } } /* create the log file entry with function params. */ snprintf( entry, sizeof entry, "%s,%7d,%11.2f,%12u,%11.2f,%12.2f,%12.2f,%12.2f,%8d,%8d\n", date, count, elapsed, bytes, ttime / count, count / elapsed, bytes / elapsed, ttime / elapsed, code, failed ); /* open the log and write to file */ if ((fd = open(my.logfile, O_WRONLY | O_APPEND, 0644)) < 0) { NOTIFY(ERROR, "Unable to open file: %s", my.logfile); return; } len = write(fd, entry, strlen(entry)); if (len == (unsigned int)-1) { switch (errno) { case EBADF: NOTIFY(ERROR, "Unable to write to log file (bad file descriptor): %s", my.logfile); break; case EINTR: NOTIFY(ERROR, "Unable to write to log file (system interrupt): %s", my.logfile); break; default: NOTIFY(ERROR, "Unable to write to log file (unknown error): %s", my.logfile); break; } } close(fd); return; }
MiniMacsRep * minimacs_fake_setup( OE oe, MiniMacsEnc encoder, uint ltext, uint nplayers, uint codelength, MiniMacsTripleRep *** triples, uint ltriples, MiniMacsRep *** singles, uint lsingles, MiniMacsRep **** pairs, uint lpairs, SetupListener listener) { uint ssingles=0, spairs=0, striples=0; uint i = 0, j = 0; uint count=0,player=0; byte * txt = (byte*)malloc(2*ltext); MiniMacsRep * current = 0; MiniMacsRep * currentB = 0; MiniMacsRep * compat = 0; if (!singles) { FAILURE("Singles was null",""); } if (!pairs) { FAILURE("Pairs was null",""); } if (!triples) { FAILURE("Triples was null",""); } if (!txt) { FAILURE("Out of memory",""); } // DBG_P("Generating Reedsolomon polynomial"); NOTIFY(SINGLES,0,lsingles); // Create singles ssingles = nplayers * sizeof(**singles); *singles = (MiniMacsRep**)malloc(ssingles); if (!*singles) { FAILURE("Failed to allocate singles",""); } memset(*singles,0,ssingles); for(player=0;player<nplayers;++player) { (*singles)[player] = (MiniMacsRep*)malloc(lsingles*sizeof(MiniMacsRep)); if (! (*singles)[player] ) { FAILURE("Failed to allocate singles, out of memory",""); } memset( (*singles)[player],0,lsingles*sizeof(MiniMacsRep)); } for(count = 0; count < lsingles;++count) { memset(txt,0,ltext); rand_bytes(txt,ltext); current = minimacs_create_rep_from_plaintext_f(encoder, txt,ltext, nplayers,codelength, compat); if (!current) { FAILURE("Failed to create random representation",""); } for(player = 0;player<nplayers;++player) { (*singles)[player][count] = current[player]; } if (!compat) { compat = current; } else { if (current) { (free(current),current=0); } } NOTIFY(SINGLES,count,lsingles); } NOTIFY(PAIRS, count, lpairs ); // ******************** // Pairs // ******************** spairs = nplayers * sizeof(**pairs); *pairs = (MiniMacsRep***)malloc(spairs); if (!*pairs) { FAILURE("Failed to create singles star pairs, out of memory",""); } memset(*pairs,0,spairs); for(player=0;player<nplayers;++player) { (*pairs)[player] = (MiniMacsRep**)malloc(lpairs*sizeof( MiniMacsRep * ) ); if (!(*pairs)[player]) { FAILURE("Failed to create list of pairs, out of memory",""); } memset ( (*pairs)[player],0,lpairs*sizeof (MiniMacsRep*)); } for(count = 0;count<lpairs;++count) { memset(txt,0,2*ltext); rand_bytes(txt,2*ltext); // allocate for(player = 0; player < nplayers; ++player) { (*pairs)[player][count] = (MiniMacsRep*)malloc(2*sizeof(MiniMacsRep)); if (! (*pairs)[player][count] ) { FAILURE("Failed to allocate pair, out of memory",""); } memset((*pairs)[player][count],0,2*sizeof(MiniMacsRep)); } // first current = minimacs_create_rep_from_plaintext_f(encoder,txt,ltext, nplayers,codelength,compat); if (!current) { FAILURE("Failed to create single in pair %d",i); } for(player = 0; player < nplayers; ++player) { (*pairs)[player][count][0] = current[player]; } if (current) { free(current); current=0; } // second current = minimacs_create_rep_from_plaintext_f(encoder,txt,2*ltext, nplayers,codelength,compat); if (!current) { FAILURE("Failed to create star in pair %d",i); } for(player = 0; player < nplayers; ++player) { (*pairs)[player][count][1] = current[player]; } if (current) { free(current); current=0; } NOTIFY(PAIRS,count,lpairs); } NOTIFY(TRIPLES, count, ltriples); // Triples striples = nplayers * sizeof(**triples); *triples = (MiniMacsTripleRep**)malloc(striples); if (!*triples) { FAILURE("Out of memory",""); } memset(*triples,0,sizeof(**triples)); for(player=0; player < nplayers;++player) { (*triples)[player] = (MiniMacsTripleRep*) malloc( ltriples * sizeof(MiniMacsTripleRep)); if (!(*triples)[player]) { FAILURE("Out of memory",""); } memset((*triples)[player],0,ltriples*sizeof(MiniMacsTripleRep)); } for(count = 0; count < ltriples; ++ count ) { MiniMacsRep * tmp = 0; for(player=0;player<nplayers;++player) { (*triples)[player][count] = (MiniMacsTripleRep)malloc(sizeof(*(*triples)[player][count])); if (!(*triples)[player][count]) { FAILURE("Out of memory",""); } memset((*triples)[player][count],0,sizeof(*(*triples)[player][count])); } // create a memset(txt,0,2*ltext); rand_bytes(txt,ltext); current = minimacs_create_rep_from_plaintext_f(encoder,txt,ltext,nplayers,codelength,compat); if (!current) { FAILURE("Count not create rep",""); } for(player=0;player<nplayers;++player) { (*triples)[player][count]->a = current[player]; } // create b memset(txt,0,2*ltext); rand_bytes(txt,ltext); currentB = minimacs_create_rep_from_plaintext_f(encoder,txt,ltext,nplayers,codelength,compat); if (!currentB) { FAILURE("Count not create rep",""); } for(player=0;player<nplayers;++player) { (*triples)[player][count]->b = currentB[player]; } // create c=ab tmp = current; current = minimacs_rep_mul_fast(encoder, current, currentB, nplayers); if (!current) { FAILURE("Representation multiplication failed",""); } (free(tmp),tmp=0); (free(currentB),currentB=0); for(player=0; player < nplayers; ++player) { (*triples)[player][count]->cstar = current[player]; } (free(current),current=0); NOTIFY(TRIPLES,count+1,ltriples); } if(txt) { free(txt); txt=0; } if (current) { free(current); current=0; } return compat; failure: MiniMacsEnc_MatrixDestroy( &encoder ); if (current) { for(player=0;player<nplayers;++player) { minimacs_rep_clean_up(& (current[player] ) ); } (free(current),current=0); } if (currentB) { for(player=0;player<nplayers;++player) { minimacs_rep_clean_up(& (currentB[player] ) ); } (free(currentB),currentB=0); } if (txt) { free(txt); txt=0; } if (*singles) { for(player=0; player < nplayers; ++player) { for(count = 0; count < lsingles; ++count ) { minimacs_rep_clean_up( & (*singles)[player][count] ); } free( (*singles)[player] ); (*singles)[player] = 0; } free( (*singles) ); (*singles) = 0; } if (*pairs) { for(player = 0; player < nplayers;++player) { if ( (*pairs)[player] ) { for(count = 0; count < lpairs;++pairs) { if ( (*pairs)[player][count] ) { // first if ( (*pairs)[player][count][0] ) { minimacs_rep_clean_up( & (*pairs)[player][count][0] ); } // second if ( (*pairs)[player][count][1] ) { minimacs_rep_clean_up( & (*pairs)[player][count][1] ); } // pair free((*pairs)[player][count]),(*pairs)[player][count]=0; } } // list free( (*pairs)[player] ); (*pairs)[player] = 0; } } (free((*pairs)),(*pairs)=0); } if (*triples) { for(player = 0; player < nplayers; ++player) { if ( (*pairs)[player] ) { for(count = 0; count < ltriples; ++count ) { if ((*pairs)[player][count] ) { // a if ((*triples)[player][count]->a) { minimacs_rep_clean_up( & (*triples)[player][count]->a ); } // b if ((*triples)[player][count]->b) { minimacs_rep_clean_up( & (*triples)[player][count]->b ); } // c if ((*triples)[player][count]->cstar) { minimacs_rep_clean_up( & (*triples)[player][count]->cstar ); } free((*triples)[player][count]); (*triples)[player][count] = 0; } } free((*triples)[player]); (*triples)[player] = 0; } } free(*triples); *triples = 0; } if (compat) { for(player=0;player<nplayers;++player) { minimacs_rep_clean_up( & compat[player] ); } free(compat); compat = 0; } return compat; }
HRESULT recChannel_t::map(void) { __CONTEXT("recChannel_t::map"); int hr = 0; IBaseFilter * pFilter = NULL; IBaseFilter * pFilter2 = NULL; IPin * pVideoInputPin = NULL; pControl->StopWhenReady(); mapping = true; pOutput = camInfo->output; if (remaped){ //refresh Codec BW before creation pSender->sampleGrabber->BWController->refreshBW(); pSender->rebind(); hr = pGraph->Render(pOutput); { // Enumerate the filters in the graph. IEnumFilters *pEnum = NULL; int hr = pGraph->EnumFilters(&pEnum); if (SUCCEEDED(hr)) { IBaseFilter *pFilter = NULL; pEnum->Reset(); while (S_OK == pEnum->Next(1, &pFilter, NULL)) { CLSID filterId; pFilter->GetClassID(&filterId); if(filterId == CLSID_AviSplitter) { IEnumPins * pEnumpin = NULL; hr = pFilter->EnumPins(&pEnumpin); if (!hr) { IPin * pPin = NULL; pEnumpin->Reset(); while (pEnumpin->Next(1, &pPin, 0) == S_OK) { bool break_loop = false; AM_MEDIA_TYPE * mediaType; IEnumMediaTypes * enumMedia = NULL; hr = pPin->EnumMediaTypes(&enumMedia); if(!hr) { enumMedia->Reset(); while(enumMedia->Next(1,&mediaType , NULL) == S_OK) { if (mediaType->majortype == MEDIATYPE_Audio) { pPin->Disconnect(); pGraph->Render(pPin); pPin->Release(); break_loop = true; break; } } enumMedia->Release(); if (break_loop) break; } } pEnumpin->Release(); } } pFilter->Release(); } pEnum->Release(); } } pipeCreated = true; if (hr) { errorCheck(hr); NOTIFY("[recChannel_t::map]WARNING :: Can't render actual format, restoring default settings...\r\n"); capInfo.heigth = DEFAULT_CAPTURE_HEIGTH; capInfo.width = DEFAULT_CAPTURE_WIDTH; ql_t<AM_MEDIA_TYPE *> auxFormats = camInfo->getFormatList(); pSender->SetActualCodec(DEFAULT_CODEC_STR); } } if (fullScreen){ set_full_screen(true); }else{ hr = setWindowGeometry(windowInfo); errorCheck(hr); } // IVideoWindow *pWindowInfo = NULL; // hr = pGraph->QueryInterface(IID_IVideoWindow, (void **)&pWindowInfo); // if (!hr) // { // wchar_t wtext[100]; // long windowStyle,windowStyleEx; // lText(wtext,title); // pWindowInfo->get_WindowStyle(&windowStyle); // pWindowInfo->get_WindowStyleEx(&windowStyleEx); // windowStyle = windowStyle + DEFAULT_WINDOW_PROPS - DEFAULT_WINDOW_NON_PROPS; // windowStyleEx = windowStyleEx - WS_EX_APPWINDOW; // pWindowInfo->put_WindowStyle(WS_CHILD | WS_CLIPSIBLINGS); // pWindowInfo->put_WindowStyleEx(WS_EX_TOOLWINDOW); // pWindowInfo->put_Caption(wtext); // //#ifdef _WINDOWS // if (camInfo->getKind() == MEDIA) // { // fControl->setGeometry(windowInfo); // // } //#endif ////Ares daemon don't show local windows on ////recChannels //#ifndef __ARES // if (camInfo->getKind() != SHARED) // { // pWindowInfo->put_Visible(OATRUE); // pWindowInfo->put_AutoShow(OATRUE); // } // else // { //#endif // pWindowInfo->put_Visible(OAFALSE); // pWindowInfo->put_AutoShow(OAFALSE); //#ifndef __ARES // } //#endif // // pWindowInfo->Release(); // setOwner(); // } IMediaSeeking * pSeek = NULL; pGraph->QueryInterface(IID_IMediaSeeking,(void **)&pSeek); if (pSeek)pSeek->SetRate(1); pControl->Run(); if (camInfo->getKind() == SHARED) { camInfo->RunSource(); } if (camInfo->getKind() == TEST) { if (pSeek) pSeek->SetRate(0.5); looper->Run(); } remaped = false; return hr; }
void restartSubsystems(RunTimeOpts *rtOpts, PtpClock *ptpClock) { DBG("RestartSubsystems: %d\n",rtOpts->restartSubsystems); /* So far, PTP_INITIALIZING is required for both network and protocol restart */ if((rtOpts->restartSubsystems & PTPD_RESTART_PROTOCOL) || (rtOpts->restartSubsystems & PTPD_RESTART_NETWORK)) { if(rtOpts->restartSubsystems & PTPD_RESTART_NETWORK) { NOTIFY("Applying network configuration: going into PTP_INITIALIZING\n"); } /* These parameters have to be passed to ptpClock before re-init */ ptpClock->clockQuality.clockClass = rtOpts->clockQuality.clockClass; ptpClock->slaveOnly = rtOpts->slaveOnly; ptpClock->disabled = rtOpts->portDisabled; if(rtOpts->restartSubsystems & PTPD_RESTART_PROTOCOL) { INFO("Applying protocol configuration: going into %s\n", ptpClock->disabled ? "PTP_DISABLED" : "PTP_INITIALIZING"); } /* Move back to primary interface only during configuration changes. */ ptpClock->runningBackupInterface = FALSE; toState(ptpClock->disabled ? PTP_DISABLED : PTP_INITIALIZING, rtOpts, ptpClock); } else { /* Nothing happens here for now - SIGHUP handler does this anyway */ if(rtOpts->restartSubsystems & PTPD_UPDATE_DATASETS) { NOTIFY("Applying PTP engine configuration: updating datasets\n"); updateDatasets(ptpClock, rtOpts); }} /* Nothing happens here for now - SIGHUP handler does this anyway */ if(rtOpts->restartSubsystems & PTPD_RESTART_LOGGING) { NOTIFY("Applying logging configuration: restarting logging\n"); } if(rtOpts->restartSubsystems & PTPD_RESTART_ACLS) { NOTIFY("Applying access control list configuration\n"); /* re-compile ACLs */ freeIpv4AccessList(&ptpClock->netPath.timingAcl); freeIpv4AccessList(&ptpClock->netPath.managementAcl); if(rtOpts->timingAclEnabled) { ptpClock->netPath.timingAcl=createIpv4AccessList(rtOpts->timingAclPermitText, rtOpts->timingAclDenyText, rtOpts->timingAclOrder); } if(rtOpts->managementAclEnabled) { ptpClock->netPath.managementAcl=createIpv4AccessList(rtOpts->managementAclPermitText, rtOpts->managementAclDenyText, rtOpts->managementAclOrder); } } #ifdef PTPD_STATISTICS /* Reinitialising the outlier filter containers */ if(rtOpts->restartSubsystems & PTPD_RESTART_FILTERS) { NOTIFY("Applying filter configuration: re-initialising filters\n"); freeDoubleMovingStatFilter(&ptpClock->filterMS); freeDoubleMovingStatFilter(&ptpClock->filterSM); ptpClock->oFilterMS.shutdown(&ptpClock->oFilterMS); ptpClock->oFilterSM.shutdown(&ptpClock->oFilterSM); outlierFilterSetup(&ptpClock->oFilterMS); outlierFilterSetup(&ptpClock->oFilterSM); ptpClock->oFilterMS.init(&ptpClock->oFilterMS,&rtOpts->oFilterMSConfig, "delayMS"); ptpClock->oFilterSM.init(&ptpClock->oFilterSM,&rtOpts->oFilterSMConfig, "delaySM"); if(rtOpts->filterMSOpts.enabled) { ptpClock->filterMS = createDoubleMovingStatFilter(&rtOpts->filterMSOpts,"delayMS"); } if(rtOpts->filterSMOpts.enabled) { ptpClock->filterSM = createDoubleMovingStatFilter(&rtOpts->filterSMOpts, "delaySM"); } } #endif /* PTPD_STATISTICS */ ptpClock->timingService.reloadRequested = TRUE; if(rtOpts->restartSubsystems & PTPD_RESTART_NTPENGINE && timingDomain.serviceCount > 1) { ptpClock->ntpControl.timingService.shutdown(&ptpClock->ntpControl.timingService); } if((rtOpts->restartSubsystems & PTPD_RESTART_NTPENGINE) || (rtOpts->restartSubsystems & PTPD_RESTART_NTPCONFIG)) { ntpSetup(rtOpts, ptpClock); } if((rtOpts->restartSubsystems & PTPD_RESTART_NTPENGINE) && rtOpts->ntpOptions.enableEngine) { timingServiceSetup(&ptpClock->ntpControl.timingService); ptpClock->ntpControl.timingService.init(&ptpClock->ntpControl.timingService); } ptpClock->timingService.dataSet.priority1 = rtOpts->preferNTP; timingDomain.electionDelay = rtOpts->electionDelay; if(timingDomain.electionLeft > timingDomain.electionDelay) { timingDomain.electionLeft = timingDomain.electionDelay; } timingDomain.services[0]->holdTime = rtOpts->ntpOptions.failoverTimeout; if(timingDomain.services[0]->holdTimeLeft > timingDomain.services[0]->holdTime) { timingDomain.services[0]->holdTimeLeft = rtOpts->ntpOptions.failoverTimeout; } ptpClock->timingService.timeout = rtOpts->idleTimeout; /* Update PI servo parameters */ setupPIservo(&ptpClock->servo, rtOpts); /* Config changes don't require subsystem restarts - acknowledge it */ if(rtOpts->restartSubsystems == PTPD_RESTART_NONE) { NOTIFY("Applying configuration\n"); } if(rtOpts->restartSubsystems != -1) rtOpts->restartSubsystems = 0; }
/* * Synchronous signal processing: * This function should be called regularly from the main loop */ void checkSignals(RunTimeOpts * rtOpts, PtpClock * ptpClock) { /* * note: * alarm signals are handled in a similar way in dep/timer.c */ if(sigint_received || sigterm_received){ do_signal_close(ptpClock); } if(sighup_received){ do_signal_sighup(rtOpts, ptpClock); sighup_received=0; } if(sigusr1_received){ if(ptpClock->portState == PTP_SLAVE){ WARNING("SIGUSR1 received, stepping clock to current known OFM\n"); stepClock(rtOpts, ptpClock); // ptpClock->clockControl.stepRequired = TRUE; } else { ERROR("SIGUSR1 received - will not step clock, not in PTP_SLAVE state\n"); } sigusr1_received = 0; } if(sigusr2_received){ /* testing only: testing step detection */ #if 0 { ptpClock->addOffset ^= 1; INFO("a: %d\n", ptpClock->addOffset); sigusr2_received = 0; return; } #endif displayCounters(ptpClock); if(rtOpts->timingAclEnabled) { INFO("\n\n"); INFO("** Timing message ACL:\n"); dumpIpv4AccessList(ptpClock->netPath.timingAcl); } if(rtOpts->managementAclEnabled) { INFO("\n\n"); INFO("** Management message ACL:\n"); dumpIpv4AccessList(ptpClock->netPath.managementAcl); } if(rtOpts->clearCounters) { clearCounters(ptpClock); NOTIFY("PTP engine counters cleared\n"); } #ifdef PTPD_STATISTICS if(rtOpts->oFilterSMConfig.enabled) { ptpClock->oFilterSM.display(&ptpClock->oFilterSM); } if(rtOpts->oFilterMSConfig.enabled) { ptpClock->oFilterMS.display(&ptpClock->oFilterMS); } #endif /* PTPD_STATISTICS */ sigusr2_received = 0; } }
void applyConfig(dictionary *baseConfig, RunTimeOpts *rtOpts, PtpClock *ptpClock) { Boolean reloadSuccessful = TRUE; /* Load default config to fill in the blanks in the config file */ RunTimeOpts tmpOpts; loadDefaultSettings(&tmpOpts); /* Check the new configuration for errors, fill in the blanks from defaults */ if( ( rtOpts->candidateConfig = parseConfig(CFGOP_PARSE, NULL, baseConfig, &tmpOpts)) == NULL ) { WARNING("Configuration has errors, reload aborted\n"); return; } /* Check for changes between old and new configuration */ if(compareConfig(rtOpts->candidateConfig,rtOpts->currentConfig)) { INFO("Configuration unchanged\n"); goto cleanup; } /* * Mark which subsystems have to be restarted. Most of this will be picked up by doState() * If there are errors past config correctness (such as non-existent NIC, * or lock file clashes if automatic lock files used - abort the mission */ rtOpts->restartSubsystems = checkSubsystemRestart(rtOpts->candidateConfig, rtOpts->currentConfig, rtOpts); /* If we're told to re-check lock files, do it: tmpOpts already has what rtOpts should */ if( (rtOpts->restartSubsystems & PTPD_CHECK_LOCKS) && tmpOpts.autoLockFile && !checkOtherLocks(&tmpOpts)) { reloadSuccessful = FALSE; } /* If the network configuration has changed, check if the interface is OK */ if(rtOpts->restartSubsystems & PTPD_RESTART_NETWORK) { INFO("Network configuration changed - checking interface(s)\n"); if(!testInterface(tmpOpts.primaryIfaceName, &tmpOpts)) { reloadSuccessful = FALSE; ERROR("Error: Cannot use %s interface\n",tmpOpts.primaryIfaceName); } if(rtOpts->backupIfaceEnabled && !testInterface(tmpOpts.backupIfaceName, &tmpOpts)) { rtOpts->restartSubsystems = -1; ERROR("Error: Cannot use %s interface as backup\n",tmpOpts.backupIfaceName); } } #if (defined(linux) && defined(HAVE_SCHED_H)) || defined(HAVE_SYS_CPUSET_H) || defined(__QNXNTO__) /* Changing the CPU affinity mask */ if(rtOpts->restartSubsystems & PTPD_CHANGE_CPUAFFINITY) { NOTIFY("Applying CPU binding configuration: changing selected CPU core\n"); if(setCpuAffinity(tmpOpts.cpuNumber) < 0) { if(tmpOpts.cpuNumber == -1) { ERROR("Could not unbind from CPU core %d\n", rtOpts->cpuNumber); } else { ERROR("Could bind to CPU core %d\n", tmpOpts.cpuNumber); } reloadSuccessful = FALSE; } else { if(tmpOpts.cpuNumber > -1) INFO("Successfully bound "PTPD_PROGNAME" to CPU core %d\n", tmpOpts.cpuNumber); else INFO("Successfully unbound "PTPD_PROGNAME" from cpu core CPU core %d\n", rtOpts->cpuNumber); } } #endif if(!reloadSuccessful) { ERROR("New configuration cannot be applied - aborting reload\n"); rtOpts->restartSubsystems = 0; goto cleanup; } /** * Commit changes to rtOpts and currentConfig * (this should never fail as the config has already been checked if we're here) * However if this DOES fail, some default has been specified out of range - * this is the only situation where parse will succeed but commit not: * disable quiet mode to show what went wrong, then die. */ if (rtOpts->currentConfig) { dictionary_del(&rtOpts->currentConfig); } if ( (rtOpts->currentConfig = parseConfig(CFGOP_PARSE_QUIET, NULL, rtOpts->candidateConfig,rtOpts)) == NULL) { CRITICAL("************ "PTPD_PROGNAME": parseConfig returned NULL during config commit" " - this is a BUG - report the following: \n"); if ((rtOpts->currentConfig = parseConfig(CFGOP_PARSE, NULL, rtOpts->candidateConfig,rtOpts)) == NULL) CRITICAL("*****************" PTPD_PROGNAME" shutting down **********************\n"); /* * Could be assert(), but this should be done any time this happens regardless of * compile options. Anyhow, if we're here, the daemon will no doubt segfault soon anyway */ abort(); } /* clean up */ cleanup: dictionary_del(&rtOpts->candidateConfig); }
int main(int argc, char *argv[]) { int x; int j = 0; int result; DATA D = new_data(); ARRAY urls = new_array(); CREW crew; LINES *lines; CLIENT *client; pthread_t cease; pthread_t timer; pthread_attr_t scope_attr; void *statusp; sigset_t sigs; sigemptyset(&sigs); sigaddset(&sigs, SIGHUP); sigaddset(&sigs, SIGINT); sigaddset(&sigs, SIGALRM); sigaddset(&sigs, SIGTERM); sigaddset(&sigs, SIGPIPE); sigprocmask(SIG_BLOCK, &sigs, NULL); lines = xcalloc(1, sizeof *lines); lines->index = 0; lines->line = NULL; memset(&my, 0, sizeof(struct CONFIG)); parse_rc_cmdline(argc, argv); if (init_config() < 0) { exit(EXIT_FAILURE); } parse_cmdline(argc, argv); ds_module_check(); /** * XXX: we should consider moving the following * if-checks into the ds_module_check */ if (my.config) { show_config(TRUE); } if (my.url != NULL) { my.length = 1; } else { my.length = read_cfg_file(lines, my.file); } //if (my.reps < 0) { // my.reps = my.length; //} if (my.length == 0) { display_help(); } /* cookie is an EXTERN, defined in setup */ cookie = xcalloc(sizeof(COOKIE), 1); cookie->first = NULL; if ((result = pthread_mutex_init( &(cookie->mutex), NULL)) !=0) { NOTIFY(FATAL, "pthread_mutex_init" ); } /* memory allocation for threads and clients */ client = xcalloc(my.cusers, sizeof(CLIENT)); if ((crew = new_crew(my.cusers, my.cusers, FALSE)) == NULL) { NOTIFY(FATAL, "unable to allocate memory for %d simulated browser", my.cusers); } /** * determine the source of the url(s), * command line or file, and add them * to the urls struct. */ if (my.url != NULL) { URL tmp = new_url(my.url); url_set_ID(tmp, 0); if (my.get && url_get_method(tmp) != POST && url_get_method(tmp) != PUT) { url_set_method(tmp, my.method); } array_npush(urls, tmp, URLSIZE); // from cmd line } else { for (x = 0; x < my.length; x++) { URL tmp = new_url(lines->line[x]); url_set_ID(tmp, x); array_npush(urls, tmp, URLSIZE); } } /** * display information about the siege * to the user and prepare for verbose * output if necessary. */ if (!my.get && !my.quiet) { fprintf(stderr, "** "); display_version(FALSE); fprintf(stderr, "** Preparing %d concurrent users for battle.\n", my.cusers); fprintf(stderr, "The server is now under siege..."); if (my.verbose) { fprintf(stderr, "\n"); } } /** * record start time before spawning threads * as the threads begin hitting the server as * soon as they are created. */ data_set_start(D); /** * for each concurrent user, spawn a thread and * loop until condition or pthread_cancel from the * handler thread. */ pthread_attr_init(&scope_attr); pthread_attr_setscope(&scope_attr, PTHREAD_SCOPE_SYSTEM); #if defined(_AIX) /* AIX, for whatever reason, defies the pthreads standard and * * creates threads detached by default. (see pthread.h on AIX) */ pthread_attr_setdetachstate(&scope_attr, PTHREAD_CREATE_JOINABLE); #endif /** * invoke OpenSSL's thread safety */ #ifdef HAVE_SSL SSL_thread_setup(); #endif /** * create the signal handler and timer; the * signal handler thread (cease) responds to * ctrl-C (sigterm) and the timer thread sends * sigterm to cease on time out. */ if ((result = pthread_create(&cease, NULL, (void*)sig_handler, (void*)crew)) < 0) { NOTIFY(FATAL, "failed to create handler: %d\n", result); } if (my.secs > 0) { if ((result = pthread_create(&timer, NULL, (void*)siege_timer, (void*)cease)) < 0) { NOTIFY(FATAL, "failed to create handler: %d\n", result); } } /** * loop until my.cusers and create a corresponding thread... */ for (x = 0; x < my.cusers && crew_get_shutdown(crew) != TRUE; x++) { client[x].id = x; client[x].bytes = 0; client[x].time = 0.0; client[x].hits = 0; client[x].code = 0; client[x].ok200 = 0; client[x].fail = 0; if (my.reps > 0 ) { /** * Traditional -r/--reps where each user * loops through every URL in the file. */ client[x].urls = urls; } else { /** * -r once/--reps=once where each URL * in the file is hit only once... */ int len = (array_length(urls)/my.cusers); ARRAY tmp = new_array(); for ( ; j < ((x+1) * len) && j < (int)array_length(urls); j++) { URL u = array_get(urls, j); if (u != NULL && url_get_hostname(u) != NULL && strlen(url_get_hostname(u)) > 1) { array_npush(tmp, array_get(urls, j), URLSIZE); } } client[x].urls = tmp; } client[x].auth.www = 0; client[x].auth.proxy = 0; client[x].auth.type.www = BASIC; client[x].auth.type.proxy = BASIC; client[x].rand_r_SEED = urandom(); result = crew_add(crew, (void*)start_routine, &(client[x])); if (result == FALSE) { my.verbose = FALSE; fprintf(stderr, "Unable to spawn additional threads; you may need to\n"); fprintf(stderr, "upgrade your libraries or tune your system in order\n"); fprintf(stderr, "to exceed %d users.\n", my.cusers); NOTIFY(FATAL, "system resources exhausted"); } } /* end of for pthread_create */ crew_join(crew, TRUE, &statusp); #ifdef HAVE_SSL SSL_thread_cleanup(); #endif /** * collect all the data from all the threads that * were spawned by the run. */ for (x = 0; x < ((crew_get_total(crew) > my.cusers || crew_get_total(crew)==0 ) ? my.cusers : crew_get_total(crew)); x++) { data_increment_count(D, client[x].hits); data_increment_bytes(D, client[x].bytes); data_increment_total(D, client[x].time); data_increment_code (D, client[x].code); data_increment_ok200(D, client[x].ok200); data_increment_fail (D, client[x].fail); data_set_highest (D, client[x].himark); data_set_lowest (D, client[x].lomark); client[x].rand_r_SEED = urandom(); } /* end of stats accumulation */ /** * record stop time */ data_set_stop(D); /** * cleanup crew */ crew_destroy(crew); for (x = 0; x < my.cusers; x++) { // XXX: TODO //digest_challenge_destroy(client[x].auth.wwwchlg); //digest_credential_destroy(client[x].auth.wwwcred); //digest_challenge_destroy(client[x].auth.proxychlg); //digest_credential_destroy(client[x].auth.proxycred); } array_destroy(my.lurl); xfree(client); if (my.get) { if (data_get_ok200(D) > 0) { exit(EXIT_SUCCESS); } else { if (!my.quiet) echo("[done]\n"); exit(EXIT_FAILURE); } } /** * take a short nap for cosmetic effect * this does NOT affect performance stats. */ pthread_usleep_np(10000); if (my.verbose) fprintf(stderr, "done.\n"); else fprintf(stderr, "\b done.\n"); /** * prepare and print statistics. */ if (my.failures > 0 && my.failed >= my.failures) { fprintf(stderr, "%s aborted due to excessive socket failure; you\n", program_name); fprintf(stderr, "can change the failure threshold in $HOME/.%src\n", program_name); } fprintf(stderr, "\nTransactions:\t\t%12u hits\n", data_get_count(D)); fprintf(stderr, "Availability:\t\t%12.2f %%\n", data_get_count(D)==0 ? 0 : (double)data_get_count(D) / (data_get_count(D)+my.failed) *100 ); fprintf(stderr, "Elapsed time:\t\t%12.2f secs\n", data_get_elapsed(D)); fprintf(stderr, "Data transferred:\t%12.2f MB\n", data_get_megabytes(D)); /*%12llu*/ fprintf(stderr, "Response time:\t\t%12.2f secs\n", data_get_response_time(D)); fprintf(stderr, "Transaction rate:\t%12.2f trans/sec\n", data_get_transaction_rate(D)); fprintf(stderr, "Throughput:\t\t%12.2f MB/sec\n", data_get_throughput(D)); fprintf(stderr, "Concurrency:\t\t%12.2f\n", data_get_concurrency(D)); fprintf(stderr, "Successful transactions:%12u\n", data_get_code(D)); if (my.debug) { fprintf(stderr, "HTTP OK received:\t%12u\n", data_get_ok200(D)); } fprintf(stderr, "Failed transactions:\t%12u\n", my.failed); fprintf(stderr, "Longest transaction:\t%12.2f\n", data_get_highest(D)); fprintf(stderr, "Shortest transaction:\t%12.2f\n", data_get_lowest(D)); fprintf(stderr, " \n"); if(my.mark) mark_log_file(my.markstr); if(my.logging) log_transaction(D); data_destroy(D); if (my.url == NULL) { for (x = 0; x < my.length; x++) xfree(lines->line[x]); xfree(lines->line); xfree(lines); } else { xfree(lines->line); xfree(lines); } pthread_mutex_destroy( &(cookie->mutex)); /** * I should probably take a deeper look * at cookie content to free it but at * this point we're two lines from exit */ xfree (cookie); xfree (my.url); exit(EXIT_SUCCESS); } /* end of int main **/
/** * parses command line arguments and assigns * values to run time variables. relies on GNU * getopts included with this distribution. */ void parse_cmdline(int argc, char *argv[]) { int c = 0; int nargs; while ((c = getopt_long(argc, argv, "VhvqCDgl::ibr:t:f:d:c:m:H:R:A:T:", long_options, (int *)0)) != EOF) { switch (c) { case 'V': display_version(TRUE); break; case 'h': display_help(); exit(EXIT_SUCCESS); case 'D': my.debug = TRUE; break; case 'C': my.config = TRUE; my.get = FALSE; break; case 'c': my.cusers = atoi(optarg); break; case 'i': my.internet = TRUE; break; case 'b': my.bench = TRUE; break; case 'd': /* XXX range checking? use strtol? */ my.delay = atof(optarg); if(my.delay < 0){ my.delay = 0; } break; case 'g': my.get = TRUE; break; case 'l': my.logging = TRUE; if (optarg) { my.logfile[strlen(optarg)] = '\0'; strncpy(my.logfile, optarg, strlen(optarg)); } break; case 'm': my.mark = TRUE; my.markstr = optarg; my.logging = TRUE; break; case 'q': my.quiet = TRUE; break; case 'v': my.verbose = TRUE; break; case 'r': if(strmatch(optarg, "once")){ my.reps = -1; } else { my.reps = atoi(optarg); } break; case 't': parse_time(optarg); break; case 'f': memset(my.file, 0, sizeof(my.file)); if(optarg == NULL) break; /*paranoia*/ strncpy(my.file, optarg, strlen(optarg)); break; case 'A': strncpy(my.uagent, optarg, 255); break; case 'T': strncpy(my.conttype, optarg, 255); break; case 'R': /** * processed above */ break; case 'H': { if(!strchr(optarg,':')) NOTIFY(FATAL, "no ':' in http-header"); if((strlen(optarg) + strlen(my.extra) + 3) > 2048) NOTIFY(FATAL, "header is too large"); strcat(my.extra,optarg); strcat(my.extra,"\015\012"); } break; } /* end of switch( c ) */ } /* end of while c = getopt_long */ nargs = argc - optind; if (nargs) my.url = xstrdup(argv[argc-1]); if (my.get && my.url==NULL) { puts("ERROR: -g/--get requires a commandline URL"); exit(1); } return; } /* end of parse_cmdline */
bool recChannel_t::set_captureInfo(captureInfo_t newCapInfo) { __CONTEXT("recChannel_t::set_captureInfo"); char auxHeight[5]; char auxWidth[5]; char auxRes[11]; memset(auxRes,0,strlen(auxRes)); itoa(newCapInfo.heigth,auxHeight,10); itoa(newCapInfo.width,auxWidth,10); strcat(auxRes,auxWidth); strcat(auxRes,"x"); strcat(auxRes,auxHeight); strcat(auxRes,";"); char * supportedRes = camInfo->getSupportedRes(); if ((strstr(supportedRes,auxRes))<=0) { NOTIFY("recChannel_t %d:: Source does not support resolution %s\n", getId(), auxRes); int i=0; for (;i<1000;i++) { itoa(newCapInfo.width+i,auxWidth,10); char * c = NULL; if((c = strstr(supportedRes,auxWidth))>0) { char * w = strstr(c,";"); char * x = strstr(c,"x"); if(x<w) { int j = 0; while(c[j]!=w[0] && c[j]!=0) { auxRes[j] = c[j]; j++; } break; } } } if ((strstr(supportedRes,auxRes))<=0) { return false; }else{ char width[5]; char heigth[5]; memset(width,0,5); memset(heigth,0,5); for (i = 0;auxRes[i]!='x' && auxRes[i]!=0;i++) { width[i] = auxRes[i]; } newCapInfo.width = atoi(width); int j=0; for(i++;auxRes[i]!=0;i++,j++) { heigth[j] = auxRes[i]; } newCapInfo.heigth= atoi(heigth); } } capInfo = newCapInfo; NOTIFY("recChannel_t %d:: Source resolution changed to %dx%d\n", getId(), newCapInfo.width, newCapInfo.heigth); return true; }
/** * Signal handler for HUP which tells us to swap the log file * and reload configuration file if specified * * @param sig */ void do_signal_sighup(RunTimeOpts * rtOpts, PtpClock * ptpClock) { NOTIFY("SIGHUP received\n"); #ifdef RUNTIME_DEBUG if(rtOpts->transport == UDP_IPV4 && rtOpts->ip_mode != IPMODE_UNICAST) { DBG("SIGHUP - running an ipv4 multicast based mode, re-sending IGMP joins\n"); netRefreshIGMP(&ptpClock->netPath, rtOpts, ptpClock); } #endif /* RUNTIME_DEBUG */ /* if we don't have a config file specified, we're done - just reopen log files*/ if(strlen(rtOpts->configFile) == 0) goto end; dictionary* tmpConfig = dictionary_new(0); /* Try reloading the config file */ NOTIFY("Reloading configuration file: %s\n",rtOpts->configFile); if(!loadConfigFile(&tmpConfig, rtOpts)) { dictionary_del(tmpConfig); goto end; } dictionary_merge(rtOpts->cliConfig, tmpConfig, 1, "from command line"); /* Load default config to fill in the blanks in the config file */ RunTimeOpts tmpOpts; loadDefaultSettings(&tmpOpts); /* Check the new configuration for errors, fill in the blanks from defaults */ if( ( rtOpts->candidateConfig = parseConfig(tmpConfig,&tmpOpts)) == NULL ) { WARNING("Configuration file has errors, reload aborted\n"); dictionary_del(tmpConfig); goto end; } /* Check for changes between old and new configuration */ if(compareConfig(rtOpts->candidateConfig,rtOpts->currentConfig)) { INFO("Configuration unchanged\n"); goto cleanup; } /* * Mark which subsystems have to be restarted. Most of this will be picked up by doState() * If there are errors past config correctness (such as non-existent NIC, * or lock file clashes if automatic lock files used - abort the mission */ rtOpts->restartSubsystems = checkSubsystemRestart(rtOpts->candidateConfig, rtOpts->currentConfig); /* If we're told to re-check lock files, do it: tmpOpts already has what rtOpts should */ if( (rtOpts->restartSubsystems & PTPD_CHECK_LOCKS) && tmpOpts.autoLockFile && !checkOtherLocks(&tmpOpts)) { rtOpts->restartSubsystems = -1; } /* If the network configuration has changed, check if the interface is OK */ if(rtOpts->restartSubsystems & PTPD_RESTART_NETWORK) { INFO("Network configuration changed - checking interface\n"); if(!testInterface(tmpOpts.ifaceName, &tmpOpts)) { rtOpts->restartSubsystems = -1; ERROR("Error: Cannot use %s interface\n",tmpOpts.ifaceName); } } #if defined(linux) && defined(HAVE_SCHED_H) /* Changing the CPU affinity mask */ if(rtOpts->restartSubsystems & PTPD_CHANGE_CPUAFFINITY) { NOTIFY("Applying CPU binding configuration: changing selected CPU core\n"); cpu_set_t mask; CPU_ZERO(&mask); if(tmpOpts.cpuNumber > -1) { CPU_SET(tmpOpts.cpuNumber,&mask); } else { int i; for(i = 0; i < CPU_SETSIZE; i++) { CPU_SET(i, &mask); } } if(sched_setaffinity(0, sizeof(mask), &mask) < 0) { if(tmpOpts.cpuNumber == -1) { PERROR("Could not unbind from CPU core %d", rtOpts->cpuNumber); } else { PERROR("Could bind to CPU core %d", tmpOpts.cpuNumber); } rtOpts->restartSubsystems = -1; } else { if(tmpOpts.cpuNumber > -1) INFO("Successfully bound "PTPD_PROGNAME" to CPU core %d\n", tmpOpts.cpuNumber); else INFO("Successfully unbound "PTPD_PROGNAME" from cpu core CPU core %d\n", rtOpts->cpuNumber); } } #endif /* linux && HAVE_SCHED_H */ #ifdef HAVE_SYS_CPUSET_H /* Changing the CPU affinity mask */ if (rtOpts->restartSubsystems & PTPD_CHANGE_CPUAFFINITY) { NOTIFY("Applying CPU binding configuration:" "changing selected CPU core\n"); cpuset_t mask; CPU_ZERO(&mask); if (tmpOpts.cpuNumber < 0) { if (cpuset_getaffinity(CPU_LEVEL_ROOT, CPU_WHICH_CPUSET, 1, sizeof(mask), &mask) < 0) PERROR("Could not get affinity."); if (cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(mask), &mask) < 0) PERROR("Could not unbind from CPU core %d", rtOpts->cpuNumber); else INFO("Successfully unbound " PTPD_PROGNAME" from cpu core CPU core %d\n", rtOpts->cpuNumber); } else { CPU_SET(tmpOpts.cpuNumber,&mask); if (cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(mask), &mask) < 0) { PERROR("Could not bind to CPU core %d", tmpOpts.cpuNumber); rtOpts->restartSubsystems = -1; } else { INFO("Successfully bound " PTPD_PROGNAME" to CPU core %d\n", tmpOpts.cpuNumber); } } } #endif if(rtOpts->restartSubsystems == -1) { ERROR("New configuration cannot be applied - aborting reload\n"); rtOpts->restartSubsystems = 0; goto cleanup; } /* Tell parseConfig to shut up - it's had its chance already */ dictionary_set(rtOpts->candidateConfig,"%quiet%:%quiet%","Y"); /** * Commit changes to rtOpts and currentConfig * (this should never fail as the config has already been checked if we're here) * However if this DOES fail, some default has been specified out of range - * this is the only situation where parse will succeed but commit not: * disable quiet mode to show what went wrong, then die. */ if (rtOpts->currentConfig) { dictionary_del(rtOpts->currentConfig); } if ( (rtOpts->currentConfig = parseConfig(rtOpts->candidateConfig,rtOpts)) == NULL) { CRITICAL("************ "PTPD_PROGNAME": parseConfig returned NULL during config commit" " - this is a BUG - report the following: \n"); dictionary_unset(rtOpts->candidateConfig,"%quiet%:%quiet%"); if ((rtOpts->currentConfig = parseConfig(rtOpts->candidateConfig,rtOpts)) == NULL) CRITICAL("*****************" PTPD_PROGNAME" shutting down **********************\n"); /* * Could be assert(), but this should be done any time this happens regardless of * compile options. Anyhow, if we're here, the daemon will no doubt segfault soon anyway */ abort(); } /* clean up */ cleanup: dictionary_del(tmpConfig); dictionary_del(rtOpts->candidateConfig); end: if(rtOpts->recordLog.logEnabled || rtOpts->eventLog.logEnabled || (rtOpts->statisticsLog.logEnabled)) INFO("Reopening log files\n"); restartLogging(rtOpts); if(rtOpts->statisticsLog.logEnabled) ptpClock->resetStatisticsLog = TRUE; }
int recChannel_t::source_format(char* newFormat) { __CONTEXT("recChannel_t::source_format"); int hr = 0; bool formatFound = false; IAMStreamConfig *pConfig = NULL; AM_MEDIA_TYPE * format = NULL; pControl->StopWhenReady(); ql_t<AM_MEDIA_TYPE *> auxFormats = camInfo->getFormatList(); for(int i = 0; i<auxFormats.len() ; i++) { AM_MEDIA_TYPE format = *(auxFormats.nth(i)); IAMStreamConfig *pConfig = NULL; IVideoWindow * pWindow = NULL; char subtypeName [100]; memset(subtypeName,0,100); GetGUIDString(subtypeName,&format.subtype); VIDEOINFOHEADER *pVih = (VIDEOINFOHEADER*) format.pbFormat; if((pVih==NULL && strcmp(newFormat,sourceFormat)==0 )|| (pVih->bmiHeader.biHeight == capInfo.heigth && pVih->bmiHeader.biWidth == capInfo.width && strcmp(subtypeName,newFormat)==0) || camInfo->getKind() == SHARED ) { if (strcmp(sourceFormat,newFormat)) { memset(sourceFormat,0,100); strcpy(sourceFormat,newFormat); } if (!hr && (camInfo->getKind() == CAM || camInfo->getKind() == SHARED)){ camInfo->output->Disconnect(); hr = camInfo->output->QueryInterface(IID_IAMStreamConfig, (void**)&pConfig); //pVih->AvgTimePerFrame = 666666;// pVih->AvgTimePerFrame = 333333/(frameRate); int hr = pConfig->SetFormat(&format); actualFormat = format; pConfig->Release(); } formatFound = true; break; } } if (!formatFound) { IAMStreamConfig *pConfig = NULL; if (camInfo->getKind() == CAM || camInfo->getKind() == SHARED) { VIDEOINFOHEADER *pVih = (VIDEOINFOHEADER*) actualFormat.pbFormat; camInfo->output->Disconnect(); hr = camInfo->output->QueryInterface(IID_IAMStreamConfig, (void**)&pConfig); //pVih->AvgTimePerFrame = 666666; if (pConfig) { int hr = pConfig->SetFormat(&actualFormat); pConfig->Release(); } } } NOTIFY("reChannel_t" "\r\n=========================================\r\n" "Channel %d : Source Description...\r\n" "- sourceName: %s\r\n" "- capture Size: %dx%d\r\n" "- supported Formats: %s\r\n" "- Window Info: (%d,%d,%d,%d)\r\n" "- Title: %s\r\n" "=========================================\r\n", getId(), camInfo->getCamName(), capInfo.width, capInfo.heigth, camInfo->getSupportedFormats(), windowInfo.top, windowInfo.left, windowInfo.width, windowInfo.heigth, title); remap(); if (mapping){ map(); } return 0; }
PtpClock * ptpdStartup(int argc, char **argv, Integer16 * ret, RunTimeOpts * rtOpts) { PtpClock * ptpClock; int i = 0; /* * Set the default mode for all newly created files - previously * this was not the case for log files. This adds consistency * and allows to use FILE* vs. fds everywhere */ umask(~DEFAULT_FILE_PERMS); /** * If a required setting, such as interface name, or a setting * requiring a range check is to be set via getopts_long, * the respective currentConfig dictionary entry should be set, * instead of just setting the rtOpts field. * * Config parameter evaluation priority order: * 1. Any dictionary keys set in the getopt_long loop * 2. CLI long section:key type options * 3. Config file (parsed last), merged with 2. and 3 - will be overwritten by CLI options * 4. Defaults and any rtOpts fields set in the getopt_long loop **/ /** * Load defaults. Any options set here and further inside loadCommandLineOptions() * by setting rtOpts fields, will be considered the defaults * for config file and section:key long options. */ loadDefaultSettings(rtOpts); /* initialise the config dictionary */ rtOpts->candidateConfig = dictionary_new(0); rtOpts->cliConfig = dictionary_new(0); /* parse all long section:key options and clean up argv for getopt */ loadCommandLineKeys(rtOpts->cliConfig,argc,argv); /* parse the normal short and long option, exit on error */ if (!loadCommandLineOptions(rtOpts, rtOpts->cliConfig, argc, argv, ret)) { goto fail; } /* Display startup info and argv if not called with -? or -H */ NOTIFY("%s version %s starting\n",USER_DESCRIPTION, USER_VERSION); dump_command_line_parameters(argc, argv); /* * we try to catch as many error conditions as possible, but before we call daemon(). * the exception is the lock file, as we get a new pid when we call daemon(), * so this is checked twice: once to read, second to read/write */ if(geteuid() != 0) { printf("Error: "PTPD_PROGNAME" daemon can only be run as root\n"); *ret = 1; goto fail; } /* Have we got a config file? */ if(strlen(rtOpts->configFile) > 0) { /* config file settings overwrite all others, except for empty strings */ INFO("Loading configuration file: %s\n",rtOpts->configFile); if(loadConfigFile(&rtOpts->candidateConfig, rtOpts)) { dictionary_merge(rtOpts->cliConfig, rtOpts->candidateConfig, 1, "from command line"); } else { *ret = 1; dictionary_merge(rtOpts->cliConfig, rtOpts->candidateConfig, 1, "from command line"); goto configcheck; } } else { dictionary_merge(rtOpts->cliConfig, rtOpts->candidateConfig, 1, "from command line"); } /** * This is where the final checking of the candidate settings container happens. * A dictionary is returned with only the known options, explicitly set to defaults * if not present. NULL is returned on any config error - parameters missing, out of range, * etc. The getopt loop in loadCommandLineOptions() only sets keys verified here. */ if( ( rtOpts->currentConfig = parseConfig(rtOpts->candidateConfig,rtOpts)) == NULL ) { *ret = 1; dictionary_del(rtOpts->candidateConfig); goto configcheck; } /* we've been told to print the lock file and exit cleanly */ if(rtOpts->printLockFile) { printf("%s\n", rtOpts->lockFile); *ret = 0; goto fail; } /* we don't need the candidate config any more */ dictionary_del(rtOpts->candidateConfig); /* Check network before going into background */ if(!testInterface(rtOpts->ifaceName, rtOpts)) { ERROR("Error: Cannot use %s interface\n",rtOpts->ifaceName); *ret = 1; goto configcheck; } configcheck: /* * We've been told to check config only - clean exit before checking locks */ if(rtOpts->checkConfigOnly) { if(*ret != 0) { printf("Configuration has errors\n"); *ret = 1; } else printf("Configuration OK\n"); return 0; } /* Previous errors - exit */ if(*ret !=0) return 0; /* First lock check, just to be user-friendly to the operator */ if(!rtOpts->ignore_daemon_lock) { if(!writeLockFile(rtOpts)) { /* check and create Lock */ ERROR("Error: file lock failed (use -L or global:ignore_lock to ignore lock file)\n"); *ret = 3; return 0; } /* check for potential conflicts when automatic lock files are used */ if(!checkOtherLocks(rtOpts)) { *ret = 3; return 0; } } /* Manage log files: stats, log, status and quality file */ restartLogging(rtOpts); /* Allocate memory after we're done with other checks but before going into daemon */ ptpClock = (PtpClock *) calloc(1, sizeof(PtpClock)); if (!ptpClock) { PERROR("Error: Failed to allocate memory for protocol engine data"); *ret = 2; return 0; } else { DBG("allocated %d bytes for protocol engine data\n", (int)sizeof(PtpClock)); ptpClock->foreign = (ForeignMasterRecord *) calloc(rtOpts->max_foreign_records, sizeof(ForeignMasterRecord)); if (!ptpClock->foreign) { PERROR("failed to allocate memory for foreign " "master data"); *ret = 2; free(ptpClock); return 0; } else { DBG("allocated %d bytes for foreign master data\n", (int)(rtOpts->max_foreign_records * sizeof(ForeignMasterRecord))); } ptpClock->owd_filt = FilterCreate(FILTER_EXPONENTIAL_SMOOTH, "owd"); ptpClock->ofm_filt = FilterCreate(FILTER_MOVING_AVERAGE, "ofm"); } if(rtOpts->statisticsLog.logEnabled) ptpClock->resetStatisticsLog = TRUE; /* Init to 0 net buffer */ memset(ptpClock->msgIbuf, 0, PACKET_SIZE); memset(ptpClock->msgObuf, 0, PACKET_SIZE); /* Init user_description */ memset(ptpClock->user_description, 0, sizeof(ptpClock->user_description)); memcpy(ptpClock->user_description, &USER_DESCRIPTION, sizeof(USER_DESCRIPTION)); /* Init outgoing management message */ ptpClock->outgoingManageTmp.tlv = NULL; /* DAEMON */ #ifdef PTPD_NO_DAEMON if(!rtOpts->nonDaemon) { rtOpts->nonDaemon=TRUE; } #endif if(!rtOpts->nonDaemon) { /* * fork to daemon - nochdir non-zero to preserve the working directory: * allows relative paths to be used for log files, config files etc. * Always redirect stdout/err to /dev/null */ if (daemon(1,0) == -1) { PERROR("Failed to start as daemon"); *ret = 3; return 0; } INFO(" Info: Now running as a daemon\n"); /* * Wait for the parent process to terminate, but not forever. * On some systems this happened after we tried re-acquiring * the lock, so the lock would fail. Hence, we wait. */ for (i = 0; i < 1000000; i++) { /* Once we've been reaped by init, parent PID will be 1 */ if(getppid() == 1) break; usleep(1); } } /* Second lock check, to replace the contents with our own new PID and re-acquire the advisory lock */ if(!rtOpts->nonDaemon && !rtOpts->ignore_daemon_lock) { /* check and create Lock */ if(!writeLockFile(rtOpts)) { ERROR("Error: file lock failed (use -L or global:ignore_lock to ignore lock file)\n"); *ret = 3; return 0; } } #if defined(linux) && defined(HAVE_SCHED_H) /* Try binding to a single CPU core if configured to do so */ if(rtOpts->cpuNumber > -1) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(rtOpts->cpuNumber,&mask); if(sched_setaffinity(0, sizeof(mask), &mask) < 0) { PERROR("Could not bind to CPU core %d", rtOpts->cpuNumber); } else { INFO("Successfully bound "PTPD_PROGNAME" to CPU core %d\n", rtOpts->cpuNumber); } } #endif /* linux && HAVE_SCHED_H */ #ifdef HAVE_SYS_CPUSET_H /* Try binding to a single CPU core if configured to do so */ if(rtOpts->cpuNumber > -1) { cpuset_t mask; CPU_ZERO(&mask); CPU_SET(rtOpts->cpuNumber,&mask); if(cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(mask), &mask) < 0) { PERROR("Could not bind to CPU core %d", rtOpts->cpuNumber); } else { INFO("Successfully bound "PTPD_PROGNAME" to CPU core %d\n", rtOpts->cpuNumber); } } #endif /* HAVE_SYS_CPUSET_H */ /* use new synchronous signal handlers */ signal(SIGINT, catchSignals); signal(SIGTERM, catchSignals); signal(SIGHUP, catchSignals); signal(SIGUSR1, catchSignals); signal(SIGUSR2, catchSignals); #if defined PTPD_SNMP /* Start SNMP subsystem */ if (rtOpts->snmp_enabled) snmpInit(rtOpts, ptpClock); #endif NOTICE(USER_DESCRIPTION" started successfully on %s using \"%s\" preset (PID %d)\n", rtOpts->ifaceName, (getPtpPreset(rtOpts->selectedPreset,rtOpts)).presetName, getpid()); ptpClock->resetStatisticsLog = TRUE; #ifdef PTPD_STATISTICS if (rtOpts->delayMSOutlierFilterEnabled) { ptpClock->delayMSRawStats = createDoubleMovingStdDev(rtOpts->delayMSOutlierFilterCapacity); strncpy(ptpClock->delayMSRawStats->identifier, "delayMS", 10); ptpClock->delayMSFiltered = createDoubleMovingMean(rtOpts->delayMSOutlierFilterCapacity); } else { ptpClock->delayMSRawStats = NULL; ptpClock->delayMSFiltered = NULL; } if (rtOpts->delaySMOutlierFilterEnabled) { ptpClock->delaySMRawStats = createDoubleMovingStdDev(rtOpts->delaySMOutlierFilterCapacity); strncpy(ptpClock->delaySMRawStats->identifier, "delaySM", 10); ptpClock->delaySMFiltered = createDoubleMovingMean(rtOpts->delaySMOutlierFilterCapacity); } else { ptpClock->delaySMRawStats = NULL; ptpClock->delaySMFiltered = NULL; } #endif *ret = 0; return ptpClock; fail: dictionary_del(rtOpts->candidateConfig); return 0; }
void BasicHDT::loadTriplesFromHDTs(const char** fileNames, size_t numFiles, const char* baseUri, ProgressListener* listener) { // Generate Triples ModifiableTriples* triplesList = new TriplesList(spec); //ModifiableTriples *triplesList = new TriplesKyoto(spec); //ModifiableTriples *triplesList = new TripleListDisk(); StopWatch st; IntermediateListener iListener(listener); try { NOTIFY(listener, "Loading Triples", 0, 100); iListener.setRange(0, 60); triplesList->startProcessing(&iListener); TriplesLoader tripLoader(dictionary, triplesList, &iListener); // FIXME: Import from files uint64_t totalOriginalSize=0; BasicHDT hdt; for(size_t i=0;i<numFiles;i++) { const char *fileName = fileNames[i]; cout << endl << "Load triples from " << fileName << endl; hdt.mapHDT(fileName); Dictionary *dict = hdt.getDictionary(); // Create mapping arrays cout << "Generating mapping subjects" << endl; unsigned int nsubjects = dict->getNsubjects(); LogSequence2 subjectMap(bits(dictionary->getNsubjects()), nsubjects); subjectMap.resize(nsubjects); for(unsigned int i=0;i<nsubjects;i++) { string str = dict->idToString(i+1, SUBJECT); unsigned int newid = dictionary->stringToId(str, SUBJECT); subjectMap.set(i, newid); } cout << "Generating mapping predicates" << endl; unsigned int npredicates = dict->getNpredicates(); LogSequence2 predicateMap(bits(dictionary->getNpredicates()), npredicates); predicateMap.resize(npredicates); for(unsigned int i=0;i<npredicates;i++) { string str = dict->idToString(i+1, PREDICATE); unsigned int newid = dictionary->stringToId(str, PREDICATE); predicateMap.set(i, newid); } cout << "Generating mapping objects" << endl; unsigned int nobjects = dict->getNobjects(); LogSequence2 objectMap(bits(dictionary->getNobjects()), nobjects); objectMap.resize(nobjects); for(unsigned int i=0;i<nobjects;i++) { string str = dict->idToString(i+1, OBJECT); unsigned int newid = dictionary->stringToId(str, OBJECT); objectMap.set(i, newid); } totalOriginalSize += hdt.getHeader()->getPropertyLong("_:statistics", HDTVocabulary::ORIGINAL_SIZE.c_str()); size_t numtriples = hdt.getTriples()->getNumberOfElements(); IteratorTripleID *it = hdt.getTriples()->searchAll(); TripleID newTid; char str[100]; long long int j = 0; while(it->hasNext()) { TripleID *tid = it->next(); newTid.setAll( (unsigned int)subjectMap.get(tid->getSubject()-1), (unsigned int)predicateMap.get(tid->getPredicate()-1), (unsigned int)objectMap.get(tid->getObject()-1) ); triplesList->insert(newTid); if ((listener != NULL) && (j % 100000) == 0) { sprintf(str, "%lld triples added.", j); listener->notifyProgress((j*100)/numtriples, str); } j++; } delete it; } triplesList->stopProcessing(&iListener); // SORT & Duplicates TripleComponentOrder order = parseOrder(spec.get("triplesOrder").c_str()); if (order == Unknown) { order = SPO; } iListener.setRange(80, 85); triplesList->sort(order, &iListener); iListener.setRange(85, 90); triplesList->removeDuplicates(&iListener); header->insert("_:statistics", HDTVocabulary::ORIGINAL_SIZE, totalOriginalSize); } catch (const char *e) { cout << "Catch exception triples" << e << endl; delete triplesList; throw e; } catch (char *e) { cout << "Catch exception triples" << e << endl; delete triplesList; throw e; } if (triples->getType() == triplesList->getType()) { delete triples; triples = triplesList; } else { iListener.setRange(90, 100); try { triples->load(*triplesList, &iListener); } catch (const char* e) { delete triplesList; throw e; } delete triplesList; } //cout << triples->getNumberOfElements() << " triples added in " << st << endl << endl; }
/** * @brief Function to set time to the system or specific * hardware PTP timer (based on system capabilities * and architecture) base on ptpv2d system * internal time format * * @param[in] time Pointer to TimeInternal structure with time in seconds and nanoseconds TAI time * @param[in] utc_offset Integer16 value of number of UTC leap seconds since January 1, 1970 */ void setTime(TimeInternal *time, Integer16 utc_offset) { #ifdef CONFIG_MPC831X mpc831x_set_curr_time(time); #elif defined(__WINDOWS__) unsigned long long U64WindowsTime; FILETIME WindowsUTCTime; SYSTEMTIME WindowsSystemTime; U64WindowsTime = (unsigned long long) time->seconds; // Change epoch in seconds from January 1, 1970 // to Windows January 1, 1901 U64WindowsTime += 11644473600ULL; // Change seconds from January 1, 1970 TAI time to UTC time U64WindowsTime -= (unsigned long long) utc_offset; // Convert seconds to 100 ns increments since January 1, 1601 U64WindowsTime *= 10000000ULL; // Add in nanoseconds converted to 100 ns increments U64WindowsTime += (unsigned long long)(time->nanoseconds / 100U); // Convert unsigned long long 64 bit variable to // File time structure time WindowsUTCTime.dwLowDateTime = (unsigned long)(U64WindowsTime & (unsigned long long)0xFFFFFFFF); WindowsUTCTime.dwHighDateTime = (unsigned long)(U64WindowsTime >> 32); // Convert Windows UTC "file time" to Windows UTC "system time" FileTimeToSystemTime(&WindowsUTCTime, &WindowsSystemTime); // Now finally we can set the windows system time SetSystemTime(&WindowsSystemTime); // Sets the current system time #else // Linux time type, simply need to convert nanoseconds // to microseconds, subtract the TAI time UTC offset // (leap seconds since January 1, 1970) and set // the time struct timeval tv; tv.tv_sec = time->seconds; tv.tv_usec = time->nanoseconds/1000; /* PTP uses TAI, gettime of day is UTC, so adjust by subtracting * UTC offset from TAI to adjust for leap seconds */ tv.tv_sec -= utc_offset; settimeofday(&tv, 0); #endif NOTIFY("setTime: resetting clock to UTC %ds %dns\n", time->seconds, time->nanoseconds); }
videoApp_t::videoApp_t(int &argc,argv_t &argv) :application_t(argc, argv), __controlPort(NULL), __bandwidth(1000000.0) { strcpy(__rtpPort,"51017"); strcpy(__rtcpPort,"51019"); enum myOptions { ctrlPort, notify, dport, autoChannel, h }; s = static_cast<sched_t*>(this); optionDefList_t opt; appParamList_t *parList; //Available options opt << new optionDef_t("@cport", ctrlPort , "Opens a Control Socket in <port>") << new optionDef_t("@rtpPort", dport , "Receiver data port") << new optionDef_t("@notify", notify , "Notify file") << new optionDef_t("autoChannel", autoChannel , "autoShows playChannels") << new optionDef_t("h", h , "Video Help"); parList = getOpt(opt, argc, argv); ctrlTask_t * ctrlTask = NULL; SetAutoChannel = new bool(); *SetAutoChannel = false; for ( ; parList->len(); parList->behead()) { switch(parList->head()->parId) { case ctrlPort: char * port; port = strdup(parList->head()->parValue); ctrlTask = new ctrlTask_t(port); break; case dport: char * strDport; strDport = strdup(parList->head()->parValue); strcpy(__rtpPort,strDport); itoa(atoi(strDport) + 2,__rtcpPort,10); break; case notify: char * file; file = strdup(parList->head()->parValue); setNotifyFile(file); break; case autoChannel: *SetAutoChannel = true; break; case h: default: int i; for(i=0; i < opt.len(); i++) { optionDef_t * op= static_cast<optionDef_t*>(opt.nth(i)); if(op->optDesc) fprintf(stderr, " %-10s %-5s\t-- %s\n", op->optName, op->optHasArg?"value":"", op->optDesc); else fprintf(stderr, " %-10s %-5s\t", op->optName, op->optHasArg?"":"value"); } exit(0); break; } }; // RTP Object Creation #ifdef WIN32 if (getenv("MCU_USE_ONLY_IPv4")){ rtpSession= new videoRTPSession_t(this, "0.0.0.0", __rtpPort, "0.0.0.0", __rtcpPort, VIDEO_TIMESTAMP_UNIT ); } else{ rtpSession= new videoRTPSession_t(this, NULL, __rtpPort, NULL, __rtcpPort, VIDEO_TIMESTAMP_UNIT ); } #else rtpSession= new videoRTPSession_t(this, NULL, __rtpPort, NULL, __rtcpPort, VIDEO_TIMESTAMP_UNIT ); #endif //init log file struct _timeb timebuffer; char * timeline; _ftime( &timebuffer ); timeline = ctime( & ( timebuffer.time ) ); char auxFile[20]; char auxArgv[100]; memset(auxArgv,0,100); for (int i = 1; i<argc; i++) { strcat(auxArgv,argv[i]); strcat(auxArgv," "); } if (char * n = strstr(auxArgv,"File")) { n = strstr(n," "); strcpy(auxFile,n); }else{ strcpy(auxFile," Screen"); } // Debug Session Info NOTIFY( "\n·:======================================================:·\n\n" " Isabel Video v0.1 Debug Session:\n\n" " - Options: %s\n" " - Log File:%s\n" " - Date: %s\n" " - Author: Vicente Sirvent Orts\n" "\n" "·:=======================================================:·\n\n", auxArgv, auxFile, timeline); }
void * drsym_obj_mod_init_pre(byte *map_base, size_t map_size) { IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *) map_base; IMAGE_NT_HEADERS *nt; IMAGE_SECTION_HEADER *sec; uint i; pecoff_data_t *mod; bool is_mingw = false; if (dos->e_magic != IMAGE_DOS_SIGNATURE) return NULL; nt = (IMAGE_NT_HEADERS *) (((ptr_uint_t)dos) + dos->e_lfanew); if (nt == NULL || nt->Signature != IMAGE_NT_SIGNATURE) return NULL; mod = dr_global_alloc(sizeof(*mod)); memset(mod, 0, sizeof(*mod)); mod->map_base = map_base; mod->map_size = map_size; mod->symbol_table = (IMAGE_SYMBOL *) (map_base + nt->FileHeader.PointerToSymbolTable); mod->symbol_count = nt->FileHeader.NumberOfSymbols; NOTIFY(1, "%s: mapped @"PFX" w/ %d symbols\n", __FUNCTION__, map_base, mod->symbol_count); /* String table immediately follows symbol table */ mod->string_table = ((const char *)mod->symbol_table) + (nt->FileHeader.NumberOfSymbols * sizeof(IMAGE_SYMBOL)); if (mod->symbol_count > 0) mod->debug_kind |= DRSYM_SYMBOLS | DRSYM_PECOFF_SYMTAB; mod->is_64 = (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC); mod->preferred_base = (byte *)(ptr_uint_t) (mod->is_64 ? ((IMAGE_OPTIONAL_HEADER64 *)(&nt->OptionalHeader))->ImageBase : nt->OptionalHeader.ImageBase); /* We sort the symbols only once we know the time spent is worth it in init_post */ mod->section_count = nt->FileHeader.NumberOfSections; mod->section_base = (size_t *) dr_global_alloc(mod->section_count*sizeof(*mod->section_base)); sec = IMAGE_FIRST_SECTION(nt); for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++) { size_t name_maxsz; const char *secname = drsym_pecoff_get_section_name(mod, sec, &name_maxsz); NOTIFY(2, "%s: %.*s\n", __FUNCTION__, name_maxsz, secname); if (strncmp(secname, ".debug_line", name_maxsz) == 0) { mod->debug_kind |= DRSYM_LINE_NUMS | DRSYM_DWARF_LINE; } if (strncmp(secname, ".gnu_debuglink", name_maxsz) == 0) { mod->debuglink = sec->PointerToRawData + mod->map_base; } /* i#1395: heuristic to identify MinGW stripped libraries */ if (strncmp(secname, ".eh_frame", name_maxsz) == 0 || strncmp(secname, ".CRT", name_maxsz) == 0) { is_mingw = true; } mod->section_base[i] = sec->VirtualAddress; } /* i#1395: since dbghelp does not handle MinGW exports properly (strips leading * underscore and does not demangle) we handle them ourselves. * * XXX: it might be better to check for presence of a PDB first, just in case * our heuristics match non-MinGW -- but that's a little awkward to arrange * with the current code setup. */ if (is_mingw && TEST(IMAGE_FILE_LOCAL_SYMS_STRIPPED, nt->FileHeader.Characteristics) && mod->symbol_count == 0) { mod->exports_only = true; NOTIFY(1, "%s: no pecoff symbols and likely no pdb, so using exports\n", __FUNCTION__); } return (void *) mod; }