Esempio n. 1
0
/*  main function takes a PLATYPUS source file as
 *  an argument at the command line.
 *  usage: scanner source_file_name"
 */     
int main(int argc, char ** argv){

	Buffer *sc_buf; /* pointer to input (source) buffer */
	FILE *fi;       /* input file handle */
	Token t;        /* token produced by the scanner */
	int loadsize = 0; /*the size of the file loaded in the buffer */
    int ansi_c = !ANSI_C; /* ANSI C compliancy flag */

/* Check if the compiler option is set to compile ANSI C */
/* __DATE__, __TIME__, __LINE__, __FILE__, __STDC__ are predefined preprocessor macros*/
  if(ansi_c){
    err_printf("Date: %s  Time: %s",__DATE__, __TIME__);
    err_printf("ERROR: Compiler is not ANSI C compliant!\n");
    exit(1);
  }

/*check for correct arrguments - source file name */
      if (argc <= 1){
/* __DATE__, __TIME__, __LINE__, __FILE__ are predefined preprocessor macros*/
       err_printf("Date: %s  Time: %s",__DATE__, __TIME__);
       err_printf("Runtime error at line %d in file %s", __LINE__, __FILE__);
       err_printf("%s%s%s",argv[0],": ","Missing source file name.");
       err_printf("%s%s%s","Usage: ", "scanner", "  source_file_name");
       exit(1);
	}	
 

 /* create a source code input buffer - multiplicative mode */	
	sc_buf = b_create(INIT_CAPACITY,INC_FACTOR,'m');
	if (sc_buf == NULL){
	  err_printf("%s%s%s",argv[0],": ","Could not create source buffer");
	  exit(1);
	}

/*open source file */
	if ((fi = fopen(argv[1],"r")) == NULL){
		err_printf("%s%s%s%s",argv[0],": ", "Cannot open file: ",argv[1]);
		exit (1);
	}
/* load source file into input buffer  */
     printf("Reading file %s ....Please wait\n",argv[1]);
     loadsize = b_load (fi,sc_buf);
     if(loadsize == R_FAIL_1)
       err_printf("%s%s%s",argv[0],": ","Error in loading buffer.");

/* close source file */	
 	fclose(fi);
/*find the size of the file  */
    if (loadsize == LOAD_FAIL){
     printf("The input file %s %s\n", argv[1],"is not completely loaded.");
     printf("Input file size: %ld\n", get_filesize(argv[1]));
    }
/* pack and display the source buffer */

       if(b_pack(sc_buf)){
         display(sc_buf);
  }

/* create string Literal Table */
 	
  str_LTBL = b_create(INIT_CAPACITY,INC_FACTOR,'a');
	if (str_LTBL == NULL){
	 err_printf("%s%s%s",argv[0],": ","Could not create string literals buffer");
	 exit(1);
	}
	
	/*Testbed for the scanner */
/* add SEOF to input program buffer*/
	b_addc(sc_buf,'\0');

	/* Initialize scanner input buffer */ 
	if(scanner_init(sc_buf)){;
	  err_printf("%s%s%s",argv[0],": ","Empty program buffer - scanning canceled");
	  exit(1); 
	}	

	printf("\nScanning source file...\n\n");
	printf("Token\t\tAttribute\n");
	printf("----------------------------------\n");
	do{	
	  t= mlwpar_next_token(sc_buf);  
	  print_token(t);
	}while(t.code != SEOF_T);
  if(b_size(str_LTBL)) b_print(str_LTBL);
	b_destroy(sc_buf);
	b_destroy(str_LTBL);
	sc_buf = str_LTBL = NULL;
 
  return (0);
}
Esempio n. 2
0
SysStatus
HATDefaultBase<ALLOC>::unmapRange(uval rangeAddr, uval rangeSize, VPSet ppset)
{
    SysStatus rc=0;
    SegmentList<ALLOC>* restart;
    SegmentHATRef ref;
    VPSet *tmpset, unionset;
    VPNum numprocs, pp, mypp;
    uval rangeEnd = rangeAddr+rangeSize;
    uval segmentAddr, segmentEnd;
    UnmapRangeMsg msg;
    /* we first cleanup the global list and find what processors have cached
     * copies of the segment in their local lists.
     */
    glock.acquire();
    restart = &segmentList;
    while (0<=(rc = SegmentList<ALLOC>::DeleteSegment(
	rangeAddr, rangeEnd,  segmentAddr, segmentEnd,
	ref, tmpset, restart))) {
	// accumulate all pp's which have seen any relevant segment
	unionset.unite(*tmpset);
	if(rc == 0) {
	    // if we delete the whole segmentHAT, we must visit
	    // every processor that's seen it, no matter what this
	    // region says
	    ppset.unite(*tmpset);
	}
    }
    glock.release();
    // only visit pp's which this region has seen
    unionset.intersect(ppset);

    msg.barrier	    = 1;
    msg.waiter	    = Scheduler::GetCurThread();
    msg.myRef       = getRef();
    msg.start       = rangeAddr;
    msg.size        = rangeSize;

    mypp = Scheduler::GetVP();		// physical processor
    numprocs = DREFGOBJK(TheProcessRef)->vpCount();
    for (pp = unionset.firstVP(numprocs); pp < numprocs;
	 pp = unionset.nextVP(pp, numprocs)) {
	if (pp != mypp) {
	    //err_printf("Remote unmap for %d\n", vp);
	    FetchAndAddSignedVolatile(&msg.barrier,1);
	    rc = MPMsgMgr::SendAsyncUval(Scheduler::GetEnabledMsgMgr(),
					 SysTypes::DSPID(0, pp),
					 UnmapRangeMsgHandler, uval(&msg));
	    tassert(_SUCCESS(rc),err_printf("UnmapRange remote failed\n"));
	}
    }

    if (unionset.isSet(mypp)) {
	rc = unmapRangeLocal(rangeAddr, rangeSize);
	tassert(_SUCCESS(rc), err_printf("oops\n"));
    }

    FetchAndAddSignedVolatile(&msg.barrier,-1);

    while (msg.barrier != 0) {
	Scheduler::Block();
    }

    //err_printf("All done unmapRange\n");

    return 0;
}
Esempio n. 3
0
File: main.c Progetto: Frogee/bwa
void bwa_print_sam_PG()
{
	err_printf("@PG\tID:bwa\tPN:bwa\tVN:%s\n", PACKAGE_VERSION);
}
Esempio n. 4
0
/* this is called from assembler and passed control in long mode 64 bit
 * interrupts disabled.
 * At this stage the first 32MB have been mapped with 2MB pages.
 */
extern "C" void
kinit()
{
    extern char __bss_end[];
    struct KernelInitArgs kernelInitArgs;
    MemoryMgrPrimitiveKern *memory = &kernelInitArgs.memory;
    uval vp = 0;	/* master processor */
    uval vaddr;

    /* on this machine like all x86 machines nowaydays the boot
     * image is loaded at 1MB.  This is hard coded here.  */
    extern code start_real;
    codeAddress kernPhysStartAddress = &start_real;
    extern code kernVirtStart;

    early_printk("kernPhysStartAddress 0x%lx \n",
		 (unsigned long)kernPhysStartAddress);


    /* We ignore memory below the 1meg boundary.  PhysSize is the
     * size of memory above the boundary.
     */
    uval physSize = BOOT_MINIMUM_REAL_MEMORY -0x100000;
    uval physStart = 0x0;
    uval physEnd = physStart + 0x100000 + physSize;

    early_printk("BOOT_MINIMUM_REAL_MEMORY 0x%lx, physStart 0x%lx,"
		 " physEnd 0x%lx, physSize 0x%lx \n",
		 BOOT_MINIMUM_REAL_MEMORY,  physStart, physEnd, physSize);

    /*
     * We want to map all of physical memory into a V->R region.  We choose a
     * base for the V->R region (virtBase) that makes the kernel land correctly
     * at its link origin, &kernVirtStart.  This link origin must wind up
     * mapped to the physical location at which the kernel was loaded
     * (kernPhysStartAddress).
     */
    uval virtBase = (uval) (&kernVirtStart - kernPhysStartAddress);
    early_printk("&kernVirtStart 0x%lx virtBase 0x%lx \n",
		 (unsigned long long)&kernVirtStart,
		 (unsigned long long)virtBase);

    /*
     * Memory from __end_bss
     * to the end of physical memory is available for allocation.
     * Correct first for the 2MB page mapping the kernel.
     */
    early_printk("__bss_end is 0x%lx physEnd is 0x%lx \n", __bss_end , physEnd);
    uval allocStart = ALIGN_UP(__bss_end, SEGMENT_SIZE);
    uval allocEnd = virtBase + physEnd;

    early_printk("allocStart is 0x%lx allocEnd is 0x%lx \n",
		 allocStart, allocEnd);
    memory->init(physStart, physEnd, virtBase, allocStart, allocEnd);

    /*
     * Remove mappings between allocStart and
     * BOOT_MINIMUM_REAL_MEMORY to allow 4KB page mapping for
     * that range.  No need to tlb invalidate, unless they are
     * touched (debugging).  Actually we need to keep the first
     * 2MB mapping above allocStart so that we can initialize the
     * first 2 (or 3 if we need a PDP page as well) 4KB pages
     * which are PDE and PTE pages for the V->R mapping before
     * they are themselves mapped as 4KB pages.
     */
    early_printk("top page real address is 0x%lx \n", (uval)&level4_pgt);
    uval level1_pgt_virt = memory->virtFromPhys((uval)&level4_pgt);
    early_printk("top page real address is 0x%lx \n", (uval)level4_pgt & ~0xfff);
    early_printk("top page virtual  address is 0x%lx \n", (uval )level1_pgt_virt);

    for (vaddr = allocStart + SEGMENT_SIZE; vaddr < allocEnd; vaddr += SEGMENT_SIZE)	{

#ifndef NDEBUG
      //     early_printk("removing pde, pml4 at virtual address 0x%lx \n", EARLY_VADDR_TO_L1_PTE_P(level1_pgt_virt, vaddr, memory));
      TOUCH(EARLY_VADDR_TO_L1_PTE_P(level1_pgt_virt, vaddr, memory));

      //     early_printk("removing pde, pdp at virtual address 0x%lx \n", EARLY_VADDR_TO_L2_PTE_P(level1_pgt_virt, vaddr, memory));
      TOUCH(EARLY_VADDR_TO_L2_PTE_P(level1_pgt_virt, vaddr, memory));

      //     early_printk("removing pde at virtual address 0x%lx \n", EARLY_VADDR_TO_L3_PTE_P(level1_pgt_virt, vaddr, memory));
      TOUCH(EARLY_VADDR_TO_L3_PTE_P(level1_pgt_virt, vaddr, memory));
#endif /* #ifndef NDEBUG */


      EARLY_VADDR_TO_L3_PTE_P(level1_pgt_virt, vaddr, memory)->P = 0;
      EARLY_VADDR_TO_L3_PTE_P(level1_pgt_virt, vaddr, memory)->PS = 0;
      EARLY_VADDR_TO_L3_PTE_P(level1_pgt_virt, vaddr, memory)->G = 0;
      EARLY_VADDR_TO_L3_PTE_P(level1_pgt_virt, vaddr, memory)->Frame = 0;
      __flush_tlb_one(vaddr);
    }

    /*
     * Because of the 2MB page mapping for the kernel no
     * unused space can be recuperated at a 4KB page granularity.
     * We may want to map the fringe bss with 4KB page(s)
     * or alternatively make free for (pinned only) 4KB allocation
     * the unused 4KB pages unused in the 2MB pages at this point. XXX dangerous
     */

    early_printk("Calling InitKernelMappings\n");
    InitKernelMappings(0, memory);

    // kernelInitArgs.onSim = onSim; not there anymore but where is it set XXX

    kernelInitArgs.vp = 0;
    kernelInitArgs.barrierP = 0;

#define LOOP_NUMBER 	0x000fffff	// iteration counter for delay
    init_PIC(LOOP_NUMBER);

    early_printk("Calling InitIdt\n");
    InitIdt();			// initialize int handlers

    early_printk("Calling enableHardwareInterrupts\n");
    enableHardwareInterrupts();

    early_printk("Calling thinwireInit\n");
    thinwireInit(memory);

    /* no thinwire console XXX taken from mips64 but check  */
    early_printk("Calling LocalConsole and switching to tty \n");
    LocalConsole::Init(vp, memory, CONSOLE_CHANNEL, 1, 0 );

    err_printf("Calling KernelInit.C\n");

    /* Remove the V=R initial mapping only used for jumping to
     * the final mapping, i.e the first 2MB. XXX todo should not
     * do it until VGABASE has been relocated currently mapped
     * V==R XXX cannot use early_printk() from now on.  */
    L3_PTE *p;
    p = EARLY_VADDR_TO_L3_PTE_P(level1_pgt_virt,(uval)0x100000,memory);
    p->P = 0;
    p->PS = 0;
    p->G = 0;
    p->Frame = 0;
    __flush_tlb_one(0x100000);

    KernelInit(kernelInitArgs);
    /* NOTREACHED */
}
Esempio n. 5
0
void
wisvc_CreateKublService (int argc, char **argv,
			 char *service_name, char *BinaryPathName,
			 int autostart, int start_now)
{
  int called_as_service = 0;	/* Needed by macro err_printf */
  SC_HANDLE schSCManager, schService;
  int stat;

  schSCManager = OpenSCManager (
				 NULL,	/* LPCTSTR  lpMachineName, address of machine name string */
				 NULL,	/* LPCTSTR  lpDatabaseName, address of database name string */
				 SC_MANAGER_ALL_ACCESS	/* DWORD dwDesiredAccess, type of access */
    );

  if (NULL == schSCManager)
    {
      DWORD erhe = GetLastError ();

      err_printf ((
       "%s: Installing \"%s\" (path: \"%s\") as Windows NT service failed. "
	"Could not open Services Database with OpenSCManager, errno=%ld.\n",
		    argv[0], service_name, BinaryPathName, erhe));
      exit (1);
    }

  schService = CreateService (
			       schSCManager,	/* SCManager database      */
			       TEXT (service_name),	/* name of service         */
			       service_name,	/* service name to display */
			       SERVICE_ALL_ACCESS,	/* desired access          */
			       SERVICE_WIN32_OWN_PROCESS,	/* service type            */
		    (autostart ? SERVICE_AUTO_START : SERVICE_DEMAND_START),	/* start type */
			       SERVICE_ERROR_NORMAL,	/* error control type      */
			       ((LPCSTR) BinaryPathName),	/* service's binary        */
			       NULL,	/* no load ordering group  */
			       NULL,	/* no tag identifier       */
			       NULL,	/* no dependencies         */
			       NULL,	/* LocalSystem account     */
			       NULL);	/* no password             */

  if (NULL == schService)
    {
      DWORD erhe = GetLastError ();

      if (ERROR_SERVICE_EXISTS == erhe)
	{
	  err_printf ((
			"%s: Cannot install service \"%s\" because a service with the same "
			"name already exists! (errno=%ld, path=\"%s\").\n",
			argv[0], service_name, erhe, BinaryPathName));
	}
      else if (ERROR_SERVICE_MARKED_FOR_DELETE == erhe)
	{
	  err_printf ((
			"%s: Cannot install service \"%s\" because a service with the same "
			"name still exists, although it has been marked for delete. Use ISQL to "
			"stop the old service with shutdown or raw_exit() before continuing "
			" (errno=%ld, path=\"%s\").\n",
			argv[0], service_name, erhe, BinaryPathName));
	}
      else
	{
	  err_printf ((
			"%s: Installing \"%s\" (path: \"%s\") as Windows NT service failed. "
			"CreateService returned NULL, errno=%ld.\n",
			argv[0], service_name, BinaryPathName, erhe));
	}
      exit (1);
    }

  err_printf (("%s: Service \"%s\" installed successfully.\n",
	       argv[0], service_name));

  if (start_now)
    {
      stat = wisvc_StartKublService (argc, argv, schService,
				     service_name, BinaryPathName, 1);

    }

  CloseServiceHandle (schService);

  exit (!stat);
}
Esempio n. 6
0
/* virtual */ SysStatusUval
FCMPrimitive<PL,ALLOC>::mapPage(uval offset, uval regionVaddr, uval regionSize,
				AccessMode::pageFaultInfo pfinfo, uval vaddr,
				AccessMode::mode access, HATRef hat, VPNum vp,
				RegionRef reg, uval firstAccessOnPP,
				PageFaultNotification */*fn*/)
{
    SysStatus rc;
    uval paddr;
    uval unneededFrameAddr=0;
    setPFBit(fcmPrimitive);
    ScopeTime timer(MapPageTimer);

    /*
     * we round vaddr down to a pageSize boundary.
     * thus, pageSize is the smallest pageSize this FCM supports.
     * for now, its the only size - but we may consider using multiple
     * page sizes in a single FCM in the future.
     * Note that caller can't round down since caller may not know
     * the FCM pageSize.
     */
    vaddr &= -this->pageSize;

    if (firstAccessOnPP) this->updateRegionPPSet(reg);

    this->lock.acquire();

    offset += vaddr - regionVaddr;

    //err_printf("FCMPrimitive::mapPage(o %lx, h %lx)\n", offset, hat);

    MLSStatistics::StartTimer(4);
    PageDesc *pg = this->findPage(offset);
    MLSStatistics::DoneTimer(4);
    if (!pg) {
	// allocate a new page
	uval virtAddr;
	this->lock.release();
	rc = DREF(this->pmRef)->allocPages(this->getRef(), virtAddr,
		this->pageSize, this->pageable);
	tassert(_SUCCESS(rc), err_printf("woops\n"));
	this->lock.acquire();
	if ((pg = this->findPage(offset)) != 0) {
	    // added in our absence
	    unneededFrameAddr = virtAddr;
	    paddr = pg->paddr;
	    TraceOSMemFCMPrimFoundPage(offset, paddr);
	} else {
	    paddr = PageAllocatorKernPinned::virtToReal(virtAddr);
	    TraceOSMemFCMPrimMapPage(vaddr, offset, paddr,
		      (uval64)this);
	    pg = this->addPage(offset, paddr, this->pageSize);
            pg->cacheSynced = PageDesc::SET;
	    DILMA_TRACE_PAGE_DIRTY(this,pg,1);
	    pg->dirty = PageDesc::SET;
	}
    } else {
	paddr = pg->paddr;
	TraceOSMemFCMPrimFound1Page(offset, paddr);
    }
    tassert(1, err_printf(" should use offset %ld\n", offset));

    MLSStatistics::StartTimer(5);
    rc = this->mapPageInHAT(vaddr, pfinfo, access, vp, hat, reg, pg, offset);
    MLSStatistics::DoneTimer(5);

    this->lock.release();

    /*
     * do the free not holding a lock for safety sake
     */
    if (unneededFrameAddr != 0) {
	DREF(this->pmRef)->deallocPages(this->getRef(), unneededFrameAddr,
		this->pageSize);
    }

    return rc;
}
Esempio n. 7
0
/*-------------------- coord_rmsd ------------------------------------------
 * Takes a pairset and two structures and moves coord1 on top of coord2 so 
 * that the RMSD is minimized. The superimposed structures are returned as
 * c1_new and c2_new. If sub_flag is set, the returned structures contain only
 * the subset of residues specified by the pairset.
 */
int
coord_rmsd(struct pair_set *const pairset, struct coord *source,
           struct coord *target, const int sub_flag, float *rmsd,
           struct coord **c1_new, struct coord **c2_new)
{
    float rmat[3][3];
    size_t tmp_idx = 0;
    size_t size, i;
    int r, a, b;
    struct RPoint translation1, translation2;
    int **pairs = pairset->indices;
    struct coord *temp_struct_1 =
        coord_template(source, coord_size(source));
    struct coord *temp_struct_2 =
        coord_template(target, coord_size(target));
    const char *this_sub = "coord_rmsd";
    /* Create temporary structures to hold the aligned parts of the two structures */
    temp_struct_1->seq = seq_copy(source->seq);
    temp_struct_2->seq = seq_copy(target->seq);
    coord_nm_2_a(temp_struct_1);
    coord_nm_2_a(temp_struct_2);
    if(sub_flag > 4){
                for (i = 0; i < pairset->n; i++) {
                   a = pairs[i][0];
                   b = pairs[i][1];
                   if (a != GAP_INDEX && b != GAP_INDEX) {
                           copy_coord_elem(temp_struct_1, source, tmp_idx, pairs[i][1]);
                           copy_coord_elem(temp_struct_2, target, tmp_idx, pairs[i][0]);
                           tmp_idx++;
                   }
                }
        }
        else{
                for (i = 0; i < pairset->n; i++) {
                    a = pairs[i][0];
                    b = pairs[i][1];
                    if (a != GAP_INDEX && b != GAP_INDEX) {
                            copy_coord_elem(temp_struct_1, source, tmp_idx, pairs[i][0]);
                            copy_coord_elem(temp_struct_2, target, tmp_idx, pairs[i][1]);
                            tmp_idx++;
                    }
                }
        }
    size = tmp_idx;
    coord_trim(temp_struct_1, size);
    coord_trim(temp_struct_2, size);
/* Determine the center of mass of the two structures and move the CoMs to the 
 * coordinate origin.
 */
    translation1 = calc_CM(size, temp_struct_1->rp_ca);
    translation2 = calc_CM(size, temp_struct_2->rp_ca);
    coord_trans(&translation1, temp_struct_1, size);
    coord_trans(&translation2, temp_struct_2, size);

/* Determine the rotation matrix and apply the rotation to structure 2.
 * Then calculate the RMSD
 */

    r = lsq_fit(tmp_idx, temp_struct_1->rp_ca, temp_struct_2->rp_ca,
                rmat);
    if (r == EXIT_FAILURE) {
            err_printf(this_sub, "lsq_fit fail\n");
            *rmsd = -1;
            goto escape;
    }
    apply_rot(rmat, temp_struct_1);
    *rmsd = calc_RMSD(size, temp_struct_1->rp_ca, temp_struct_2->rp_ca);

/* Move the structures' CoMs back to the original CoM of structure 2.*/
    translation2.x *= -1;
    translation2.y *= -1;
    translation2.z *= -1;
/* If only the aligned subset of the structures is needed, translate and
 *  return the temporary structures.
 */
    if (sub_flag%2) {
           coord_trans(&translation2, temp_struct_1, size);
           coord_trans(&translation2, temp_struct_2, size);
           *c1_new = temp_struct_1;
           *c2_new = temp_struct_2;
    }
/* Otherwise create a copy of the original structures, apply translation
 * and rotation to the copies and return those.
 */
    else {
           coord_destroy(temp_struct_1);
           coord_destroy(temp_struct_2);
           *c1_new = coord_template(source, coord_size(source));
           *c2_new = coord_template(target, coord_size(target));
           (*c1_new)->seq = seq_copy(source->seq);
           (*c2_new)->seq = seq_copy(target->seq);
           for (i = 0; i < coord_size(source); i++) {
               copy_coord_elem(*c1_new, source, i, i);
           }
           for (i = 0; i < coord_size(target); i++) {
               copy_coord_elem(*c2_new, target, i, i);
           }
           coord_trans(&translation1, *c1_new, (*c1_new)->size);
           apply_rot(rmat, *c1_new);
           coord_trans(&translation2, *c1_new, (*c1_new)->size);
    }

    return (EXIT_SUCCESS);
  escape:
    return (EXIT_FAILURE);
}
Esempio n. 8
0
void exec_wait()
{
    int finished = 0;

    /* Process children that signaled. */
    while ( !finished )
    {
        int i;
        struct timeval tv;
        struct timeval * ptv = NULL;
        int select_timeout = globs.timeout;

        /* Check for timeouts:
         *   - kill children that already timed out
         *   - decide how long until the next one times out
         */
        if ( globs.timeout > 0 )
        {
            struct tms buf;
            clock_t const current = times( &buf );
            for ( i = 0; i < globs.jobs; ++i )
                if ( cmdtab[ i ].pid )
                {
                    clock_t const consumed =
                        ( current - cmdtab[ i ].start_time ) / tps;
                    if ( consumed >= globs.timeout )
                    {
                        killpg( cmdtab[ i ].pid, SIGKILL );
                        cmdtab[ i ].exit_reason = EXIT_TIMEOUT;
                    }
                    else if ( globs.timeout - consumed < select_timeout )
                        select_timeout = globs.timeout - consumed;
                }

            /* If nothing else causes our select() call to exit, force it after
             * however long it takes for the next one of our child processes to
             * crossed its alloted processing time so we can terminate it.
             */
            tv.tv_sec = select_timeout;
            tv.tv_usec = 0;
            ptv = &tv;
        }

        /* select() will wait for I/O on a descriptor, a signal, or timeout. */
        {
            /* disable child termination signals while in select */
            int ret;
            sigset_t sigmask;
            sigemptyset(&sigmask);
            sigaddset(&sigmask, SIGCHLD);
            sigprocmask(SIG_BLOCK, &sigmask, NULL);
            while ( ( ret = poll( wait_fds, WAIT_FDS_SIZE, select_timeout * 1000 ) ) == -1 )
                if ( errno != EINTR )
                    break;
            /* restore original signal mask by unblocking sigchld */
            sigprocmask(SIG_UNBLOCK, &sigmask, NULL);
            if ( ret <= 0 )
                continue;
        }

        for ( i = 0; i < globs.jobs; ++i )
        {
            int out_done = 0;
            int err_done = 0;
            if ( GET_WAIT_FD( i )[ OUT ].revents )
                out_done = read_descriptor( i, OUT );

            if ( globs.pipe_action && ( GET_WAIT_FD( i )[ ERR ].revents ) )
                err_done = read_descriptor( i, ERR );

            /* If feof on either descriptor, we are done. */
            if ( out_done || err_done )
            {
                int pid;
                int status;
                int rstat;
                timing_info time_info;
                struct rusage cmd_usage;

                /* We found a terminated child process - our search is done. */
                finished = 1;

                /* Close the stream and pipe descriptors. */
                close_streams( i, OUT );
                if ( globs.pipe_action )
                    close_streams( i, ERR );

                /* Reap the child and release resources. */
                while ( ( pid = wait4( cmdtab[ i ].pid, &status, 0, &cmd_usage ) ) == -1 )
                    if ( errno != EINTR )
                        break;
                if ( pid != cmdtab[ i ].pid )
                {
                    err_printf( "unknown pid %d with errno = %d\n", pid, errno );
                    exit( EXITBAD );
                }

                /* Set reason for exit if not timed out. */
                if ( WIFEXITED( status ) )
                    cmdtab[ i ].exit_reason = WEXITSTATUS( status )
                        ? EXIT_FAIL
                        : EXIT_OK;

                {
                    time_info.system = ((double)(cmd_usage.ru_stime.tv_sec)*1000000.0+(double)(cmd_usage.ru_stime.tv_usec))/1000000.0;
                    time_info.user   = ((double)(cmd_usage.ru_utime.tv_sec)*1000000.0+(double)(cmd_usage.ru_utime.tv_usec))/1000000.0;
                    timestamp_copy( &time_info.start, &cmdtab[ i ].start_dt );
                    timestamp_current( &time_info.end );
                }

                /* Drive the completion. */
                if ( interrupted() )
                    rstat = EXEC_CMD_INTR;
                else if ( status )
                    rstat = EXEC_CMD_FAIL;
                else
                    rstat = EXEC_CMD_OK;

                /* Call the callback, may call back to jam rule land. */
                (*cmdtab[ i ].func)( cmdtab[ i ].closure, rstat, &time_info,
                    cmdtab[ i ].buffer[ OUT ], cmdtab[ i ].buffer[ ERR ],
                    cmdtab[ i ].exit_reason );

                /* Clean up the command's running commands table slot. */
                BJAM_FREE( cmdtab[ i ].buffer[ OUT ] );
                cmdtab[ i ].buffer[ OUT ] = 0;
                cmdtab[ i ].buf_size[ OUT ] = 0;

                BJAM_FREE( cmdtab[ i ].buffer[ ERR ] );
                cmdtab[ i ].buffer[ ERR ] = 0;
                cmdtab[ i ].buf_size[ ERR ] = 0;

                cmdtab[ i ].pid = 0;
                cmdtab[ i ].func = 0;
                cmdtab[ i ].closure = 0;
                cmdtab[ i ].start_time = 0;
            }
        }
    }
}
Esempio n. 9
0
void RunWorkerThread()
{
    DWORD dwKey, nBytes;
    OVERLAPPED *p_Ovl;
    int error;
    MPD_Context *pContext;
    int ret_val;

    while (true)
    {
        if (GetQueuedCompletionStatus(g_hCommPort, &nBytes, &dwKey, &p_Ovl, INFINITE))
        {
            //dbg_printf("RunWorkerThread::%d bytes\n", nBytes);
            if (dwKey == EXIT_WORKER_KEY)
                ExitThread(0);
            pContext = (MPD_Context*)dwKey;
            if (nBytes)
            {
                if (nBytes == 1)
                {
                    pContext->bReadPosted = false;
                    if (!RunRead(pContext, &ret_val))
                        ErrorExit("RunRead returned FALSE", ret_val);

                    if (pContext->bDeleteMe)
                    {
                        RemoveContext(pContext);
                        pContext = NULL;
                    }
                    else
                    {
                        // post the next read
                        error = PostContextRead(pContext);
                        if (error)
                        {
                            if (error == ERROR_NETNAME_DELETED || error == ERROR_IO_PENDING || error == WSAECONNABORTED)
                                dbg_printf("RunWorkerThread:Post read for %s(%d) failed, error %d\n", ContextTypeToString(pContext), pContext->sock, error);
                            else
                                err_printf("RunWorkerThread:Post read for %s(%d) failed, error %d\n", ContextTypeToString(pContext), pContext->sock, error);
                            RemoveContext(pContext);
                            pContext = NULL;
                        }
                    }
                }
                else
                {
                    dbg_printf("RunWorkerThread: nBytes = %d, *** unexpected ***\n", nBytes);
                    error = PostContextRead(pContext);
                    if (error)
                    {
                        err_printf("RunWorkerThread:Post read for %s(%d) failed, error %d\n", ContextTypeToString(pContext), pContext->sock, error);
                        RemoveContext(pContext);
                        pContext = NULL;
                    }
                }
            }
            else
            {
                dbg_printf("RunWorkerThread::closing context %s(%d)\n", ContextTypeToString(pContext), pContext->sock);
                RemoveContext(pContext);
                pContext = NULL;
            }
        }
        else
        {
            error = GetLastError();
            if (error == ERROR_NETNAME_DELETED || error == ERROR_IO_PENDING || error == WSAECONNABORTED)
            {
                dbg_printf("RunWorkerThread: GetQueuedCompletionStatus failed, error %d\n", error);
            }
            else
            {
                err_printf("RunWorkerThread: GetQueuedCompletionStatus failed, error %d\n", error);
            }
            //return;
        }
    }
}
Esempio n. 10
0
/*
 * writeBlock()
 *
 *   Writes the logical block specified to the disk. This operation is
 *   the only difference between PSOBasicRW and PSOPreallocExtent.
 */
sval
PSOPreallocExtent::writeBlock(uval32 lblkno, char *buffer, uval local)
{
    sval rc;
    uval32 dblkno;

    // lock this PSO
    lock.acquire();

    if (lblkno < RW_MAXBLK) {
	dblkno = dblk[lblkno];

        // If there isn't a block already there, allocate one
        if (dblkno == 0) {
	    uval32 extentLen = 1;

	    // Here is where we do extent allocation!
	    // First, try to see how many blocks we can sequentially allocate
	    while (extentLen < EXTENT_SIZE 
		   && lblkno + extentLen < RW_MAXBLK 
		   && !dblk[lblkno + extentLen]) {
		extentLen++;
	    }

	    KFS_DPRINTF(DebugMask::PSO_REALLOC_EXTENT,
			"PSOPreallocExtent::writeBlock() trying to allocate "
			"%u blocks\n", extentLen);
            rc = dblkno = globals->super->allocExtent(extentLen);
	    KFS_DPRINTF(DebugMask::PSO_REALLOC_EXTENT,
			"PSOPreallocExtent::writeBlock() successfully "
			"allocated %u blocks\n", extentLen);
	    
	    if (_FAILURE(rc)) {
		tassertMsg(0, "PSOPreallocExtent::writeBlock() failed to "
			   "alloc extent\n");
		lock.release();
		return rc;
	    }
	    for (uval i = 0; i < extentLen; i++) {
		dblk[lblkno + i] = dblkno + i;
	    }

            locked_markDirty(lblkno);
        }

        KFS_DPRINTF(DebugMask::PSO_REALLOC_EXTENT_RW,
		    "PSOPreallocExtent::writeBlock: writing block %u %u\n",
                    dblkno, lblkno);
	passertMsg(dblkno, "PSOPreallocExtent::writeBlock() bad disk block "
		   "for writing d=%u, l=%u, this=0x%p\n",
		   dblkno, lblkno, this);

        // FIXME: change disk routines to handle correct token
	rc = llpso->writeBlock(dblkno, buffer, local);

        lock.release();
        return rc;
    }

    /* pass on to sub-object */
    KFS_DPRINTF(DebugMask::PSO_REALLOC_EXTENT_RW,
		"PSOPreallocExtent::write_page: forwarding subobj\n");

    if (subPSO == NULL) {
        // need to get a new PSO to extend the file! Since allocRecord writes
	// the entry to subObjID it will be written out to the data buffer,
	// because subObjID is a pointer to the correct place in the data buffer
	rc = getRecordMap()->allocRecord(OT_BASIC_EXTENT, subObjID);
	if (_FAILURE(rc)) {
	    err_printf("PSOPreallocExtent::writeBlock() problem creating ORSMap"
		       " entry\n");
	    return rc;
	}

	// We have to make sure the subObjID goes to disk. It'll hopefully get
	// correctly flushed later. Warning: lockedMarkDirty() won't work here.
        flags |= PSO_BASICRW_DIRTY;

        subPSO = (PSOBase *)recordMap->getObj(subObjID);
        if (subPSO == NULL) {
	    tassertMsg(0, "?");
            // this is a problem...
            lock.release();
            return -1;
        }
    }
    rc = subPSO->writeBlock(lblkno - RW_MAXBLK, buffer, local);

    lock.release();
    return rc;
}
Esempio n. 11
0
static int          /* 0 failure, 1 success */
regmatch( char * prog )
{
    char * scan;  /* Current node. */
    char * next;  /* Next node. */

    scan = prog;
#ifdef DEBUG
    if (scan != NULL && regnarrate)
        err_printf("%s(\n", regprop(scan));
#endif
    while (scan != NULL) {
#ifdef DEBUG
        if (regnarrate)
            err_printf("%s...\n", regprop(scan));
#endif
        next = regnext(scan);

        switch (OP(scan)) {
        case BOL:
            if (reginput != regbol)
                return(0);
            break;
        case EOL:
            if (*reginput != '\0')
                return(0);
            break;
        case WORDA:
            /* Must be looking at a letter, digit, or _ */
            if ((!isalnum(*reginput)) && *reginput != '_')
                return(0);
            /* Prev must be BOL or nonword */
            if (reginput > regbol &&
                (isalnum(reginput[-1]) || reginput[-1] == '_'))
                return(0);
            break;
        case WORDZ:
            /* Must be looking at non letter, digit, or _ */
            if (isalnum(*reginput) || *reginput == '_')
                return(0);
            /* We don't care what the previous char was */
            break;
        case ANY:
            if (*reginput == '\0')
                return(0);
            reginput++;
            break;
        case EXACTLY: {
                register int len;
                register char *opnd;

                opnd = OPERAND(scan);
                /* Inline the first character, for speed. */
                if (*opnd != *reginput)
                    return(0);
                len = strlen(opnd);
                if (len > 1 && strncmp(opnd, reginput, len) != 0)
                    return(0);
                reginput += len;
            }
            break;
        case ANYOF:
            if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL)
                return(0);
            reginput++;
            break;
        case ANYBUT:
            if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL)
                return(0);
            reginput++;
            break;
        case NOTHING:
            break;
        case BACK:
            break;
        case OPEN+1:
        case OPEN+2:
        case OPEN+3:
        case OPEN+4:
        case OPEN+5:
        case OPEN+6:
        case OPEN+7:
        case OPEN+8:
        case OPEN+9: {
                register int no;
                register const char *save;

                no = OP(scan) - OPEN;
                save = reginput;

                if (regmatch(next)) {
                    /*
                     * Don't set startp if some later
                     * invocation of the same parentheses
                     * already has.
                     */
                    if (regstartp[no] == NULL)
                        regstartp[no] = save;
                    return(1);
                } else
                    return(0);
            }
            break;
        case CLOSE+1:
        case CLOSE+2:
        case CLOSE+3:
        case CLOSE+4:
        case CLOSE+5:
        case CLOSE+6:
        case CLOSE+7:
        case CLOSE+8:
        case CLOSE+9: {
                register int no;
                register const char *save;

                no = OP(scan) - CLOSE;
                save = reginput;

                if (regmatch(next)) {
                    /*
                     * Don't set endp if some later
                     * invocation of the same parentheses
                     * already has.
                     */
                    if (regendp[no] == NULL)
                        regendp[no] = save;
                    return(1);
                } else
                    return(0);
            }
            break;
        case BRANCH: {
                register const char *save;

                if (OP(next) != BRANCH)     /* No choice. */
                    next = OPERAND(scan);   /* Avoid recursion. */
                else {
                    do {
                        save = reginput;
                        if (regmatch(OPERAND(scan)))
                            return(1);
                        reginput = save;
                        scan = regnext(scan);
                    } while (scan != NULL && OP(scan) == BRANCH);
                    return(0);
                    /* NOTREACHED */
                }
            }
            break;
        case STAR:
        case PLUS: {
                register char nextch;
                register int no;
                register const char *save;
                register int min;

                /*
                 * Lookahead to avoid useless match attempts
                 * when we know what character comes next.
                 */
                nextch = '\0';
                if (OP(next) == EXACTLY)
                    nextch = *OPERAND(next);
                min = (OP(scan) == STAR) ? 0 : 1;
                save = reginput;
                no = regrepeat(OPERAND(scan));
                while (no >= min) {
                    /* If it could work, try it. */
                    if (nextch == '\0' || *reginput == nextch)
                        if (regmatch(next))
                            return(1);
                    /* Couldn't or didn't -- back up. */
                    no--;
                    reginput = save + no;
                }
                return(0);
            }
            break;
        case END:
            return(1);  /* Success! */
            break;
        default:
            regerror("memory corruption");
            return(0);
            break;
        }

        scan = next;
    }

    /*
     * We get here only if there's trouble -- normally "case END" is
     * the terminating point.
     */
    regerror("corrupted pointers");
    return(0);
}
Esempio n. 12
0
int i915_error_state_to_str(struct drm_i915_error_state_buf *m,
			    const struct i915_error_state_file_priv *error_priv)
{
	struct drm_device *dev = error_priv->dev;
	drm_i915_private_t *dev_priv = dev->dev_private;
	struct drm_i915_error_state *error = error_priv->error;
	struct intel_ring_buffer *ring;
	int i, j, page, offset, elt;

	if (!error) {
		err_printf(m, "no error state collected\n");
		goto out;
	}

	err_printf(m, "Time: %ld s %ld us\n", error->time.tv_sec,
		   error->time.tv_usec);
	err_printf(m, "Kernel: " UTS_RELEASE "\n");
	err_printf(m, "PCI ID: 0x%04x\n", dev->pdev->device);
	err_printf(m, "EIR: 0x%08x\n", error->eir);
	err_printf(m, "IER: 0x%08x\n", error->ier);
	err_printf(m, "PGTBL_ER: 0x%08x\n", error->pgtbl_er);
	err_printf(m, "FORCEWAKE: 0x%08x\n", error->forcewake);
	err_printf(m, "DERRMR: 0x%08x\n", error->derrmr);
	err_printf(m, "CCID: 0x%08x\n", error->ccid);
	err_printf(m, "Missed interrupts: 0x%08lx\n", dev_priv->gpu_error.missed_irq_rings);

	for (i = 0; i < dev_priv->num_fence_regs; i++)
		err_printf(m, "  fence[%d] = %08llx\n", i, error->fence[i]);

	for (i = 0; i < ARRAY_SIZE(error->extra_instdone); i++)
		err_printf(m, "  INSTDONE_%d: 0x%08x\n", i,
			   error->extra_instdone[i]);

	if (INTEL_INFO(dev)->gen >= 6) {
		err_printf(m, "ERROR: 0x%08x\n", error->error);
		err_printf(m, "DONE_REG: 0x%08x\n", error->done_reg);
	}

	if (INTEL_INFO(dev)->gen == 7)
		err_printf(m, "ERR_INT: 0x%08x\n", error->err_int);

	for_each_ring(ring, dev_priv, i)
		i915_ring_error_state(m, dev, error, i);

	if (error->active_bo)
		print_error_buffers(m, "Active",
				    error->active_bo[0],
				    error->active_bo_count[0]);

	if (error->pinned_bo)
		print_error_buffers(m, "Pinned",
				    error->pinned_bo[0],
				    error->pinned_bo_count[0]);

	for (i = 0; i < ARRAY_SIZE(error->ring); i++) {
		struct drm_i915_error_object *obj;

		if ((obj = error->ring[i].batchbuffer)) {
			err_printf(m, "%s --- gtt_offset = 0x%08x\n",
				   dev_priv->ring[i].name,
				   obj->gtt_offset);
			offset = 0;
			for (page = 0; page < obj->page_count; page++) {
				for (elt = 0; elt < PAGE_SIZE/4; elt++) {
					err_printf(m, "%08x :  %08x\n", offset,
						   obj->pages[page][elt]);
					offset += 4;
				}
			}
		}

		if (error->ring[i].num_requests) {
			err_printf(m, "%s --- %d requests\n",
				   dev_priv->ring[i].name,
				   error->ring[i].num_requests);
			for (j = 0; j < error->ring[i].num_requests; j++) {
				err_printf(m, "  seqno 0x%08x, emitted %ld, tail 0x%08x\n",
					   error->ring[i].requests[j].seqno,
					   error->ring[i].requests[j].jiffies,
					   error->ring[i].requests[j].tail);
			}
		}

		if ((obj = error->ring[i].ringbuffer)) {
			err_printf(m, "%s --- ringbuffer = 0x%08x\n",
				   dev_priv->ring[i].name,
				   obj->gtt_offset);
			offset = 0;
			for (page = 0; page < obj->page_count; page++) {
				for (elt = 0; elt < PAGE_SIZE/4; elt++) {
					err_printf(m, "%08x :  %08x\n",
						   offset,
						   obj->pages[page][elt]);
					offset += 4;
				}
			}
		}

		obj = error->ring[i].ctx;
		if (obj) {
			err_printf(m, "%s --- HW Context = 0x%08x\n",
				   dev_priv->ring[i].name,
				   obj->gtt_offset);
			offset = 0;
			for (elt = 0; elt < PAGE_SIZE/16; elt += 4) {
				err_printf(m, "[%04x] %08x %08x %08x %08x\n",
					   offset,
					   obj->pages[0][elt],
					   obj->pages[0][elt+1],
					   obj->pages[0][elt+2],
					   obj->pages[0][elt+3]);
					offset += 16;
			}
		}
	}

	if (error->overlay)
		intel_overlay_print_error_state(m, error->overlay);

	if (error->display)
		intel_display_print_error_state(m, dev, error->display);

out:
	if (m->bytes == 0 && m->err)
		return m->err;

	return 0;
}
Esempio n. 13
0
static void i915_ring_error_state(struct drm_i915_error_state_buf *m,
				  struct drm_device *dev,
				  struct drm_i915_error_state *error,
				  unsigned ring)
{
	BUG_ON(ring >= I915_NUM_RINGS); /* shut up confused gcc */
	err_printf(m, "%s command stream:\n", ring_str(ring));
	err_printf(m, "  HEAD: 0x%08x\n", error->head[ring]);
	err_printf(m, "  TAIL: 0x%08x\n", error->tail[ring]);
	err_printf(m, "  CTL: 0x%08x\n", error->ctl[ring]);
	err_printf(m, "  ACTHD: 0x%08x\n", error->acthd[ring]);
	err_printf(m, "  IPEIR: 0x%08x\n", error->ipeir[ring]);
	err_printf(m, "  IPEHR: 0x%08x\n", error->ipehr[ring]);
	err_printf(m, "  INSTDONE: 0x%08x\n", error->instdone[ring]);
	if (ring == RCS && INTEL_INFO(dev)->gen >= 4)
		err_printf(m, "  BBADDR: 0x%08llx\n", error->bbaddr);

	if (INTEL_INFO(dev)->gen >= 4)
		err_printf(m, "  INSTPS: 0x%08x\n", error->instps[ring]);
	err_printf(m, "  INSTPM: 0x%08x\n", error->instpm[ring]);
	err_printf(m, "  FADDR: 0x%08x\n", error->faddr[ring]);
	if (INTEL_INFO(dev)->gen >= 6) {
		err_printf(m, "  RC PSMI: 0x%08x\n", error->rc_psmi[ring]);
		err_printf(m, "  FAULT_REG: 0x%08x\n", error->fault_reg[ring]);
		err_printf(m, "  SYNC_0: 0x%08x [last synced 0x%08x]\n",
			   error->semaphore_mboxes[ring][0],
			   error->semaphore_seqno[ring][0]);
		err_printf(m, "  SYNC_1: 0x%08x [last synced 0x%08x]\n",
			   error->semaphore_mboxes[ring][1],
			   error->semaphore_seqno[ring][1]);
		if (HAS_VEBOX(dev)) {
			err_printf(m, "  SYNC_2: 0x%08x [last synced 0x%08x]\n",
				   error->semaphore_mboxes[ring][2],
				   error->semaphore_seqno[ring][2]);
		}
	}
	err_printf(m, "  seqno: 0x%08x\n", error->seqno[ring]);
	err_printf(m, "  waiting: %s\n", yesno(error->waiting[ring]));
	err_printf(m, "  ring->head: 0x%08x\n", error->cpu_ring_head[ring]);
	err_printf(m, "  ring->tail: 0x%08x\n", error->cpu_ring_tail[ring]);
	err_printf(m, "  hangcheck: %s [%d]\n",
		   hangcheck_action_to_str(error->hangcheck_action[ring]),
		   error->hangcheck_score[ring]);
}
Esempio n. 14
0
/*
 * convert a 64 bit glibc stat struct, produced by k42, into a linux
 * 32 bit stat structure, as used by the 64 bit linux kernel for a 32
 * bit system call.  
 *
 *     kstat <-- gstat
 */
void _convert_gstat2kstat32(struct compat_stat *kstat, struct _gstat64 *gstat)
{
    kstat->st_dev	= gstat->st_dev;
    kstat->st_ino	= gstat->st_ino;
    kstat->st_mode	= gstat->st_mode;
    kstat->st_nlink	= gstat->st_nlink;
    kstat->st_uid	= gstat->st_uid;
    kstat->st_gid	= gstat->st_gid;
    kstat->st_rdev	= gstat->st_rdev;
    kstat->st_size	= gstat->st_size;
    kstat->st_blksize	= gstat->st_blksize;
    kstat->st_blocks	= gstat->st_blocks;
    kstat->st_atime	= gstat->st_atim.tv_sec;
    kstat->st_atime_nsec= gstat->st_atim.tv_nsec;
    kstat->st_mtime	= gstat->st_mtim.tv_sec;
    kstat->st_mtime_nsec= gstat->st_mtim.tv_nsec;
    kstat->st_ctime	= gstat->st_ctim.tv_sec;
    kstat->st_ctime_nsec= gstat->st_ctim.tv_nsec;
    kstat->__unused4	= 0;
    kstat->__unused5	= 0;

    #if 0
    int verbose = 1;
    if (verbose)
    {
	unsigned int i;
	err_printf("struct _gstat64 (glibc version size=%ld):",
		sizeof(struct _gstat64));
	for ( i = 0; i < sizeof (struct _gstat64); i += 4)
	    err_printf("%c%08x",
	    	i%(8*4)==0 ? '\n' : ' ',
	    	*(unsigned int *) ( (long)gstat + i));
	err_printf("\nstruct kstat (linux 32 version size=%ld):",
		sizeof(struct compat_stat));
	for ( i = 0; i < sizeof (struct compat_stat); i += 4)
	    err_printf("%c%08x",
	    	i%(8*4)==0 ? '\n' : ' ',
	    	*(unsigned int *) ( (long)kstat + i));

	err_printf("\nsizeof ndev %ld offset %d\n",
                sizeof (kstat->st_dev),
                (int) ( (uval) &(kstat->st_dev) - (uval) kstat));
	err_printf("\nsizeof ino %ld offset %d\n",
                sizeof (kstat->st_ino),
                (int) ( (uval) &(kstat->st_ino) - (uval) kstat));
	err_printf( "\nsizeof nlink %ld offset %d\n",
                sizeof (kstat->st_nlink),
                (int) ( (uval) &(kstat->st_nlink) - (uval) kstat));
	err_printf( "\nsizeof mode %ld offset %d\n",
                sizeof (kstat->st_mode),
                (int) ( (uval) &(kstat->st_mode) - (uval) kstat));
	err_printf( "\nsizeof uid %ld offset %d\n",
                sizeof (kstat->st_uid),
                (int) ( (uval) &(kstat->st_uid) - (uval) kstat));
	err_printf( "\nsizeof gid %ld offset %d\n",
                sizeof (kstat->st_gid),
                (int) ( (uval) &(kstat->st_gid) - (uval) kstat));
	err_printf( "\nsizeof rdev %ld offset %d\n",
                sizeof (kstat->st_rdev),
                (int) ( (uval) &(kstat->st_rdev) - (uval) kstat));
	err_printf( "\nsizeof size %ld offset %d\n",
                sizeof (kstat->st_size),
                (int) ( (uval) &(kstat->st_size) - (uval) kstat));
	err_printf( "\nsizeof blksize %ld offset %d\n",
                sizeof (kstat->st_blksize),
                (int) ( (uval) &(kstat->st_blksize) - (uval) kstat));
	err_printf( "\nsizeof blocks %ld offset %d\n",
                sizeof (kstat->st_blocks),
                (int) ( (uval) &(kstat->st_blocks) - (uval) kstat));
	err_printf( "\nsizeof atime %ld offset %d\n",
                sizeof (kstat->st_atime),
                (int) ( (uval) &(kstat->st_atime) - (uval) kstat));

	err_printf("\ndev=%ud\tino=%d\tnlink=%d\tmode=%x\n",
		kstat->st_dev, kstat->st_ino, kstat->st_nlink, kstat->st_mode);
	err_printf("uid=%d\tgid=%d\tsize=%ud\n",
		kstat->st_uid, kstat->st_gid, kstat->st_size);
	err_printf("blksize=%d\tblocks=%d\tatime=%d\tmtime=%d\n",
		kstat->st_blksize, kstat->st_blocks, kstat->st_atime,
		kstat->st_mtime);
    }
    #endif
}
Esempio n. 15
0
int main(int argc, char **argv){

	Buffer *ptr_Buffer;   /* pointer to Buffer structure */
	FILE *fi;             /* input file handle */
	int loadsize = 0;     /*the size of the file loaded in the buffer */
	int ansi_c = !ANSI_C; /* ANSI C compliancy flag */

	/* Check if the compiler option is set to compile ANSI C */
	/* __DATE__, __TIME__, __LINE__, __FILE__, __STDC__ are predefined preprocessor macros*/
	if (ansi_c){
		err_printf("Date: %s  Time: %s", __DATE__, __TIME__);
		err_printf("ERROR: Compiler is not ANSI C compliant!\n");
		exit(1);
	}

	/* missing file name or/and mode parameter */
	if (argc <= 2){

		err_printf("\nDate: %s  Time: %s", __DATE__, __TIME__);
		err_printf("\nRuntime error at line %d in file %s\n", __LINE__, __FILE__);
		err_printf("%s\b\b\b\b%s%s", argv[0], ": ", "Missing parameters.");
		err_printf("Usage: platybt source_file_name mode");
		exit(1);
	}

	/* create a source code input buffer */
	switch (*argv[2]){ /*gets the first caracter of the mode argument*/
	case 'f': case 'a': case 'm': break;
	default:
		err_printf("%s%s%s", argv[0], ": ", "Wrong mode parameter.");
		exit(1);
	}
	/*create the input buffer */
	ptr_Buffer = b_create(INIT_CAPACITY, INC_FACTOR, *argv[2]);
	if (ptr_Buffer == NULL){
		err_printf("%s%s%s", argv[0], ": ", "Could not create buffer.");
		exit(1);
	}

	/* open the source file */
	if ((fi = fopen(argv[1], "r")) == NULL){
		err_printf("%s%s%s%s", argv[0], ": ", "Cannot open file: ", argv[1]);
		exit(1);
	}

	/* load a source file into the input buffer  */
	printf("Reading file %s ....Please wait\n", argv[1]);
	loadsize = b_load(fi, ptr_Buffer);
	if (loadsize == R_FAIL_1)
		err_printf("%s%s%s", argv[0], ": ", "Error in loading buffer.");

	/* close the source file */
	fclose(fi);
	/*find the size of the file  */
	if (loadsize == LOAD_FAIL){
		printf("The input file %s %s\n", argv[1], "is not completely loaded.");
		printf("Input file size: %ld\n", get_filesize(argv[1]));
	}
	/* set a mark at the last char in the buffer*/
	b_setmark(ptr_Buffer, b_size(ptr_Buffer));

	/* display the contents of the input buffer */
	display(ptr_Buffer);

	/* pack the buffer
	* if possible, add end-of-file character (EOF) to the buffer
	* display again
	*/
	if (b_pack(ptr_Buffer)){
		if (!b_addc(ptr_Buffer, EOF))
			err_printf("%s%s%s", argv[0], ": ", "Error in writing to buffer.");
		display(ptr_Buffer);
	}


	/* destroy the buffer */
	b_destroy(ptr_Buffer);
	/* make the buffer invalid
	It is not necessary here because the function terminates anyway,
	but will prevent run-time errors and crashes in future expansions
	*/
	ptr_Buffer = NULL;
	/*return success */
	return (0);
}
Esempio n. 16
0
// Mount disk/filesystem
static void
do_mount(int argc, char *argv[])
{
    char *dev_str = "<undefined>", *type_str, *mp_str;
    bool dev_set = false, type_set = false;
    struct option_info opts[3];
    int err, num_opts = 2;
    int i,m=0; /* Set to 0 to silence warning */
#ifdef CYGPKG_IO_FLASH_BLOCK_DEVICE_LEGACY
    char *part_str;
    bool part_set = false;
#endif

    init_opts(&opts[0], 'd', true, OPTION_ARG_TYPE_STR,
              (void *)&dev_str, &dev_set, "device");
    init_opts(&opts[1], 't', true, OPTION_ARG_TYPE_STR,
              (void *)&type_str, &type_set, "fstype");
#ifdef CYGPKG_IO_FLASH_BLOCK_DEVICE_LEGACY
    init_opts(&opts[2], 'f', true, OPTION_ARG_TYPE_STR,
              (void *)&part_str, &part_set, "partition");
    num_opts++;
#endif

    CYG_ASSERT(num_opts <= NUM_ELEMS(opts), "Too many options");

    if (!scan_opts(argc, argv, 1, opts, num_opts, &mp_str, OPTION_ARG_TYPE_STR, "mountpoint"))
        return;

    if (!type_set) {
        err_printf("fs mount: Must specify file system type\n");
        return;
    }

    if( mp_str == 0 )
        mp_str = "/";

    if( mount_count >= MAX_MOUNTS )
    {
        err_printf("fs mount: Maximum number of mounts exceeded\n");
        return;
    }
    
#ifdef CYGPKG_IO_FLASH_BLOCK_DEVICE_LEGACY
    if (part_set) {
        int len;
        cyg_io_handle_t h;

        if (dev_set && strcmp(dev_str, CYGDAT_IO_FLASH_BLOCK_DEVICE_NAME_1)) {
            err_printf("fs mount: May only set one of <device> or <partition>\n");
            return;
        }

        dev_str = CYGDAT_IO_FLASH_BLOCK_DEVICE_NAME_1;
        len = strlen(part_str);

        err = cyg_io_lookup(dev_str, &h);
        if (err < 0) {
            err_printf("fs mount: cyg_io_lookup of \"%s\" returned %d\n", err);
            return;
        }
        err = cyg_io_set_config(h, CYG_IO_SET_CONFIG_FLASH_FIS_NAME,
                                part_str, &len);
        if (err < 0) {
            diag_printf("fs mount: FIS partition \"%s\" not found\n",
                        part_str);
            return;
        }
    }
#endif

    for( i = 0; i < MAX_MOUNTS; i++ )
    {
        if( mounts[i].mp_str[0] != '\0' )
        {
            if( strcmp(mounts[i].dev_str, dev_str ) == 0 )
            {
                err_printf("fs mount: Device %s already mounted\n",dev_str);
                return;
            }
        }
        else
            m = i;
    }

    strcpy( mounts[m].mp_str, mp_str );
    strcpy( mounts[m].dev_str, dev_str );
    strcpy( mounts[m].type_str, type_str );
    
    err = mount(mounts[m].dev_str, mounts[m].mp_str, mounts[m].type_str);

    if (err)
    {
        err_printf("fs mount: mount(%s,%s,%s) failed %d\n", dev_str, mp_str, type_str, errno);
        mounts[m].mp_str[0] = '\0'; // mount failed so don't let it appear mounted
    }
    else
    {
        if( mount_count == 0 )
            chdir( "/" );
        mount_count++;
    }
}
Esempio n. 17
0
// Assign visibility to a dummy vertex representing all the possible pins
// for this pinClassId.
void ConnEnd::assignPinVisibilityTo(VertInf *dummyConnectionVert,
                                    VertInf *targetVert)
{
    unsigned int validPinCount = 0;

    COLA_ASSERT(m_anchor_obj);
    COLA_ASSERT(m_connection_pin_class_id != CONNECTIONPIN_UNSET);

    Router *router = m_anchor_obj->router();
    for (ShapeConnectionPinSet::iterator curr =
                m_anchor_obj->m_connection_pins.begin();
            curr != m_anchor_obj->m_connection_pins.end(); ++curr)
    {
        ShapeConnectionPin *currPin = *curr;
        if ((currPin->m_class_id == m_connection_pin_class_id) &&
                (!currPin->m_exclusive || currPin->m_connend_users.empty()))
        {
            double routingCost = currPin->m_connection_cost;
            Point adjTargetPt = targetVert->point - currPin->m_vertex->point;
            double angle = rotationalAngle(adjTargetPt);
            bool inVisibilityRange = false;

            if (angle <= 45 || angle >= 315)
            {
                if (currPin->directions() & ConnDirRight)
                {
                    inVisibilityRange = true;
                }
            }
            if (angle >= 45 && angle <= 135)
            {
                if (currPin->directions() & ConnDirDown)
                {
                    inVisibilityRange = true;
                }
            }
            if (angle >= 135 && angle <= 225)
            {
                if (currPin->directions() & ConnDirLeft)
                {
                    inVisibilityRange = true;
                }
            }
            if (angle >= 225 && angle <= 315)
            {
                if (currPin->directions() & ConnDirUp)
                {
                    inVisibilityRange = true;
                }
            }
            if (!inVisibilityRange)
            {
                routingCost += router->routingParameter(portDirectionPenalty);
            }

            if (router->m_allows_orthogonal_routing)
            {
                // This has same ID and is either unconnected or not
                // exclusive, so give it visibility.
                EdgeInf *edge = new EdgeInf(dummyConnectionVert,
                                            currPin->m_vertex, true);
                // XXX Can't use a zero cost due to assumptions
                //     elsewhere in code.
                edge->setDist(manhattanDist(dummyConnectionVert->point,
                                            currPin->m_vertex->point) +
                              std::max(0.001, routingCost));
            }

            if (router->m_allows_orthogonal_routing)
            {
                // This has same ID and is either unconnected or not
                // exclusive, so give it visibility.
                EdgeInf *edge = new EdgeInf(dummyConnectionVert,
                                            currPin->m_vertex, false);
                // XXX Can't use a zero cost due to assumptions
                //     elsewhere in code.
                edge->setDist(euclideanDist(dummyConnectionVert->point,
                                            currPin->m_vertex->point) +
                              std::max(0.001, routingCost));
            }

            // Increment the number of valid pins for this ConnEnd connection.
            validPinCount++;
        }
    }

    if (validPinCount == 0)
    {
        // There should be at least one pin, otherwise we will have
        // problems finding connector routes.
        err_printf("Warning: In ConnEnd::assignPinVisibilityTo():\n"
                   "         ConnEnd for connector %d can't connect to shape %d\n"
                   "         since it has no pins with class id of %u.\n",
                   (int) m_conn_ref->id(), (int) m_anchor_obj->id(),
                   m_connection_pin_class_id);
    }
}
Esempio n. 18
0
static void 
do_list(int argc, char * argv[])
{
     char * dir_str;
     DIR *dirp;
     char filename[PATH_MAX];
     char cwd[PATH_MAX];
     struct stat sbuf;
     int err;

     if( mount_count == 0 )
     {
         err_printf("fs: No filesystems mounted\n");
         return;
     }
     
     if (!scan_opts(argc, argv, 1, NULL, 0, &dir_str, OPTION_ARG_TYPE_STR, "directory"))
          return;

     if( dir_str == 0 )
     {
         dir_str = getcwd(cwd, sizeof(cwd));
     }
     
     dirp = opendir(dir_str);
     if (dirp==NULL) {
          err_printf("fs list: no such directory %s\n",dir_str);
          return;
     }
     
     for (;;) {
          struct dirent *entry = readdir(dirp);
          
          if( entry == NULL )
               break;
    
          strcpy(filename, dir_str);
          strcat(filename, "/");
          strcat(filename, entry->d_name);
          
          err = stat(filename, &sbuf);
          if (err < 0) {
               diag_printf("Unable to stat file %s\n", filename);
               continue;
          }
          diag_printf("%4d ", sbuf.st_ino);
          if (S_ISDIR(sbuf.st_mode)) diag_printf("d");
          if (S_ISCHR(sbuf.st_mode)) diag_printf("c");
          if (S_ISBLK(sbuf.st_mode)) diag_printf("b");
          if (S_ISREG(sbuf.st_mode)) diag_printf("-");
          if (S_ISLNK(sbuf.st_mode)) diag_printf("l");
          diag_printf("%s%s%s",    // Ho, humm, have to hard code the shifts
                      rwx[(sbuf.st_mode & S_IRWXU) >> 16],
                      rwx[(sbuf.st_mode & S_IRWXG) >> 19],
                      rwx[(sbuf.st_mode & S_IRWXO) >> 22]);
          diag_printf(" %2d size %6d %s\n",
                      sbuf.st_nlink,sbuf.st_size, 
                      entry->d_name);
     }
     
     closedir(dirp);
     return;
}
Esempio n. 19
0
/* ---------------- lsq_fit  ----------------------------------
 * Least square fit routine to determine the rotation matrix to
 * superimpose coordinates r1 onto coordinates r2.
 * omega is a symmetric matrix in symmetric storage mode:
 * The element [i][j] is stored at position [i*(i+1)/2+j] with i>j
 * Thanks to Wilfred and Thomas Huber.
 */
static int
lsq_fit(const int nr_atoms, const struct RPoint *r1, const struct RPoint *r2,
        float R[3][3])
{

    int i, j, ii, jj, n;
    float U[3][3], det_U, sign_detU, sigma;
    float H[3][3], K[3][3];     /*, R[3][3]; */
    float omega[21], eve_omega[36], eva_omega[6];
    const float TINY = 1.e-10;
    const float SMALL = 1.e-5;
    const char *this_sub = "lsq_fit";

/* ----- CALCULATE THE MATRIX U AND ITS DETERMINANT ----- */
    for (i = 0; i < 3; i++)
            for (j = 0; j < 3; j++)
                U[i][j] = 0.0;

    for (n = 0; n < nr_atoms; n++) {
            U[0][0] += r1[n].x * r2[n].x;
            U[0][1] += r1[n].x * r2[n].y;
            U[0][2] += r1[n].x * r2[n].z;
            U[1][0] += r1[n].y * r2[n].x;
            U[1][1] += r1[n].y * r2[n].y;
            U[1][2] += r1[n].y * r2[n].z;
            U[2][0] += r1[n].z * r2[n].x;
            U[2][1] += r1[n].z * r2[n].y;
            U[2][2] += r1[n].z * r2[n].z;
    }

    det_U = U[0][0] * U[1][1] * U[2][2] + U[0][2] * U[1][0] * U[2][1] +
        U[0][1] * U[1][2] * U[2][0] - U[2][0] * U[1][1] * U[0][2] -
        U[2][2] * U[1][0] * U[0][1] - U[2][1] * U[1][2] * U[0][0];

    if (fabs(det_U) < TINY) {
            err_printf(this_sub, "determinant of U equal to zero\n");
            return EXIT_FAILURE;
    }

    sign_detU = det_U / fabs(det_U);    /* sign !!! */


/* ----- CONSTRUCT OMEGA, DIAGONALIZE IT AND DETERMINE H AND K --- */

    for (i = 0; i < 6; i++)
            for (j = i; j < 6; j++)
                omega[(j * (j + 1) / 2) + i] = 0.0;
    for (j = 3; j < 6; j++) {
            jj = j * (j + 1) / 2;
            for (i = 0; i < 3; i++) {
                ii = jj + i;
                omega[ii] = U[i][j - 3];
            }
    }

#ifdef DEBUG
    fprintf(stdout, "omega matrix:\n");
    for (i = 0; i < 21; i++)
            fprintf(stdout, STR(%SFO \ t), omega[i]);
    fprintf(stdout, "\n");
#endif

    i = 6;                      /* dimension of omega matrix */
    j = 0;                      /* both, eigenvalues and eigenvectors are calculated */
    eigen(omega, eve_omega, &i, &j);

    for (i = 0; i < 6; i++)
            eva_omega[i] = omega[i * (i + 1) / 2 + i];

#ifdef DEBUG
    fprintf(stdout, "Eigenvalues:\n");
    for (i = 0; i < 6; i++)
            fprintf(stdout, STR(%SFO \ t), eva_omega[i]);
    fprintf(stdout, "\n");
    ii = 0;
    fprintf(stdout, "Eigenvectors:\n");
    for (j = 0; j < 6; j++) {   /* ----- elements of eigenvector i ------ */
            for (i = 0; i < 6; i++)     /* ----  loop for eigenvectors !!! ----- */
               fprintf(stdout, STR(%SFO \ t), eve_omega[ii++]);
            fprintf(stdout, "\n");
    }

#endif


    if (det_U < 0.0) {
            if (fabs(eva_omega[1] - eva_omega[2]) < SMALL) {
                err_printf(this_sub,
                       "determinant of U < 0 && degenerated eigenvalues\n");
                return EXIT_FAILURE;
        }
    }

    for (i = 0; i < 3; i++){
           for (j = 0; j < 3; j++) {
               H[i][j] = M_SQRT2 * eve_omega[j * 6 + i];
               K[i][j] = M_SQRT2 * eve_omega[j * 6 + i + 3];
       }
    }
    sigma = (H[1][0] * H[2][1] - H[2][0] * H[1][1]) * H[0][2] +
        (H[2][0] * H[0][1] - H[0][0] * H[2][1]) * H[1][2] +
        (H[0][0] * H[1][1] - H[1][0] * H[0][1]) * H[2][2];

    if (sigma <= 0.0) {
        for (i = 0; i < 3; i++) {
                H[i][2] = -H[i][2];
                K[i][2] = -K[i][2];
            }
    }

/* --------- DETERMINE R AND ROTATE X ----------- */
    for (i = 0; i < 3; i++)
           for (j = 0; j < 3; j++)
               R[j][i] = K[j][0] * H[i][0] + K[j][1] * H[i][1] +
           sign_detU * K[j][2] * H[i][2];


#ifdef DEBUG
    mfprintf(stdout, "Rotation matrix:\n");
    for (j = 0; j < 3; j++) {
           for (i = 0; i < 3; i++)
               mfprintf(stdout, "%f ", R[i][j]);
           mfprintf(stdout, "\n");
    }
#endif

    return EXIT_SUCCESS;
}
Esempio n. 20
0
static void 
do_write(int argc, char * argv[])
{
    char *name_str = NULL;
    int err;
    struct option_info opts[2];    
    CYG_ADDRESS mem_addr = 0;
    unsigned long length = 0;
    bool mem_addr_set = false;
    bool length_set = false;
    int fd;
    
     if( mount_count == 0 )
     {
         err_printf("fs: No filesystems mounted\n");
         return;
     }

     init_opts(&opts[0], 'b', true, OPTION_ARG_TYPE_NUM, 
               (void *)&mem_addr, (bool *)&mem_addr_set, "memory base address");
     init_opts(&opts[1], 'l', true, OPTION_ARG_TYPE_NUM, 
               (void *)&length, (bool *)&length_set, "image length");
     
    if (!scan_opts(argc, argv, 1, opts, 2, &name_str, OPTION_ARG_TYPE_STR, "file name") ||
        name_str == NULL)
    {
        fs_usage("invalid arguments");
        return;
    }

//    diag_printf("load_address %08x %08x\n",load_address,load_address_end);
//    diag_printf("ram %08x %08x\n",ram_start, ram_end);
//    diag_printf("file name %08x >%s<\n",name_str,name_str);
    
    if (!mem_addr_set &&
        (load_address >= (CYG_ADDRESS)ram_start) &&
	((load_address_end) < (CYG_ADDRESS)ram_end))
    {
	mem_addr = load_address;
	mem_addr_set = true;
	if (!length_set)
        {
	    length = load_address_end - load_address;
	    length_set = true;
            // maybe get length from existing file size if no loaded
            // image?
        }
    }
    
    fd = open( name_str, O_WRONLY|O_CREAT|O_TRUNC );

    if( fd < 0 )
    {
        err_printf("fs write: Cannot open %s\n", name_str );
        return;
    }

//    diag_printf("write %08x %08x\n",mem_addr, length );
    
    err = write( fd, (void *)mem_addr, length );

    if( err != length )
    {
        err_printf("fs write: failed to write to file %d(%d) %d\n",err,length,errno);
    }

    err = close( fd );

    if( err != 0 )
        err_printf("fs write: close failed\n");
}
Esempio n. 21
0
File: sdtid.c Progetto: zbuc/stoken
static void missing_node(struct sdtid *s, const char *name)
{
	err_printf(s, "missing required xml node '%s'\n", name);
}
Esempio n. 22
0
// Populate the deleted-object vectors with all the connectors and junctions
// that form the registered hyperedges.  Then return the set of all these
// connectors so they can be ignored for individual rerouting.
ConnRefSet HyperedgeRerouter::calcHyperedgeConnectors(void)
{
    COLA_ASSERT(m_router != NULL);

    ConnRefSet allRegisteredHyperedgeConns;

    // Clear the deleted-object vectors.  We populate them here if necessary.
    m_deleted_junctions_vector.clear();
    m_deleted_junctions_vector.resize(count());
    m_deleted_connectors_vector.clear();
    m_deleted_connectors_vector.resize(count());

    m_terminal_vertices_vector.clear();
    m_terminal_vertices_vector.resize(count());
    m_added_vertices.clear();

    // Populate the deleted-object vectors.
    const size_t num_hyperedges = count();
    for (size_t i = 0; i < num_hyperedges; ++i)
    {
        if (m_root_junction_vector[i])
        {
            // Follow objects attached to junction to find the hyperedge.
            bool valid = findAttachedObjects(i, m_root_junction_vector[i], NULL,
                    allRegisteredHyperedgeConns);
            if (!valid)
            {
                err_printf("Warning: Hyperedge %d registered with "
                           "HyperedgeRerouter is invalid and will be "
                           "ignored.\n", (int) i);
                // Hyperedge is invalid.  Clear the terminals and other info
                // so it will be ignored, and rerouted as a normal set of 
                // connectors.
                m_terminals_vector[i].clear();
                m_terminal_vertices_vector[i].clear();
                m_deleted_junctions_vector[i].clear();
                m_deleted_connectors_vector[i].clear();
            }
            continue;
        }

        // Alternatively, we have a set of ConnEnds, so store the
        // corresponding terminals
        std::pair<bool, VertInf *> maybeNewVertex;
        for (ConnEndList::const_iterator it = m_terminals_vector[i].begin();
                it != m_terminals_vector[i].end(); ++it)
        {
            maybeNewVertex = it->getHyperedgeVertex(m_router);
            COLA_ASSERT(maybeNewVertex.second != NULL);
            m_terminal_vertices_vector[i].insert(maybeNewVertex.second);

            if (maybeNewVertex.first)
            {
                // This is a newly created vertex.  Remember it so we can
                // free it and it's visibility edges later.
                m_added_vertices.push_back(maybeNewVertex.second);
            }
        }
    }

    // Return these connectors that don't require rerouting.
    return allRegisteredHyperedgeConns;
}
Esempio n. 23
0
int
wisvc_Handle_I_and_J_options (int argc, char **argv,
			      char *s, int i, int autostart)
{
  int called_as_service = 0;
  size_t path_len;
  int start_now = 0;
  char *service_name = (*(s + 2) ? (s + 2) : WISVC_DEFAULT_SERVICE_NAME);
  char *progname = argv[0];
  char *last_of_path, *cutpnt;
  char BinaryPathName[(MAX_BINARY_PATH) + 10];

/*
   if(i > 1)
   {
   err_printf((
   "%s: If you give %s option, it MUST be the first argument on command line!",
   progname,s));
   kubl_main_exit(1);
   }
 */

/* Then construct absolute path to this binary executable
   by combining working directory path got with getcwd
   with the program name got from argv[0].
   Note that the program name itself can be relative or absolute path.
   getcwd returns a string that represents the path of
   the current working directory. If the current working
   directory is the root, the string ends with a backslash (\).
   If the current working directory is a directory
   other than the root, the string ends with the directory
   name and not with a backslash.
   Note that absolute paths with upward parts (..)
   like the one below seem to work equally well, so
   we do not need to worry about .. :s and .:s in any
   special way.
   D:\inetpub\wwwroot\..\..\ic\.\diskit\wi\windebug\wi.exe
 */

  if (is_abs_path (progname))
    {
      strncpy (BinaryPathName, progname, (MAX_BINARY_PATH));
    }
  else
    /* We have to combine pwd + relative starting path */
    {
      if (NULL == getcwd (BinaryPathName, _MAX_PATH))
	{
	  err_printf (("%s: Cannot getcwd because: %s",
		       progname, strerror (errno)));
	  exit (1);
	}
      path_len = strlen (BinaryPathName);
      last_of_path = (BinaryPathName + path_len - 1);
      if ((0 == path_len) || !is_abs_path (last_of_path))
	{			/* Add the missing path separator between if needed */
	  strncat_ck (BinaryPathName, "\\", (MAX_BINARY_PATH));
	}
      /* And then the progname itself. */
      strncat_ck (BinaryPathName, progname, (MAX_BINARY_PATH));
    }

  /* Add our own special .eXe extension to the program name, so that
     when service is started, the code in main can see from argv[0]
     that it was started as a service, not as an ordinary command
     line program.
   */
  strncat_ck (BinaryPathName, WISVC_EXE_EXTENSION_FOR_SERVICE, (MAX_BINARY_PATH));

  /* Do chdir to the same directory where the executable is, needed
     because of wi.cfg check soon performed. */
  if ((NULL != (cutpnt = strrchr (BinaryPathName, '\\'))))
    {				/* Search the last backslash. */
      unsigned char
        save_the_following_char = *(((unsigned char *) cutpnt) + 1);
      *(cutpnt + 1) = '\0';

      if (chdir (BinaryPathName))	/* Is not zero, i.e. -1, an error. */
	{			/* However, we do not exit yet. */
	  err_printf (("%s: Cannot chdir to \"%s\" because: %s",
		       argv[0], BinaryPathName, strerror (errno)));
	  exit (1);
	}

      *(((unsigned char *) cutpnt) + 1) = save_the_following_char;
    }


/* Add all command line arguments after the absolute program name
   itself, separated by spaces. The started service will see them
   in the elements of argv vector, in the normal way, that is
   argv[0] will contain just the absolute program name which ends with
   .eXe and arguments are in argv[1], argv[2], etc.

   Check also for options -S (start the service), and -W change working
   directory. The latter would not be actually necessary to do here,
   but, if the directory is invalid, then it is much more friendly
   to give an error message here, than let the service itself fail,
   and hide the same error message to god knows which log file.
   Check that the user does not try to give options -D, -U, -R or -d
   to the service to be installed.

 */

  for (i = 1; i < argc; i++)
    {
      s = argv[i];
      if ('-' == s[0])
	{
	  switch (s[1])
	    {			/* With -S ignore the possibility that a different service
				   name could be specified after it than after -I or -J
				   DON'T ADD OPTIONS -S, -I or -J to BinaryPathName, as
				   they would be ignored anyway in service. */
	    case 'S':
	      {
		start_now = 1;
		continue;
	      }
	    case 'I':
	    case 'J':
	      {
		continue;
	      }
	    case 'W':
	      {
		int stat
		= wisvc_Handle_W_option (argc, argv, s, &i, called_as_service);
		if (stat)
		  {
		    kubl_main_exit (stat);
		  }
		break;
	      }
	    case 'D':
	    case 'U':		/* case 'R': */
	    case 'd':
	      {
		err_printf ((
			      "%s: Sorry, the option %s can be used only from command line, not in service!\n",
			      argv[0], s));
		exit (1);
	      }
	    }
	}

      strncat_ck (BinaryPathName, " ", (MAX_BINARY_PATH));
      strncat_ck (BinaryPathName, argv[i], (MAX_BINARY_PATH));
    }

  {				/* Check already HERE that there is a config file in the final
				   working directory, for the same user-friendly reason as
				   checking the validity of -W option's argument. */
    int fd = open (CFG_FILE, O_RDWR);
    if (fd < 0)
      {
	err_printf ((
		      "There must be a %s file in the server's working directory. Exiting.\n",
		      CFG_FILE));
	exit (-1);
      }
    fd_close (fd, NULL);	/* Defined in widisk.h */
  }

  wisvc_CreateKublService (argc, argv, service_name, BinaryPathName,
			   autostart, start_now);

  return (0);
}
Esempio n. 24
0
void
__default_terminate()
{
    passert(0, err_printf("%s: called.\n", __FUNCTION__));
}
Esempio n. 25
0
int
wisvc_StartKublService (int argc, char **argv, SC_HANDLE schService,
			char *service_name, char *BinaryPathName,
			int discard_argv)
{				/* The last two arguments not really needed except for error messages */
  int called_as_service = 0;	/* Needed by macro err_printf */
  int checkpoint_has_stayed_stagnant_n_iterations = 0;
  SERVICE_STATUS ssStatus;
  DWORD dwOldCheckPoint = 0, dwOlderCheckPoint = 0;

/*
   err_printf(("StartKublService: argc=%d, argv[0]=%s, argv[1]=%s\n",
   argc,argv[0],argv[1]));
 */

  if (!StartService (schService,	/* handle of service    */
		     (discard_argv ? 0 : (argc - 1)),	/* number of arguments  */
		     (discard_argv ? NULL : (argv + 1))))	/* Arg vector from main */
    {				/* without argv[0] */
      DWORD erhe = GetLastError ();

      err_printf ((
		    "%s: Starting service \"%s\" (path: \"%s\") failed. "
		    "StartService returned zero, errno=%ld%s\n",
		    argv[0], service_name, BinaryPathName, erhe,
		    ((ERROR_SERVICE_ALREADY_RUNNING == erhe) ?
		     " because service has been already started!" : ".")
		  ));
      return (0);
    }
  else
    {
      err_printf (("Service %s start in progress, BinaryPathName=%s\n",
		   service_name, BinaryPathName));
    }

  /* Check the status until the service is running. */

  if (!QueryServiceStatus (schService,	/* handle of service       */
			   &ssStatus))	/* address of status info  */
    {
      DWORD erhe = GetLastError ();

      err_printf ((
	     "%s: Querying status of service \"%s\" (path: \"%s\") failed. "
		    "QueryServiceStatus returned zero, errno=%ld.\n",
		    argv[0], service_name, BinaryPathName, erhe));
      return (0);
    }

  Sleep (10);			/* First sleep ten seconds. */
  while (ssStatus.dwCurrentState != SERVICE_RUNNING)
    {
      if (SERVICE_STOPPED == ssStatus.dwCurrentState)
	{
	  break;
	}

      dwOlderCheckPoint = dwOldCheckPoint;
      dwOldCheckPoint = ssStatus.dwCheckPoint;	/* Save current checkpoint */

      if (ssStatus.dwWaitHint > 300)
	{
	  ssStatus.dwWaitHint = 300;
	}
      Sleep (ssStatus.dwWaitHint);	/* Wait for the specified interval. */

      /* Check the status again. */
      if (!QueryServiceStatus (schService, &ssStatus))
	{
	  break;
	}
/*
   err_printf((
   "dwOlderCheckPoint=%ld, dwOldCheckPoint=%ld, ssStatus.dwCheckPoint=%ld, ssStatus.dwWaitHint=%ld\n",
   dwOlderCheckPoint, dwOldCheckPoint,
   ssStatus.dwCheckPoint, ssStatus.dwWaitHint));
 */

/* Break if the checkpoint has not been incremented for three times. */
      if ((dwOldCheckPoint >= ssStatus.dwCheckPoint)
	  && (dwOlderCheckPoint >= ssStatus.dwCheckPoint))
	{
	  if (++checkpoint_has_stayed_stagnant_n_iterations > 3)
	    {
	      break;
	    }
	}
      checkpoint_has_stayed_stagnant_n_iterations = 0;
    }


  if (ssStatus.dwCurrentState == SERVICE_RUNNING)
    {
      {
	err_printf ((
		 "%s: Service \"%s\" started successfully (path: \"%s\").\n",
		      argv[0], service_name, BinaryPathName));
      }
      return (1);
    }
  else
    {
      err_printf ((
		"%s: Service \"%s\" (path: \"%s\") %s started correctly.\n",
		    argv[0], service_name, BinaryPathName,
	     ((SERVICE_START_PENDING != ssStatus.dwCurrentState) ? "has not"
	      : "may or may not have")));
      err_printf (("  Current State: %d\n",
		   ssStatus.dwCurrentState));
      err_printf (("  Exit Code: %d\n", ssStatus.dwWin32ExitCode));
      err_printf (("  Service Specific Exit Code: %d\n",
		   ssStatus.dwServiceSpecificExitCode));
      err_printf (("  Check Point: %d\n", ssStatus.dwCheckPoint));
      err_printf (("  Wait Hint: %d\n", ssStatus.dwWaitHint));
      err_printf ((
		    "Please use services icon in Control Panel to see whether service \"%s\" was really started."
	 " Check also the file wi.err in the server's working directory.\n",
		    service_name));
      return (0);
    }
}
Esempio n. 26
0
/* virtual */ SysStatus
XHandleTrans::free(XHandle xhandle)
{
    XBaseObj *xBaseObj;
    ObjRef objRef;
    BaseProcessRef procRef;
    SysStatus rc;
    SysStatusProcessID processPID;
    // no lock is held, so these pointers can dissapear
    // out from under us.  That's why we copy and test.
    // also, the xhandle may already be free, so all errors
    // just lead to returning

    tassertMsg(XHANDLE_IDX(xhandle) >= CObjGlobals::numReservedEntries,
	       "Freeing global xhandle\n");
    xBaseObj = &xhandleTable[XHANDLE_IDX(xhandle)];
    objRef = xBaseObj->__iobj;
    processPID = xBaseObj->getOwnerProcessID();


#ifdef __NO_REGISTER_WITH_KERNEL_WRAPPER
    if (processPID != _KERNEL_PID) {
	// we know kernel will not go away, don't insert in process list,
	// since this ProcessWrapper becomes a hot spot in file systems
	rc = DREFGOBJ(TheProcessSetRef)->
	    getRefFromPID(xBaseObj->getOwnerProcessID(), procRef);
	if (_FAILURE(rc)) {
	    tassert(!(xBaseObj->isValid()),
		    err_printf("PID %ld invalid in valid Xobj\n",
			       xBaseObj->getOwnerProcessID()));
	    return 0;
	}
	if (!procRef) return 0;
    }
#else
    rc = DREFGOBJ(TheProcessSetRef)->
	getRefFromPID(xBaseObj->getOwnerProcessID(), procRef);
    if (_FAILURE(rc)) {
	tassert(!(xBaseObj->isValid()),
		err_printf("PID %ld invalid in valid Xobj\n",
			   xBaseObj->getOwnerProcessID()));
	return 0;
    }
    if (!procRef) return 0;
#endif

    if ((!objRef)) return 0;
    if ((rc=DREF(objRef)->publicLockExportedXObjectList())) return 0;
#ifdef __NO_REGISTER_WITH_KERNEL_WRAPPER
    if (processPID != _KERNEL_PID) {
	if ((rc=DREF(procRef)->lockMatchedXObjectList())) {
	    DREF(objRef)->publicUnlockExportedXObjectList();
	    return 0;
	}
    }
#else
    if ((rc=DREF(procRef)->lockMatchedXObjectList())) {
	DREF(objRef)->publicUnlockExportedXObjectList();
	return 0;
    }
#endif
    //once we have the locks, the XObject state can't change out from
    //under us.
    if (xBaseObj->isValid()) {
	/* kill xobject so subsequent calls fail don't need a sync -
	 * token circulates before xobj becomes unsafe for stale
	 * references remove from process and object lists. Remove
	 * holder from lists and reset __nummeth to prevent another
	 * releaseAccess call (inflight) from trying to free this
	 * again.
	 */
	xBaseObj->__nummeth = 0;
#ifdef __NO_REGISTER_WITH_KERNEL_WRAPPER
	if (processPID != _KERNEL_PID) {
	    DREF(procRef)->removeMatchedXObj(xhandle);
	}
#else
	DREF(procRef)->removeMatchedXObj(xhandle);
#endif
	DREF(objRef)->removeExportedXObj(xhandle);

	// release locks before callback
#ifdef __NO_REGISTER_WITH_KERNEL_WRAPPER
	if (processPID != _KERNEL_PID) {
	    DREF(procRef)->unlockMatchedXObjectList();
	}
#else
	DREF(procRef)->unlockMatchedXObjectList();
#endif
	DREF(objRef)->publicUnlockExportedXObjectList();

	xBaseObj->setBeingFreed(0);
	DREF(objRef)->handleXObjFree(xhandle);

	XBaseObj *removed;

	// must to this after removes - same space is used for both
	do {
	    removed = removedEntries;
	    xBaseObj->setNextFree(removed);
	} while (!CompareAndStoreSynced((uval*)(&removedEntries),
				       (uval)removed, (uval)xBaseObj));

	numberRemoved++;		// doesn't have to be exact,
					// so don't sync
    } else {
	// race - someone else freed the XObject
	// release locks using original values.
#ifdef __NO_REGISTER_WITH_KERNEL_WRAPPER
	if (processPID != _KERNEL_PID) {
	    DREF(procRef)->unlockMatchedXObjectList();
	}
#else
	DREF(procRef)->unlockMatchedXObjectList();
#endif
	DREF(objRef)->publicUnlockExportedXObjectList();
    }

    if ((numberRemoved % XHANDLE_TABLE_GC_INTERVAL) == 0) processToken();
    return 0;
}
Esempio n. 27
0
SysStatus
HATDefaultBase<ALLOC>::destroy(void)
{
    //err_printf("HATDefaultBase %p destroying\n", getRef());

    {   // remove all ObjRefs to this object
	SysStatus rc=closeExportedXObjectList();
	// most likely cause is that another destroy is in progress
	// in which case we return success
	if (_FAILURE(rc)) return _SCLSCD(rc)==1?0:rc;
    }

    SysStatus rc=0;
    VPSet* dummy;

    //Get rid of all the segments
    SegmentList<ALLOC>* restart;
    SegmentHATRef ref;

    //Use region logic, setting region bounds to all of memory
    uval regionAddr = 0;
    uval regionEnd = (uval)(-1);
    uval segmentAddr, segmentEnd;
    uval vp;

    /*
     * clean up the global list
     */
    glock.acquire();
    // regionAddr is updated by delete to be correct for this segment
    restart = &segmentList;
    while (0<=(rc=SegmentList<ALLOC>::DeleteSegment(regionAddr, regionEnd,
					segmentAddr, segmentEnd,
					ref, dummy, restart))) {
	tassert(rc==0,err_printf("Impossible in HATDefaultBase::destroy()\n"));

	//err_printf("HATDefaultBase %p destroying seg %p\n", getRef(), ref);
	DREF(ref)->destroy();
    }


    glock.release();

    for (vp=0;vp<Scheduler::VPLimit;vp++) {
	byVP[vp].lock.acquire();
	// Free segment table
	if (byVP[vp].segps) {
	    //err_printf("HATDefaultBase %p destroying segtable %p on %ld\n",
	    //       getRef(), byVP[vp].segps, vp);
	    byVP[vp].segps->destroy();
	}
	// Free local copy of segmentHAT list
	restart = &(byVP[vp].segmentList);
	while (0<=(rc=SegmentList<ALLOC>::DeleteSegment(regionAddr, regionEnd,
						       segmentAddr, segmentEnd,
						       ref, dummy, restart)));

	byVP[vp].lock.release();
    }

    // schedule the object for deletion
    destroyUnchecked();

    return 0;
}
Esempio n. 28
0
/* static */ SysStatus
XHandleTrans::ClassInit(VPNum vp)
{
    SysStatus rc;
    uval ptr;
    XHandleTrans *theXHandleTransPtr;

    if (vp != 0) {
//	tassertWrn(0, "processor %d sharing xhandle table\n", vp);
	return 0;
    }

    /*
     * We allocate virtual memory for the entire quasi-infinite xhandle table,
     * but we initialize just the first chunk of the table.  Subsequent chunks
     * are initialized as needed.
     */
    rc = DREFGOBJ(ThePageAllocatorRef)->
		    allocPagesAligned(ptr, XHANDLE_TABLE_MAX*sizeof(XBaseObj),
				      sizeof(XBaseObj));
    tassert(_SUCCESS(rc), err_printf("xhandle table allocation failed.\n"));

    /*
     * We initialize the first chunk from 1 rather than 0 to avoid putting
     * XHANDLE_NONE on the free list.
     */
    tassert(XHANDLE_NONE_IDX == 0, err_printf("XHANDLE_NONE_IDX not 0?\n"));
    XBaseObj *free, *dummy;

    // We reserve a bunch of XHandle slots for global clustered objects
    // This provides free xhandles for global clustered objects
    InitXHandleRange((XBaseObj *) ptr, CObjGlobals::numReservedEntries,
		     XHANDLE_TABLE_INCREMENT,
		     free, dummy);

    // Must manually zero the reserved entries for global objects
    // since they are not part of the regular initialzation
    memset((void *)ptr, 0, CObjGlobals::numReservedEntries * sizeof(XBaseObj));

    theXHandleTransPtr = new XHandleTrans;

    theXHandleTransPtr->xhandleTable = (XBaseObj *) ptr;
    theXHandleTransPtr->xhandleTableLimit = XHANDLE_TABLE_INCREMENT;
    theXHandleTransPtr->freeEntries = free;
    theXHandleTransPtr->oldEntries.init(0);
    theXHandleTransPtr->removedEntries = 0;
    theXHandleTransPtr->numberRemoved = 0;

    new CObjRootSingleRep(theXHandleTransPtr,
			  RepRef(GOBJ(TheXHandleTransRef)));

    /*
     * Facts about the xhandle table are shadowed in the static XHandleTable
     * and in all the dispatchers.
     */
    XHandleTable = theXHandleTransPtr->xhandleTable;
    rc = DREFGOBJ(TheDispatcherMgrRef)->
		    publishXHandleTable(theXHandleTransPtr->xhandleTable,
					theXHandleTransPtr->xhandleTableLimit);
    tassert(_SUCCESS(rc), err_printf("publishXHandleTable failed.\n"));

    return 0;
}
Esempio n. 29
0
/* Receive w1 response(s) corresponding to a request 'p_req' and callback them
   by recv_cb().
 */
static lr_errc_t recv_w1msg(w1_hndl_t *p_hndl,
    const struct cn_msg *p_req, recv_w1msg_cb_t recv_cb, void *p_cb_priv_dta)
{
    lr_errc_t ret=LREC_SUCCESS;

    w1msg_more_stat_t more_stat;
    uint8_t recv_buf[MAX_W1_NETLINK_MSG_SZ];
    unsigned int n_rcv_msgs, n_pyld_msgs;
    ssize_t dta_len;
    size_t offs;

    uint32_t *p_ack;
    struct nlmsghdr *p_nlmsg;
    struct cn_msg *p_cnmsg;
    struct w1_netlink_msg *p_w1msg, *p_w1req;
    struct pollfd fds;

    if (p_req->len <= 0) {
        /* no response for no request */
        goto finish;
    }
    p_w1req = (struct w1_netlink_msg*)(p_req->data);

    more_stat = w1msg_more_req;

    fds.fd = p_hndl->sock_nl;
    fds.events = POLLIN;
    fds.revents = 0;

    for (n_rcv_msgs=0;; n_rcv_msgs++)
    {
        switch(poll(&fds, 1, (more_stat==w1msg_more_req ? 1000 :
            (more_stat==w1msg_more_opt ? 50 : 1))))
        {
        case 0:
            if (!n_rcv_msgs) {
                err_printf(
                    "[%s] No response on the w1 netlink connector received. Make "
                    "sure the \"wire\" kernel module is loaded with the netlink "
                    "support compiled!\n", __func__);
                ret=LREC_NO_RESP;
                goto finish;
            } else
            if (more_stat==w1msg_more_req) {
                err_printf("[%s] Response expected but not received; timeout\n",
                    __func__);
                ret=LREC_NO_RESP;
                goto finish;
            }
            goto break_recv_loop;
        case -1:
            err_printf("[%s] poll() on the w1 netlink connector error %d; %s\n",
                __func__, errno, strerror(errno));
            ret=LREC_COMM_ERR;
            goto finish;
        }

        /* get the message */
        dta_len = recv(p_hndl->sock_nl, recv_buf, sizeof(recv_buf), 0);
        if (dta_len<0) {
            err_printf("[%s] recv() on the w1 netlink connector error %d; %s\n",
                __func__, errno, strerror(errno));
            ret=LREC_COMM_ERR;
            goto finish;
        }

        /* parse netlink msgs chain */
        for (p_nlmsg=(struct nlmsghdr*)recv_buf, n_pyld_msgs=0, offs=0;
            NLMSG_OK(p_nlmsg, dta_len);
            n_pyld_msgs++)
        {
            struct nlmsghdr nlmsg = *p_nlmsg;

            dbg_printf("[NLSCK:%d]: %s [header]: len:0x%08x type:0x%04x "
                "flags:0x%04x seq:0x%08x pid:0x%08x\n", p_hndl->sock_nl,
                (!n_pyld_msgs ? "<- netlink" : "   netlink"), nlmsg.nlmsg_len,
                nlmsg.nlmsg_type, nlmsg.nlmsg_flags, nlmsg.nlmsg_seq,
                nlmsg.nlmsg_pid);

            switch (nlmsg.nlmsg_type)
            {
            case NLMSG_NOOP:
                continue;
            case NLMSG_ERROR:
                err_printf("[%s] Netlink error message received\n", __func__);
                ret=LREC_PROTO_ERR;
                goto finish;
            }

            if (nlmsg.nlmsg_type==NLMSG_DONE || (nlmsg.nlmsg_flags & NLM_F_MULTI))
            {
                if (nlmsg.nlmsg_len > NLMSG_HDRLEN) {
                    memcpy(&recv_buf[offs],
                        NLMSG_DATA(p_nlmsg), nlmsg.nlmsg_len-NLMSG_HDRLEN);
                    offs += (nlmsg.nlmsg_len-NLMSG_HDRLEN);
                }
                if (nlmsg.nlmsg_type==NLMSG_DONE) break;
            } else {
                err_printf("[%s] Unexpected netlink message\n", __func__);
                ret=LREC_BAD_MSG;
                goto finish;
            }

            /* move to the next nlmsg */
            dta_len -= NLMSG_ALIGN(nlmsg.nlmsg_len);
            p_nlmsg = (struct nlmsghdr*)
                (((uint8_t*)p_nlmsg)+NLMSG_ALIGN(nlmsg.nlmsg_len));
        }

#define __CNMSG_OK(c,l) \
    ((l)>=(sizeof(struct cn_msg)+((c)->len)))

#define __ACK_W1MSG_INIT(a,w,b) \
    ((a)=(uint32_t*)(b), (w)=(struct w1_netlink_msg*)((a)+1))

#define __ACK_W1MSG_OK(w,l) \
    ((l)>=(sizeof(uint32_t)+sizeof(struct w1_netlink_msg)+((w)->len)))

#define __ACK_W1MSG_NEXT(a,w,l) \
    ((l)-=(sizeof(uint32_t)+sizeof(struct w1_netlink_msg)+((w)->len)), \
    (a)=(uint32_t*)(((uint8_t*)((a)+1))+sizeof(struct w1_netlink_msg)+((w)->len)), \
    (w)=(struct w1_netlink_msg*)(((uint8_t*)((w)+1))+((w)->len)+sizeof(uint32_t)))

        /* parse & filter out connector msgs chain */
        for (p_cnmsg=(struct cn_msg*)recv_buf,
                dta_len=(ssize_t)offs, n_pyld_msgs=0, offs=0;
            __CNMSG_OK(p_cnmsg, dta_len);
            n_pyld_msgs++)
        {
            int fltr=0;
            struct cn_msg cnmsg = *p_cnmsg;

            if (cnmsg.id.idx!=CN_W1_IDX || cnmsg.id.val!=CN_W1_VAL) {
                /* no w1 subsystem message */
                fltr=1;
            } else
            if (cnmsg.seq!=p_req->seq) {
                /* request/response sequences not match */
                fltr=2;
            }

            if (get_librasp_log_level()<=LRLOG_DEBUG)
            {
                char fltr_msg[32] = "";

                if (fltr) sprintf(fltr_msg, "; filtered out: %s",
                    (fltr==1 ? "no w1 msg" : "req/resp seqs not match"));

                dbg_printf("[NLSCK:%d]:    nest. cn_msg [header]: id:0x%08x|0x%08x "
                    "seq:0x%08x ack:0x%08x len:0x%04x flags:0x%04x%s\n",
                    p_hndl->sock_nl, cnmsg.id.idx, cnmsg.id.val, cnmsg.seq,
                    cnmsg.ack, cnmsg.len, cnmsg.flags, fltr_msg);
            }

            if (!fltr && cnmsg.len>0) {
                *(uint32_t*)&recv_buf[offs] = cnmsg.ack;
                offs += sizeof(uint32_t);
                memcpy(&recv_buf[offs], p_cnmsg->data, cnmsg.len);
                offs += cnmsg.len;
            }

            /* move to the next cn_msg */
            dta_len -= sizeof(struct cn_msg)+cnmsg.len;
            p_cnmsg = (struct cn_msg*)(((uint8_t*)(p_cnmsg+1))+cnmsg.len);
        }

        /* parse & filter out w1 msgs chain */
        for (__ACK_W1MSG_INIT(p_ack, p_w1msg, recv_buf),
                dta_len=(ssize_t)offs, n_pyld_msgs=0;
            __ACK_W1MSG_OK(p_w1msg, dta_len);
            __ACK_W1MSG_NEXT(p_ack, p_w1msg, dta_len), n_pyld_msgs++)
        {
            int fltr=0;

            if (p_w1msg->type!=p_w1req->type) {
                /* request/response types not match */
                fltr=1;
            } else
            if ((p_w1req->type==W1_MASTER_CMD &&
                    p_w1msg->id.mst.id!=p_w1req->id.mst.id) ||
                (p_w1req->type==W1_SLAVE_CMD &&
                    memcmp(&p_w1msg->id, &p_w1req->id, sizeof(p_w1msg->id))))
            {
                /* request/response ids not match */
                fltr=2;
            }

            if (get_librasp_log_level()<=LRLOG_DEBUG)
            {
                char fltr_msg[32] = "";
                char data_msg[2*DBG_PRINTF_DATA_MAX+32] = "";

                PREP_DATA_MSG_BUF(data_msg, p_w1msg);
                if (fltr) {
                    sprintf(fltr_msg, "; filtered out: req/resp %s not match",
                        (fltr==1 ? "types" : "ids"));
                }
                dbg_printf("[NLSCK:%d]:    nest. w1_msg [header]: type:0x%02x "
                    "status:0x%02x len:0x%04x id:0x%08x|0x%08x%s%s\n",
                    p_hndl->sock_nl, p_w1msg->type, p_w1msg->status, p_w1msg->len,
                    p_w1msg->id.mst.id, p_w1msg->id.mst.res, data_msg, fltr_msg);
            }

            if (!fltr && more_stat!=w1msg_no_more) {
                /* callback the caller for processing the received frame */
                more_stat = recv_cb(p_cb_priv_dta, p_w1msg,
                    (*p_ack==ACK_STAT_VAL ? TRUE : FALSE));
            }
        }
#undef __CNMSG_OK
#undef __ACK_W1MSG_INIT
#undef __ACK_W1MSG_OK
#undef __ACK_W1MSG_NEXT
    }
break_recv_loop:

finish:
    return ret;
}
Esempio n. 30
0
void RedirectSocketThreadOvl(RedirectSocketArg *arg)
{
    char pBuffer[1024+sizeof(int)+sizeof(char)+sizeof(int)];
    DWORD num_read, num_written;
    HANDLE hReadEvents[2];
    OVERLAPPED pOvl[2];
    char dummy_char;
    DWORD dummy_num_read;
    DWORD dwRetVal;
    BOOL bResult;

    if (arg->bReadisPipe)
    {
	pOvl[0].hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	pOvl[0].Internal = 0;
	pOvl[0].InternalHigh = 0;
	pOvl[0].Offset = 0;
	pOvl[0].OffsetHigh = 0;
	hReadEvents[0] = pOvl[0].hEvent;
	bResult = ReadFile(arg->hRead, &pBuffer[sizeof(int)+sizeof(char)+sizeof(int)], 1024, &num_read, &pOvl[0]);
	if (!bResult) 
	{
	    switch (GetLastError()) 
	    {
	    case ERROR_HANDLE_EOF: 
		// At the end of the file.
		goto QUIT_REDIRECTION;
		break;
	    case ERROR_IO_PENDING: 
		// I/O pending.
		break;
	    }
	}
    }
    else
    {
	hReadEvents[0] = WSACreateEvent();
	WSAEventSelect(arg->sockRead, hReadEvents[0], FD_READ | FD_CLOSE);
    }

    if (arg->bWriteisPipe)
    {
	pOvl[1].hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	pOvl[1].Internal = 0;
	pOvl[1].InternalHigh = 0;
	pOvl[1].Offset = 0;
	pOvl[1].OffsetHigh = 0;
	hReadEvents[1] = pOvl[1].hEvent;
	bResult = ReadFile(arg->hWrite, &dummy_char, 1, &dummy_num_read, &pOvl[1]);
	if (!bResult) 
	{
	    switch (GetLastError()) 
	    {
	    case ERROR_HANDLE_EOF: 
		// At the end of the file.
		goto QUIT_REDIRECTION;
		break;
	    case ERROR_IO_PENDING: 
		// I/O pending.
		break;
	    }
	}
    }
    else
    {
	hReadEvents[1] = WSACreateEvent();
	WSAEventSelect(arg->sockWrite, hReadEvents[1], FD_CLOSE);
    }

    // The format is pBuffer[int nDataLength | char cType | int nRank | char[] data]
    pBuffer[sizeof(int)] = arg->cType; // The type never changes
    *(int*)&pBuffer[sizeof(int)+sizeof(char)] = arg->nRank; // The rank never changes

    while (true)
    {
	dwRetVal = WaitForMultipleObjects(2, hReadEvents, FALSE, INFINITE);
	
	if (dwRetVal == WAIT_OBJECT_0)
	{
	    if (arg->bReadisPipe)
	    {
		if (num_read == 0)
		    goto QUIT_REDIRECTION;

		// Reading from a handle
		if (arg->bWriteisPipe)
		{
		    // Writing to a handle
		    if (!WriteFile(arg->hWrite, pBuffer, num_read, &num_written, NULL))
			//break;
			goto QUIT_REDIRECTION;
		}
		else
		{
		    // Writing to a socket
		    *(int*)pBuffer = num_read;
		    if (easy_send(arg->sockWrite, pBuffer, num_read + sizeof(int) + sizeof(char) + sizeof(int)) == SOCKET_ERROR)
		    {
			// Kill the process if the socket to redirect output is closed
			if (arg->hProcess != NULL)
			{
			    int error = 1;
			    if (GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, arg->dwPid))
			    {
				if (WaitForSingleObject(arg->hProcess, 500) == WAIT_OBJECT_0)
				    error = 0;
			    }
			    if (error)
			    {
				if (!SafeTerminateProcess(arg->hProcess, 10000013))
				{
				    if (GetLastError() != ERROR_PROCESS_ABORTED)
					TerminateProcess(arg->hProcess, 1);
				}
			    }
			}
			//break;
			goto QUIT_REDIRECTION;
		    }
		}

		// Post the next read
		ResetEvent(pOvl[0].hEvent);
		bResult = ReadFile(arg->hRead, &pBuffer[sizeof(int)+sizeof(char)+sizeof(int)], 1024, &num_read, &pOvl[0]);
		if (!bResult) 
		{
		    switch (GetLastError()) 
		    {
		    case ERROR_HANDLE_EOF: 
			// At the end of the file.
			goto QUIT_REDIRECTION;
			break;
		    case ERROR_IO_PENDING: 
			// I/O pending.
			break;
		    }
		}
	    }
	    else
	    {
		// Reading from a socket
		ResetEvent(hReadEvents[0]);
		while (num_read = easy_receive_some(arg->sockRead, pBuffer, 1024))
		{
		    if (num_read == SOCKET_ERROR || num_read == 0)
		    {
			// Kill the process if the socket to redirect input is closed
			if (arg->hProcess != NULL)
			{
			    int error = 1;
			    if (GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, arg->dwPid))
			    {
				if (WaitForSingleObject(arg->hProcess, 500) == WAIT_OBJECT_0)
				    error = 0;
			    }
			    if (error)
			    {
				if (!SafeTerminateProcess(arg->hProcess, 10000014))
				{
				    if (GetLastError() != ERROR_PROCESS_ABORTED)
					TerminateProcess(arg->hProcess, 1);
				}
			    }
			}
			break;
		    }
		    if (arg->bWriteisPipe)
		    {
			// Writing to a handle
			if (!WriteFile(arg->hWrite, pBuffer, num_read, &num_written, NULL))
			    //break;
			    goto QUIT_REDIRECTION;
		    }
		    else
		    {
			// Writing to a socket
			if (easy_send(arg->sockWrite, pBuffer, num_read) == SOCKET_ERROR)
			    //break;
			    goto QUIT_REDIRECTION;
		    }
		}
	    }
	}
	else
	{
	    if (dwRetVal != WAIT_OBJECT_0+1)
	    {
		err_printf("error %d\n", GetLastError());
		goto QUIT_REDIRECTION;
	    }
	}
	
	dwRetVal = WaitForSingleObject(hReadEvents[1], 0);
	if (dwRetVal == WAIT_OBJECT_0)
	{
	    // redirect handle closed, terminate the process
	    if (arg->hProcess != NULL)
	    {
		int error = 1;
		if (GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, arg->dwPid))
		{
		    if (WaitForSingleObject(arg->hProcess, 500) == WAIT_OBJECT_0)
			error = 0;
		}
		if (error)
		{
		    if (!SafeTerminateProcess(arg->hProcess, 10000015))
		    {
			if (GetLastError() != ERROR_PROCESS_ABORTED)
			    TerminateProcess(arg->hProcess, 1);
		    }
		}
	    }
	}
	else
	{
	    if (dwRetVal != WAIT_TIMEOUT)
	    {
		err_printf("error %d\n", GetLastError());
		goto QUIT_REDIRECTION;
	    }
	}
    }

QUIT_REDIRECTION:
    CloseHandle(hReadEvents[0]);
    CloseHandle(hReadEvents[1]);
    if (arg->bReadisPipe)
	CloseHandle(arg->hRead);
    if (arg->bWriteisPipe)
	CloseHandle(arg->hWrite);
    if (arg->sockRead != INVALID_SOCKET)
	easy_closesocket(arg->sockRead);
    if (arg->sockWrite != INVALID_SOCKET)
	easy_closesocket(arg->sockWrite);
    delete arg;
}