コード例 #1
0
ファイル: ShellcodeUtils.cpp プロジェクト: amohanta/pwnypot
STATUS
ShuDumpShellcode(
	IN PVOID Address
	)
{
	LPVOID	lpStartAddress;
	LPVOID	lpEndAddress;
	CHAR szLogPath[MAX_PATH];
	CHAR szShellcodeFile[MAX_PATH];
	BYTE *ShellcodeDump;
	DWORD dwRead;
	DWORD dwWrite;
	ERRORINFO err;
	HANDLE hShellcodeFile;
	STATUS status;

	lpStartAddress	= Address;
	lpEndAddress	= Address;
	ShellcodeDump	= (BYTE *)LocalAlloc(LMEM_ZEROINIT, 2048);

	/* IsBadReadPtr sucks so I have to validate memory readability by ReadProcessMemory */
	while ( ReadProcessMemory( GetCurrentProcess(), 
                               (LPVOID)((DWORD)lpStartAddress - 4),
		                       ShellcodeDump,
		                       4,
		                       &dwRead) 
		    && ((DWORD)Address - (DWORD)lpStartAddress) < 0x200 )
	{
		lpStartAddress = (LPVOID)((DWORD)lpStartAddress - 4);
	}

	while ( ReadProcessMemory( GetCurrentProcess(),
		                       (LPVOID)((DWORD)lpEndAddress + 4),
			                   ShellcodeDump,
			                   4,
			                   &dwRead) 
			&& ((DWORD)lpEndAddress - (DWORD)Address) < 0x200)
	{
		lpEndAddress = (LPVOID)((DWORD)lpEndAddress + 4);
	}

	sprintf(szShellcodeFile, "\\Shellcode.bin");
	strncpy( szLogPath, MCEDP_REGCONFIG.LOG_PATH, MAX_PATH);
	strncat(szLogPath, szShellcodeFile, MAX_PATH);

    /* Dump shellcode from memory */
	ReadProcessMemory( GetCurrentProcess(),
		               lpStartAddress,
					   ShellcodeDump,
					   ((DWORD)lpEndAddress - (DWORD)lpStartAddress),
					   &dwRead);

	if ( dwRead != ((DWORD)lpEndAddress - (DWORD)lpStartAddress) )
	{
		REPORT_ERROR("ReadProcessMemory()", &err);
		LocalFree(ShellcodeDump);
		return MCEDP_STATUS_INTERNAL_ERROR;
	}

	hShellcodeFile = CreateFile( szLogPath,
		                         GENERIC_WRITE,
								 0,
								 NULL,
								 CREATE_ALWAYS,
								 FILE_ATTRIBUTE_NORMAL,
								 NULL);

	if ( hShellcodeFile == INVALID_HANDLE_VALUE )
	{
		REPORT_ERROR("CreateFile()", &err);
		LocalFree(ShellcodeDump);
		return MCEDP_STATUS_INTERNAL_ERROR;	
	}

	WriteFile( hShellcodeFile, 
		       ShellcodeDump,
			   dwRead,
			   &dwWrite,
			   NULL);

	if ( dwRead != dwWrite )
	{
		REPORT_ERROR("WriteFile()", &err);
		LocalFree(ShellcodeDump);
		CloseHandle(hShellcodeFile);
		return MCEDP_STATUS_INTERNAL_ERROR;
	}

	DEBUG_PRINTF(LDBG, NULL, "Shellcode Dumped from (0x%p -- 0x%p) Size ( 0x%p )\n", lpStartAddress, lpEndAddress, ((DWORD)lpEndAddress - (DWORD)lpStartAddress));

    /* log and dump disassembled version of in-memory shelloce */
	status = ShuDisassembleShellcode( lpStartAddress, lpStartAddress, ((DWORD)lpEndAddress - (DWORD)lpStartAddress));
	if ( status == MCEDP_STATUS_SUCCESS )
		DEBUG_PRINTF(LDBG, NULL, "Shellcode disassembled successfully!\n");
	else if ( status == MCEDP_STATUS_PARTIAL_DISASSEMBLE )
		DEBUG_PRINTF(LDBG, NULL, "Only a part of Shellcode disassembled successfully!\n");
	else
		DEBUG_PRINTF(LDBG, NULL, "Faild to disassemble Shellcode!\n");

	LocalFree(ShellcodeDump);
	CloseHandle(hShellcodeFile);
	return MCEDP_STATUS_SUCCESS;
}
コード例 #2
0
LIBFREESPACE_API int freespace_openDevice(FreespaceDeviceId id) {
    int idx;
    struct FreespaceDeviceStruct* device = freespace_private_getDeviceById(id);
    if (device == NULL) {
        return FREESPACE_ERROR_NO_DEVICE;
    }

    if (device->isOpened_) {
        // Each device can only be opened once.
        return FREESPACE_ERROR_BUSY;
    }


    for (idx = 0; idx < device->handleCount_; idx++) {
        struct FreespaceSubStruct* s = &device->handle_[idx];
        if (s->handle_ != NULL) {
            // Device was partially (incorrectly) opened.
            freespace_private_forceCloseDevice(device);
            return FREESPACE_ERROR_BUSY;
        }
        if (s->devicePath == NULL) {
            // Device was not fully enumerated.
            freespace_private_forceCloseDevice(device);
            return FREESPACE_ERROR_NO_DEVICE;
        }
        DEBUG_WPRINTF(L"Open %s\n", s->devicePath);
        s->handle_ = CreateFile(s->devicePath,
                                GENERIC_READ | GENERIC_WRITE,
                                FILE_SHARE_READ | FILE_SHARE_WRITE,
                                NULL,
                                OPEN_EXISTING,
                                FILE_FLAG_OVERLAPPED,
                                NULL);
        {
            DWORD d;
            if (!GetHandleInformation(s->handle_, &d)) {
                // We do not have the correct handle.
                DEBUG_PRINTF("freespace_openDevice failed with code %d\n", GetLastError());
            }
        }

        if (s->handle_ == INVALID_HANDLE_VALUE) {
            freespace_private_forceCloseDevice(device);
            return FREESPACE_ERROR_NO_DEVICE;
        }

        if (!BindIoCompletionCallback(s->handle_, freespace_private_overlappedCallback, 0)) {
            freespace_private_forceCloseDevice(device);
            return FREESPACE_ERROR_UNEXPECTED;
        }

        if (!HidD_SetNumInputBuffers(s->handle_, HID_NUM_INPUT_BUFFERS)) {
            freespace_private_forceCloseDevice(device);
            return FREESPACE_ERROR_NO_DEVICE;
        }

        // Create the read event.
        s->readOverlapped_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
        if (s->readOverlapped_.hEvent == NULL) {
            freespace_private_forceCloseDevice(device);
            return FREESPACE_ERROR_UNEXPECTED;
        }
        s->readOverlapped_.Offset = 0;
        s->readOverlapped_.OffsetHigh = 0;
        s->readStatus_ = FALSE;
    }

    device->isOpened_ = TRUE;

    // Enable send by initializing all send events.
    for (idx = 0; idx < FREESPACE_MAXIMUM_SEND_MESSAGE_COUNT; idx++) {
        device->send_[idx].overlapped_.hEvent = NULL;
        if (initializeSendStruct(&device->send_[idx]) != FREESPACE_SUCCESS) {
            freespace_private_forceCloseDevice(device);
            return FREESPACE_ERROR_UNEXPECTED;
        }
    }

    // If async mode has been enabled already, then start the receive
    // process going.
    if (freespace_instance_->fdAddedCallback_) {
        int rc;
        rc = initiateAsyncReceives(device);
        if (rc != FREESPACE_SUCCESS) {
            freespace_private_forceCloseDevice(device);
            return rc;
        }
    }

    return FREESPACE_SUCCESS;
}
コード例 #3
0
int freespace_private_read(FreespaceDeviceId id,
                           uint8_t* message,
                           int maxLength,
                           unsigned int timeoutMs,
                           int* actualLength) {

    HANDLE waitEvents[FREESPACE_HANDLE_COUNT_MAX];
    int idx;
    DWORD bResult;

    struct FreespaceDeviceStruct* device = freespace_private_getDeviceById(id);
    if (device == NULL) {
        return FREESPACE_ERROR_NO_DEVICE;
    }

    // Start the reads going.
    for (idx = 0; idx < device->handleCount_; idx++) {
        BOOL bResult;
        struct FreespaceSubStruct* s = &device->handle_[idx];
        waitEvents[idx] = s->readOverlapped_.hEvent;

        // Initiate a ReadFile on anything that doesn't already have
        // a ReadFile op pending.
        if (!s->readStatus_) {
            int lastErr;
            bResult = ReadFile(
                               s->handle_,                 /* handle to device */
                               s->readBuffer,              /* IN report buffer to fill */
                               s->info_.inputReportByteLength_,  /* input buffer size */
                               &s->readBufferSize,         /* returned buffer size */
                               &s->readOverlapped_ );      /* long pointer to an OVERLAPPED structure */
            lastErr = GetLastError();
            if (bResult) {
                // Got something immediately, so return it.
                *actualLength = min(s->readBufferSize, (unsigned long) maxLength);
                memcpy(message, s->readBuffer, *actualLength);
                return FREESPACE_SUCCESS;
            } else if (lastErr != ERROR_IO_PENDING) {
                // Something severe happened to our device!
                DEBUG_PRINTF("freespace_read 1: Error on %d : %d\n", idx, lastErr);
                return handleDeviceFailure(device, lastErr);
            }
            s->readStatus_ = TRUE;
        }
    }

    // Wait.
    bResult = WaitForMultipleObjects(device->handleCount_, waitEvents, FALSE, timeoutMs);
    if (bResult == WAIT_FAILED) {
        DEBUG_PRINTF("Error from WaitForMultipleObjects\n");
        return FREESPACE_ERROR_IO;
    } else if (bResult == WAIT_TIMEOUT) {
        return FREESPACE_ERROR_TIMEOUT;
    }

    // Check which read worked.
    for (idx = 0; idx < device->handleCount_; idx++) {
        int lastErr;
        struct FreespaceSubStruct* s = &device->handle_[idx];
        BOOL bResult = GetOverlappedResult(
                                           s->handle_,                 /* handle to device */
                                           &s->readOverlapped_,        /* long pointer to an OVERLAPPED structure */
                                           &s->readBufferSize,         /* returned buffer size */
                                           FALSE);
        lastErr = GetLastError();
        if (bResult) {
            // Got something, so report it.
            *actualLength = min(s->readBufferSize, (unsigned long) maxLength);
            memcpy(message, s->readBuffer, *actualLength);
            s->readStatus_ = FALSE;
            return FREESPACE_SUCCESS;
        } else if (lastErr != ERROR_IO_INCOMPLETE) {
            // Something severe happened to our device!
            DEBUG_PRINTF("freespace_read 2 : Error on %d : %d\n", idx, lastErr);
            return handleDeviceFailure(device, lastErr);
        }
    }

    return FREESPACE_ERROR_IO;
}
コード例 #4
0
/**
 @brief test task
  Runs corrected cube demo from Sem
  Optionally wireframe Earh viewer
 @return void
*/
LOCAL void user_task(void)
{
	uint32_t time1,time2;
	uint8_t red, blue,green;
	long timer = 0;
	uint16 system_adc_read(void);
	extern uint8_t ip_msg[];
	time_t sec;
	char buffer[256];


	

#ifdef WIRECUBE
	V.x = degree;
	V.y = degree;
	V.z = degree;
// Cube points were defined with sides of 1.0 
// We want a scale of +/- w/2
	wire_draw(windemo, cube_points, cube_edges, &V, windemo->w/2, windemo->h/2, dscale, 0);
	//wire_draw(windemo, cube_points, cube_edges, &V, windemo->w/2, windemo->h/2, dscale, 0);
#endif

#ifdef CIRCLE
	rad = dscale; // +/- 90
    tft_drawCircle(windemo, windemo->w/2, windemo->h/2, rad ,0);
	Display bounding circle that changes color around the cube
	if(dscale_inc < 0.0)
	{
		red = 255;
		blue = 0;
		green = 0;
	}
	else
	{
		red = 0;
		blue = 255;
		green = 0;
	}
	// RGB - YELLOW
    tft_drawCircle(windemo, windemo->w/2, windemo->h/2, dscale, tft_color565(red,green,blue));
#endif

    degree += deg_inc;
    dscale += dscale_inc;

	if(degree <= -360)
		deg_inc = 4;
	if(degree >= 360)
		deg_inc = -4;

    if(dscale < dscale_max/2)
	{
	   dscale_inc = -dscale_inc;
	}
    if(dscale > dscale_max)
	{
	   dscale_inc = -dscale_inc;
	}


#ifdef WIRECUBE
	V.x = degree;
	V.y = degree;
	V.z = degree;
	//time1 = system_get_time();
	wire_draw(windemo, cube_points, cube_edges, &V, windemo->w/2, windemo->h/2, dscale, ILI9341_WHITE);
	//wire_draw(windemo, cube_points, cube_edges, &V, windemo->w/2, windemo->h/2, dscale, ILI9341_WHITE);
	//time2 = system_get_time();
#endif


// Get system voltage 33 = 3.3 volts
	adc_sum += system_adc_read();
	//adc_sum += system_get_vdd33();

	// FIXME atomic access
	if(++adc_count == 10)
	{
		voltage = ((double) adc_sum / 100.0); 
		adc_count = 0;
		adc_sum = 0;
	}

	// DEBUG_PRINTF("Degree: %d \r\n",(int)degree);
	// cube redraw count
	count += 1;
	tft_set_font(winstats,0);
	tft_setpos(winstats,ip_xpos,ip_ypos);
	tft_printf(winstats,"%-26s\n", ip_msg);
	if(!signal_loop--)
	{
		signal_loop = 100;
		tft_printf(winstats,"CH:%02d, DB:-%02d\n", 
			wifi_get_channel(),
			wifi_station_get_rssi());
		signal_loop = 0;
	}
	tft_setpos(winstats,xpos,ypos);
	tft_printf(winstats,"Heap: %d\n", system_get_free_heap_size());
	tft_printf(winstats,"Iter:% 9ld, %+7.2f\n", count, degree);
	
	// NTP state machine
	ntp_setup();

	// get current time
	time(&sec);

	tft_printf(winstats,"Volt:%2.2f\n%s\n", (float)voltage, ctime(&sec));
	
#ifdef NETWORK_TEST
	poll_network_message(wintest);
#endif

// Buffered get line uses interrupts and queues
	if(uart0_gets(buffer,255))
	{
		DEBUG_PRINTF("Command:%s\n",buffer);
		if(!fatfs_tests(buffer))
		{
			if(!user_tests(buffer))
			{
				DEBUG_PRINTF("unknow command: %s\n", buffer);
			}
		}
	}
}
コード例 #5
0
static int initiateAsyncReceives(struct FreespaceDeviceStruct* device) {
    int idx;
    int funcRc = FREESPACE_SUCCESS;
    int rc;
	struct freespace_message m;

    // If no callback or not opened, then don't need to request to receive anything.
    if (!device->isOpened_ || (device->receiveCallback_ == NULL && device->receiveMessageCallback_ == NULL)) {
        return FREESPACE_SUCCESS;
    }

    // Initialize a new read operation on all handles that need it.
    for (idx = 0; idx < device->handleCount_; idx++) {
        struct FreespaceSubStruct* s = &device->handle_[idx];
        if (!s->readStatus_) {
            for (;;) {
                BOOL bResult = ReadFile(
					s->handle_,                 /* handle to device */
					s->readBuffer,              /* IN report buffer to fill */
					s->info_.inputReportByteLength_,  /* input buffer size */
					&s->readBufferSize,         /* returned buffer size */
					&s->readOverlapped_ );      /* long pointer to an OVERLAPPED structure */
                if (bResult) {
                    // Got something, so report it.
					if (device->receiveCallback_ || device->receiveMessageCallback_) {
						if (device->receiveCallback_) {
							device->receiveCallback_(device->id_, (char *) (s->readBuffer), s->readBufferSize, device->receiveCookie_, FREESPACE_SUCCESS);
						}
						if (device->receiveMessageCallback_) {
							rc = freespace_decode_message((char *) (s->readBuffer), s->readBufferSize, &m, device->hVer_);
							if (rc == FREESPACE_SUCCESS) {
								device->receiveMessageCallback_(device->id_, &m, device->receiveMessageCookie_, FREESPACE_SUCCESS);
							} else {
								device->receiveMessageCallback_(device->id_, NULL, device->receiveMessageCookie_, rc);
								DEBUG_PRINTF("freespace_decode_message failed with code %d\n", rc);
							}
						}
					} else {
                        // If no receiveCallback, then freespace_setReceiveCallback was called to stop
                        // receives from within the receiveCallback. Bail out to let it do its thing.
                        return FREESPACE_SUCCESS;
                    }
                } else {
                    // Error or would block - check below.
                    break;
                }
            }

            rc = GetLastError();
            if (rc == ERROR_IO_PENDING) {
                // We got a ReadFile to block, so mark it.
                s->readStatus_ = TRUE;
            } else {
                // Something severe happened to our device!
				if (device->receiveCallback_) {
				    device->receiveCallback_(device->id_, NULL, 0, device->receiveCookie_, rc);
				}
				if (device->receiveMessageCallback_) {
				    device->receiveMessageCallback_(device->id_, NULL, device->receiveMessageCookie_, rc);
				}
                DEBUG_PRINTF("initiateAsyncReceives : Error on %d : %d\n", idx, rc);
                return handleDeviceFailure(device, rc);
            }
        }
    }

    return funcRc;
}
コード例 #6
0
ファイル: ubasic.c プロジェクト: EtchedPixels/ubasic
/*---------------------------------------------------------------------------*/
static uint8_t statement(void)
{
  int token;

  string_temp_free();

  token = current_token;
  /* LET may be omitted.. */
  if (token != TOKENIZER_INTVAR && token != TOKENIZER_STRINGVAR)
    accept_tok(token);

  switch(token) {
  case TOKENIZER_QUESTION:
  case TOKENIZER_PRINT:
    print_statement();
    break;
  case TOKENIZER_IF:
    if_statement();
    break;
  case TOKENIZER_GO:
    go_statement();
    return 0;
  case TOKENIZER_RETURN:
    return_statement();
    break;
  case TOKENIZER_FOR:
    for_statement();
    break;
  case TOKENIZER_POKE:
    poke_statement();
    break;
  case TOKENIZER_NEXT:
    next_statement();
    break;
  case TOKENIZER_STOP:
    stop_statement();
    break;
  case TOKENIZER_REM:
    rem_statement();
    break;
  case TOKENIZER_DATA:
    data_statement();
    break;
  case TOKENIZER_RANDOMIZE:
    randomize_statement();
    break;
  case TOKENIZER_OPTION:
    option_statement();
    break;
  case TOKENIZER_INPUT:
    input_statement();
    break;
  case TOKENIZER_RESTORE:
    restore_statement();
    break;
  case TOKENIZER_DIM:
    dim_statement();
    break;
  case TOKENIZER_CLS:
    cls_statement();
    break;
  case TOKENIZER_LET:
  case TOKENIZER_STRINGVAR:
  case TOKENIZER_INTVAR:
    let_statement();
    break;
  default:
    DEBUG_PRINTF("ubasic.c: statement(): not implemented %d\n", token);
    syntax_error();
  }
  return 1;
}
コード例 #7
0
ファイル: ubasic.c プロジェクト: EtchedPixels/ubasic
/*---------------------------------------------------------------------------*/
static void relation(struct typevalue *r1)
{
  struct typevalue r2;
  int op;

  mathexpr(r1);
  op = current_token;
  DEBUG_PRINTF("relation: token %d\n", op);
  /* FIXME: unclear the while is correct here. It's not correct in most
     BASIC to write  A > B > C, rather relations should be two part linked
     with logic */
  while(op == TOKENIZER_LT ||
       op == TOKENIZER_GT ||
       op == TOKENIZER_EQ ||
       op == TOKENIZER_NE ||
       op == TOKENIZER_LE ||
       op == TOKENIZER_GE) {
    tokenizer_next();
    mathexpr(&r2);
    typecheck_same(r1, &r2);
    DEBUG_PRINTF("relation: %d %d %d\n", r1->d.i, op, r2.d.i);
    if (r1->type == TYPE_INTEGER) {
      switch(op) {
      case TOKENIZER_LT:
        r1->d.i = r1->d.i < r2.d.i;
        break;
      case TOKENIZER_GT:
        r1->d.i = r1->d.i > r2.d.i;
        break;
      case TOKENIZER_EQ:
        r1->d.i = r1->d.i == r2.d.i;
        break;
      case TOKENIZER_LE:
        r1->d.i = r1->d.i <= r2.d.i;
        break;
      case TOKENIZER_GE:
        r1->d.i = r1->d.i >= r2.d.i;
        break;
      case TOKENIZER_NE:
        r1->d.i = r1->d.i != r2.d.i;
        break;
      }
    } else {
      int n =*r1->d.p;
      if (*r2.d.p < n)
        n = *r2.d.p;
      n = memcmp(r1->d.p + 1, r2.d.p + 1, n);
      if (n == 0) {
        if (*r1->d.p > *r2.d.p)
          n = 1;
        else if (*r1->d.p < *r2.d.p)
          n = -1;
      }
      switch(op) {
        case TOKENIZER_LT:
          n = (n == -1);
          break;
        case TOKENIZER_GT:
          n = (n == 1);
          break;
        case TOKENIZER_EQ:
          n = (n == 0);
          break;
        case TOKENIZER_LE:
          n = (n != 1);
          break;
        case TOKENIZER_GE:
          n = (n != -1);
          break;
        case TOKENIZER_NE:
          n = (n != 0);
          break;
      }
      r1->d.i = n;
    }
    op = current_token;
  }
  r1->type = TYPE_INTEGER;
}
コード例 #8
0
ファイル: ng_squash.cpp プロジェクト: 0x4e38/hyperscan
map<NFAVertex, NFAStateSet> findSquashers(const NGHolder &g, som_type som) {
    map<NFAVertex, NFAStateSet> squash;

    // Number of bits to use for all our masks. If we're a triggered graph,
    // tops have already been assigned, so we don't have to account for them.
    const u32 numStates = num_vertices(g);

    // Build post-dominator tree.
    PostDomTree pdom_tree;
    buildPDomTree(g, pdom_tree);

    // Build list of vertices by state ID and a set of init states.
    vector<NFAVertex> vByIndex(numStates, NFAGraph::null_vertex());
    NFAStateSet initStates(numStates);
    smgb_cache cache(g);

    // Mappings used for SOM mode calculations, otherwise left empty.
    unordered_map<NFAVertex, u32> region_map;
    vector<DepthMinMax> som_depths;
    if (som) {
        region_map = assignRegions(g);
        som_depths = getDistancesFromSOM(g);
    }

    for (auto v : vertices_range(g)) {
        const u32 vert_id = g[v].index;
        DEBUG_PRINTF("vertex %u/%u\n", vert_id, numStates);
        assert(vert_id < numStates);
        vByIndex[vert_id] = v;

        if (is_any_start(v, g) || !in_degree(v, g)) {
            initStates.set(vert_id);
        }
    }

    for (u32 i = 0; i < numStates; i++) {
        NFAVertex v = vByIndex[i];
        assert(v != NFAGraph::null_vertex());
        const CharReach &cr = g[v].char_reach;

        /* only non-init cyclics can be squashers */
        if (!hasSelfLoop(v, g) || initStates.test(i)) {
            continue;
        }

        DEBUG_PRINTF("state %u is cyclic\n", i);

        NFAStateSet mask(numStates), succ(numStates), pred(numStates);
        buildSquashMask(mask, g, v, cr, initStates, vByIndex, pdom_tree, som,
                        som_depths, region_map, cache);
        buildSucc(succ, g, v);
        buildPred(pred, g, v);
        const auto &reports = g[v].reports;

        for (size_t j = succ.find_first(); j != succ.npos;
             j = succ.find_next(j)) {
            NFAVertex vj = vByIndex[j];
            NFAStateSet pred2(numStates);
            buildPred(pred2, g, vj);
            if (pred2 == pred) {
                DEBUG_PRINTF("adding the sm from %zu to %u's sm\n", j, i);
                NFAStateSet tmp(numStates);
                buildSquashMask(tmp, g, vj, cr, initStates, vByIndex, pdom_tree,
                                som, som_depths, region_map, cache);
                mask &= tmp;
            }
        }

        for (size_t j = pred.find_first(); j != pred.npos;
             j = pred.find_next(j)) {
            NFAVertex vj = vByIndex[j];
            NFAStateSet succ2(numStates);
            buildSucc(succ2, g, vj);
            /* we can use j as a basis for squashing if its succs are a subset
             * of ours */
            if ((succ2 & ~succ).any()) {
                continue;
            }

            if (som) {
                /* We cannot use j to add to the squash mask of v if it may
                 * have an earlier start of match offset. ie for us j as a
                 * basis for the squash mask of v we require:
                 * maxSomDist(j) <= minSomDist(v)
                 */

                /* ** TODO ** */

                const depth &max_som_dist_j =
                    som_depths[g[vj].index].max;
                const depth &min_som_dist_v =
                    som_depths[g[v].index].min;
                if (max_som_dist_j > min_som_dist_v ||
                    max_som_dist_j.is_infinite()) {
                    /* j can't be used as it may be storing an earlier SOM */
                    continue;
                }
            }

            const CharReach &crv = g[vj].char_reach;

            /* we also require that j's report information be a subset of ours
             */
            bool seen_special = false;
            for (auto w : adjacent_vertices_range(vj, g)) {
                if (is_special(w, g)) {
                    if (!edge(v, w, g).second) {
                        goto next_j;
                    }
                    seen_special = true;
                }
            }

            // FIXME: should be subset check?
            if (seen_special && g[vj].reports != reports) {
                continue;
            }

            /* ok we can use j */
            if ((crv & ~cr).none()) {
                NFAStateSet tmp(numStates);
                buildSquashMask(tmp, g, vj, cr, initStates, vByIndex, pdom_tree,
                                som, som_depths, region_map, cache);
                mask &= tmp;
                mask.reset(j);
            }

        next_j:;
        }

        mask.set(i); /* never clear ourselves */

        if ((~mask).any()) { // i.e. some bits unset in mask
            DEBUG_PRINTF("%u squashes %zu other states\n", i, (~mask).count());
            squash.emplace(v, mask);
        }
    }

    findDerivedSquashers(g, vByIndex, pdom_tree, initStates, &squash, som,
                         som_depths, region_map, cache);

    return squash;
}
コード例 #9
0
ファイル: ftpfs.c プロジェクト: aniwang2013/leon-rtems
static int rtems_ftpfs_open_ctrl_connection(
  rtems_ftpfs_entry *e,
  const char *user,
  const char *password,
  const char *hostname,
  uint32_t *client_address,
  bool verbose,
  const struct timeval *timeout
)
{
  int rv = 0;
  int eno = 0;
  rtems_ftpfs_reply reply = RTEMS_FTPFS_REPLY_ERROR;
  struct in_addr address = { .s_addr = 0 };
  struct sockaddr_in sa;
  socklen_t size = 0;

  /* Create the socket for the control connection */
  e->ctrl_socket = socket(AF_INET, SOCK_STREAM, 0);
  if (e->ctrl_socket < 0) {
    return ENOMEM;
  }

  /* Set up the server address from the hostname */
  if (inet_aton(hostname, &address) == 0) {
    /* Try to get the address by name */
    struct hostent *he = gethostbyname(hostname);

    if (he != NULL) {
      memcpy(&address, he->h_addr, sizeof(address));
    } else {
      return ENOENT;
    }
  }
  rtems_ftpfs_create_address(&sa, address.s_addr, htons(RTEMS_FTPFS_CTRL_PORT));
  DEBUG_PRINTF("server = %s\n", inet_ntoa(sa.sin_addr));

  /* Open control connection */
  rv = connect(
    e->ctrl_socket,
    (struct sockaddr *) &sa,
    sizeof(sa)
  );
  if (rv != 0) {
    return ENOENT;
  }

  /* Set control connection timeout */
  eno = rtems_ftpfs_set_connection_timeout(e->ctrl_socket, timeout);
  if (eno != 0) {
    return eno;
  }

  /* Get client address */
  size = rtems_ftpfs_create_address(&sa, INADDR_ANY, 0);
  rv = getsockname(
    e->ctrl_socket,
    (struct sockaddr *) &sa,
    &size
  );
  if (rv != 0) {
    return ENOMEM;
  }
  *client_address = ntohl(sa.sin_addr.s_addr);
  DEBUG_PRINTF("client = %s\n", inet_ntoa(sa.sin_addr));

  /* Now we should get a welcome message from the server */
  reply = rtems_ftpfs_get_reply(e, NULL, NULL, verbose);
  if (reply != RTEMS_FTPFS_REPLY_2) {
    return ENOENT;
  }

  /* Send USER command */
  reply = rtems_ftpfs_send_command(e, "USER ", user, verbose);
  if (reply == RTEMS_FTPFS_REPLY_3) {
    /* Send PASS command */
    reply = rtems_ftpfs_send_command(e, "PASS ", password, verbose);
    if (reply != RTEMS_FTPFS_REPLY_2) {
      return EACCES;
    }

    /* TODO: Some server may require an account */
  } else if (reply != RTEMS_FTPFS_REPLY_2) {
    return EACCES;
  }

  /* Send TYPE command to set binary mode for all data transfers */
  reply = rtems_ftpfs_send_command(e, "TYPE I", NULL, verbose);
  if (reply != RTEMS_FTPFS_REPLY_2) {
    return EIO;
  }

  return 0;
}

static int rtems_ftpfs_open_data_connection_active(
  rtems_ftpfs_entry *e,
  uint32_t client_address,
  const char *file_command,
  const char *filename,
  bool verbose,
  const struct timeval *timeout
)
{
  int rv = 0;
  int eno = 0;
  rtems_ftpfs_reply reply = RTEMS_FTPFS_REPLY_ERROR;
  struct sockaddr_in sa;
  socklen_t size = 0;
  int port_socket = -1;
  char port_command [] = "PORT 000,000,000,000,000,000";
  uint16_t data_port = 0;

  /* Create port socket to establish a data data connection */
  port_socket = socket(AF_INET, SOCK_STREAM, 0);
  if (port_socket < 0) {
    eno = ENOMEM;
    goto cleanup;
  }

  /* Bind port socket */
  rtems_ftpfs_create_address(&sa, INADDR_ANY, 0);
  rv = bind(
    port_socket,
    (struct sockaddr *) &sa,
    sizeof(sa)
  );
  if (rv != 0) {
    eno = EBUSY;
    goto cleanup;
  }

  /* Get port number for data socket */
  size = rtems_ftpfs_create_address(&sa, INADDR_ANY, 0);
  rv = getsockname(
    port_socket,
    (struct sockaddr *) &sa,
    &size
  );
  if (rv != 0) {
    eno = ENOMEM;
    goto cleanup;
  }
  data_port = ntohs(sa.sin_port);

  /* Send PORT command to set data connection port for server */
  snprintf(
    port_command,
    sizeof(port_command),
    "PORT %lu,%lu,%lu,%lu,%lu,%lu",
    (client_address >> 24) & 0xffUL,
    (client_address >> 16) & 0xffUL,
    (client_address >> 8) & 0xffUL,
    (client_address >> 0) & 0xffUL,
    (data_port >> 8) & 0xffUL,
    (data_port >> 0) & 0xffUL
  );
  reply = rtems_ftpfs_send_command(e, port_command, NULL, verbose);
  if (reply != RTEMS_FTPFS_REPLY_2) {
    eno = ENOTSUP;
    goto cleanup;
  }

  /* Listen on port socket for incoming data connections */
  rv = listen(port_socket, 1);
  if (rv != 0) {
    eno = EBUSY;
    goto cleanup;
  }

  /* Send RETR or STOR command with filename */
  reply = rtems_ftpfs_send_command(e, file_command, filename, verbose);
  if (reply != RTEMS_FTPFS_REPLY_1) {
    eno = EIO;
    goto cleanup;
  }

  /* Wait for connect on data connection if necessary */
  if (rtems_ftpfs_use_timeout(timeout)) {
    struct timeval to = *timeout;
    fd_set fds;

    FD_ZERO(&fds);
    FD_SET(port_socket, &fds);

    rv = select(port_socket + 1, &fds, NULL, NULL, &to);
    if (rv <= 0) {
      eno = EIO;
      goto cleanup;
    }
  }

  /* Accept data connection  */
  size = sizeof(sa);
  e->data_socket = accept(
    port_socket,
    (struct sockaddr *) &sa,
    &size
  );
  if (e->data_socket < 0) {
    eno = EIO;
    goto cleanup;
  }

cleanup:

  /* Close port socket if necessary */
  if (port_socket >= 0) {
    rv = close(port_socket);
    if (rv != 0) {
      eno = EIO;
    }
  }

  return eno;
}
コード例 #10
0
ファイル: tree.c プロジェクト: xuanvu/Carla
ZIX_API ZixStatus
zix_tree_remove(ZixTree* t, ZixTreeIter* ti)
{
	ZixTreeNode* const n          = ti;
	ZixTreeNode**      pp         = NULL;  // parent pointer
	ZixTreeNode*       to_balance = n->parent;  // lowest node to balance
	int8_t             d_balance  = 0;  // delta(balance) for n->parent

	DEBUG_PRINTF("*** REMOVE %ld\n", (intptr_t)n->data);

	if ((n == t->root) && !n->left && !n->right) {
		t->root = NULL;
		if (t->destroy) {
			t->destroy(n->data);
		}
		free(n);
		--t->size;
		assert(t->size == 0);
		return ZIX_STATUS_SUCCESS;
	}

	// Set pp to the parent pointer to n, if applicable
	if (n->parent) {
		assert(n->parent->left == n || n->parent->right == n);
		if (n->parent->left == n) {  // n is left child
			pp        = &n->parent->left;
			d_balance = 1;
		} else {  // n is right child
			assert(n->parent->right == n);
			pp        = &n->parent->right;
			d_balance = -1;
		}
	}

	assert(!pp || *pp == n);

	int height_change = 0;
	if (!n->left && !n->right) {
		// n is a leaf, just remove it
		if (pp) {
			*pp           = NULL;
			to_balance    = n->parent;
			height_change = (!n->parent->left && !n->parent->right) ? -1 : 0;
		}
	} else if (!n->left) {
		// Replace n with right (only) child
		if (pp) {
			*pp        = n->right;
			to_balance = n->parent;
		} else {
			t->root = n->right;
		}
		n->right->parent = n->parent;
		height_change    = -1;
	} else if (!n->right) {
		// Replace n with left (only) child
		if (pp) {
			*pp        = n->left;
			to_balance = n->parent;
		} else {
			t->root = n->left;
		}
		n->left->parent = n->parent;
		height_change   = -1;
	} else {
		// Replace n with in-order successor (leftmost child of right subtree)
		ZixTreeNode* replace = n->right;
		while (replace->left) {
			assert(replace->left->parent == replace);
			replace = replace->left;
		}

		// Remove replace from parent (replace_p)
		if (replace->parent->left == replace) {
			height_change = replace->parent->right ? 0 : -1;
			d_balance     = 1;
			to_balance    = replace->parent;
			replace->parent->left = replace->right;
		} else {
			assert(replace->parent == n);
			height_change = replace->parent->left ? 0 : -1;
			d_balance     = -1;
			to_balance    = replace->parent;
			replace->parent->right = replace->right;
		}

		if (to_balance == n) {
			to_balance = replace;
		}

		if (replace->right) {
			replace->right->parent = replace->parent;
		}

		replace->balance = n->balance;

		// Swap node to delete with replace
		if (pp) {
			*pp = replace;
		} else {
			assert(t->root == n);
			t->root = replace;
		}
		replace->parent = n->parent;
		replace->left   = n->left;
		n->left->parent = replace;
		replace->right  = n->right;
		if (n->right) {
			n->right->parent = replace;
		}

		assert(!replace->parent
		       || replace->parent->left == replace
		       || replace->parent->right == replace);
	}

	// Rebalance starting at to_balance upwards.
	for (ZixTreeNode* i = to_balance; i; i = i->parent) {
		i->balance += d_balance;
		if (d_balance == 0 || i->balance == -1 || i->balance == 1) {
			break;
		}

		assert(i != n);
		i = zix_tree_rebalance(t, i, &height_change);
		if (i->balance == 0) {
			height_change = -1;
		}

		if (i->parent) {
			if (i == i->parent->left) {
				d_balance = height_change * -1;
			} else {
				assert(i == i->parent->right);
				d_balance = height_change;
			}
		}
	}

	DUMP(t);

	if (t->destroy) {
		t->destroy(n->data);
	}
	free(n);

	--t->size;

#ifdef ZIX_TREE_VERIFY
	if (!verify(t, t->root)) {
		return ZIX_STATUS_ERROR;
	}
#endif

	return ZIX_STATUS_SUCCESS;
}
コード例 #11
0
ファイル: ng_squash.cpp プロジェクト: 0x4e38/hyperscan
/**
 * Builds a squash mask based on the pdom tree of v and the given char reach.
 * The built squash mask is a bit conservative for non-dot cases and could
 * be improved with a bit of thought.
 */
static
void buildSquashMask(NFAStateSet &mask, const NGHolder &g, NFAVertex v,
                     const CharReach &cr, const NFAStateSet &init,
                     const vector<NFAVertex> &vByIndex, const PostDomTree &tree,
                     som_type som, const vector<DepthMinMax> &som_depths,
                     const ue2::unordered_map<NFAVertex, u32> &region_map,
                     smgb_cache &cache) {
    DEBUG_PRINTF("build base squash mask for vertex %u)\n",
                 g[v].index);

    vector<NFAVertex> q;

    PostDomTree::const_iterator it = tree.find(v);
    if (it != tree.end()) {
        q.insert(q.end(), it->second.begin(), it->second.end());
    }

    const u32 v_index = g[v].index;

    while (!q.empty()) {
        NFAVertex u = q.back();
        q.pop_back();
        const CharReach &cru = g[u].char_reach;

        if ((cru & ~cr).any()) {
            /* bail: bad cr on vertex u */
            /* TODO: this could be better
             *
             * we still need to ensure that we record any paths leading to u.
             * Hence all vertices R which can reach u must be excluded from the
             * squash mask. Note: R != pdom(u) and there may exist an x in (R -
             * pdom(u)) which is in pdom(y) where y is in q. Clear ?
             */
            mask.set();
            return;
        }

        const u32 u_index = g[u].index;

        if (som) {
            /* We cannot add a state u to the squash mask of v if it may have an
             * earlier start of match offset. ie for us to add a state u to v
             * maxSomDist(u) <= minSomDist(v)
             */
            const depth &max_som_dist_u = som_depths[u_index].max;
            const depth &min_som_dist_v = som_depths[v_index].min;

            if (max_som_dist_u.is_infinite()) {
                /* it is hard to tell due to the INF if u can actually store an
                 * earlier SOM than w (state we are building the squash mask
                 * for) - need to think more deeply
                 */

                if (mustBeSetBefore(u, v, g, cache)
                    && !somMayGoBackwards(u, g, region_map, cache)) {
                    DEBUG_PRINTF("u %u v %u\n", u_index, v_index);
                    goto squash_ok;
                }
            }

           if (max_som_dist_u > min_som_dist_v) {
                /* u can't be squashed as it may be storing an earlier SOM */
                goto add_children_to_queue;
            }

        }

    squash_ok:
        mask.set(u_index);
        DEBUG_PRINTF("pdom'ed %u\n", u_index);
    add_children_to_queue:
        it = tree.find(u);
        if (it != tree.end()) {
            q.insert(q.end(), it->second.begin(), it->second.end());
        }
    }

    if (cr.all()) {
        /* the init states aren't in the pdom tree. If all their succ states
         * are set (or v), we can consider them post dominated */

        /* Note: init states will always result in a later som */
        for (size_t i = init.find_first(); i != init.npos;
             i = init.find_next(i)) {
            /* Yes vacuous patterns do exist */
            NFAVertex iv = vByIndex[i];
            for (auto w : adjacent_vertices_range(iv, g)) {
                if (w == g.accept || w == g.acceptEod) {
                    DEBUG_PRINTF("skipping %zu due to vacuous accept\n", i);
                    goto next_init_state;
                }

                u32 vert_id = g[w].index;
                if (w != iv && w != v && !mask.test(vert_id)) {
                    DEBUG_PRINTF("skipping %zu due to %u\n", i, vert_id);
                    goto next_init_state;
                }
            }
            DEBUG_PRINTF("pdom'ed %zu\n", i);
            mask.set(i);
        next_init_state:;
        }
    }

    mask.flip();
}
コード例 #12
0
ファイル: tree.c プロジェクト: xuanvu/Carla
ZIX_API ZixStatus
zix_tree_insert(ZixTree* t, void* e, ZixTreeIter** ti)
{
	DEBUG_PRINTF("**** INSERT %ld\n", (intptr_t)e);
	int          cmp = 0;
	ZixTreeNode* n   = t->root;
	ZixTreeNode* p   = NULL;

	// Find the parent p of e
	while (n) {
		p   = n;
		cmp = t->cmp(e, n->data, t->cmp_data);
		if (cmp < 0) {
			n = n->left;
		} else if (cmp > 0) {
			n = n->right;
		} else if (t->allow_duplicates) {
			n = n->right;
		} else {
			if (ti) {
				*ti = n;
			}
			DEBUG_PRINTF("%ld EXISTS!\n", (intptr_t)e);
			return ZIX_STATUS_EXISTS;
		}
	}

	// Allocate a new node n
	if (!(n = (ZixTreeNode*)malloc(sizeof(ZixTreeNode)))) {
		return ZIX_STATUS_NO_MEM;
	}
	memset(n, '\0', sizeof(ZixTreeNode));
	n->data    = e;
	n->balance = 0;
	if (ti) {
		*ti = n;
	}

	bool p_height_increased = false;

	// Make p the parent of n
	n->parent = p;
	if (!p) {
		t->root = n;
	} else {
		if (cmp < 0) {
			assert(!p->left);
			assert(p->balance == 0 || p->balance == 1);
			p->left = n;
			--p->balance;
			p_height_increased = !p->right;
		} else {
			assert(!p->right);
			assert(p->balance == 0 || p->balance == -1);
			p->right = n;
			++p->balance;
			p_height_increased = !p->left;
		}
	}

	DUMP(t);

	// Rebalance if necessary (at most 1 rotation)
	assert(!p || p->balance == -1 || p->balance == 0 || p->balance == 1);
	if (p && p_height_increased) {
		int height_change = 0;
		for (ZixTreeNode* i = p; i && i->parent; i = i->parent) {
			if (i == i->parent->left) {
				if (--i->parent->balance == -2) {
					zix_tree_rebalance(t, i->parent, &height_change);
					break;
				}
			} else {
				assert(i == i->parent->right);
				if (++i->parent->balance == 2) {
					zix_tree_rebalance(t, i->parent, &height_change);
					break;
				}
			}

			if (i->parent->balance == 0) {
				break;
			}
		}
	}

	DUMP(t);

	++t->size;

#ifdef ZIX_TREE_VERIFY
	if (!verify(t, t->root)) {
		return ZIX_STATUS_ERROR;
	}
#endif

	return ZIX_STATUS_SUCCESS;
}
コード例 #13
0
int cmodprint (MODEL *model){
    int i, j, n;
    struct MODEL_PATH *parent;
    char **names;
    FILE *f;
    int l;
    char *fname;
    VECTOR_3D size;
    VECTOR_3D centre;
    float radius;
    float rotate;
    char *movetype;
    VECTOR_3D min, max;

    /* We only want LOD0 */

    if (model->path.lod != 1){
        return 0;
    }

    /* We don't want destroyed stuff */

    if (strstr (model->path.name, "-destroyed")){
        return 0;
    }
    
    parent = &model->path;
    n = model->path.nr_parents;
    names = malloc ((n + 1) * sizeof(char *));
    ASSERT_PERROR (names != NULL, "Unable to allocate memory for model path");
    memset (names, 0, (n + 1) * sizeof(char *));

    parent = &model->path;
    l = 0;
    for (i = n; i >= 0; i--){
        names[i] = parent->name;
	DEBUG_PRINTF ("# Parent: %s\n", names[i]);
	l += strlen(names[i]) + 1;
        parent = parent->parent;
    }
    DEBUG_PRINTF ("# Length: %d\n", l);
    fname = malloc (l + 6);
    ASSERT_PERROR (fname != NULL, "Unable to allocate memory for model path");
    memset (fname, 0, l + 6);
    strcpy (fname, names[0]);
    for (i=2; i <= n; i++){
        strcat (fname, ".");
	strcat (fname, names[i]);
    }
    strcat (fname, ".cmod");
    free (names);
    f = fopen (fname, "wb");
    ASSERT_PERROR (f != NULL, "Unable to open output file");
    DEBUG_PRINTF ("# Starting model\n");
    fprintf (f, "#celmodel__ascii\n\n");
    fprintf (f, "# name: %s\n", fname);

    min = rotate_axis (model->min, model->axis);
    max = rotate_axis (model->max, model->axis);
    size.x = (model->max.x - model->min.x) / 2;
    size.y = (model->max.y - model->min.y) / 2;
    size.z = (model->max.z - model->min.z) / 2;
    centre.x = model->min.x + size.x;
    centre.y = model->min.y + size.y;
    centre.z = model->min.z + size.z;
    radius = size.x;
    radius = (size.y > radius) ? size.y : radius;
    radius = (size.z > radius) ? size.z : radius;
    switch (model->movetype){
        case -1: movetype = "None"; break;
	case 0: movetype = "Linear"; break;
	case 1: movetype = "Rotate"; break;
	case 2: movetype = "Turret"; break;
	default: movetype = "Unknown";
    }

    DEBUG_PRINTF ("# Geometric:\n"
                "# radius: %f\n"
		"# centre: [ %f %f %f ]\n"
		"# Celestia:\n"
		"# radius: %f\n"
		"# centre: [ %f %f %f ]\n"
		"# \n"
		"# offset: [ %f %f %f ]\n"
		"# axis: [ %f %f %f ]\n"
		"# movement: %s\n"
		"# Properties:\n", 
		model->radius,
		model->centre.z, model->centre.y, model->centre.x,
		radius, 
		centre.z, centre.y, centre.x,
		model->offset.z, model->offset.y, model->offset.x,
		model->axis.z, model->axis.y, model->axis.x,
		movetype);
    rotate = 8.64e24;
#ifdef DEBUGAXIS
    if (model->movetype == 1 || model->movetype == 2){
        rotate = 3.6;
    }
#endif
    DEBUG_PRINTF ("# Reading properties\n");
    for (i=0; i < model->nr_props; i++){
        fprintf (f, "#   %s\n", model->props[i]);
	if (!strncmp (model->props[i], "$rotate=", 8)){
	    rotate = strtod (model->props[i] + 8, NULL);
	}
    }

    DEBUG_PRINTF ("# Calculating orbital and rotational parameters\n");
    {
        float obliq, eqascnod;
	float rotofs = 0;
	float lat, lon, dist;
	VECTOR_3D a, c, o;

	a = model->axis;
	if (a.x == 0 && a.y == 0 && a.z == 0){
	    a.y = 1;
	}

	c = rotate_axis (centre, a);
	o = model->offset;
	dist = sqrt (a.x * a.x + a.y * a.y + a.z * a.z);
	a.x /= dist;
	a.y /= dist;
	a.z /= dist;
	obliq = asin(a.y);
	eqascnod = 0;
	if (isnan(obliq)){
	    obliq = (a.y < 0) ? -M_PI / 2 : M_PI / 2;
	}
	if (cos(obliq) > 0.0001){
	    if (cos(obliq) <= fabs(a.x)){
	        eqascnod = (a.x > 0) ? -M_PI / 2 : M_PI / 2;
	    } else {
	        eqascnod = -asin (a.x / cos(obliq));
	    }
	    if (isnan(eqascnod)){
	        eqascnod = (a.x > 0) ? -M_PI / 2 : M_PI / 2;
	    }
	}
	if (a.z < 0){
	    eqascnod = M_PI - eqascnod;
	}

	obliq = 90 - (obliq * 180 / M_PI);
	eqascnod *= 180 / M_PI;
	
	dist = sqrt (o.x * o.x + o.y * o.y + o.z * o.z);
	lat = lon = 0;
	if (dist > 0){
	    lat = asin (o.y / dist);
	    if (isnan(lat)){
	        lat = (o.y < 0) ? -M_PI / 2 : M_PI / 2;
	    }
	    if (cos(lat) <= fabs(o.x / dist)){
	        lon = (o.z > 0) ? -M_PI / 2 : M_PI / 2;
	    } else {
	        lon = -asin (o.z / dist / cos(lat));
	    }
	    if (isnan(lon)){
	        lon = (o.z > 0) ? -M_PI / 2 : M_PI / 2;
	    }
	}
	if (o.x > 0){
	    lon = M_PI - lon;
	}
	lat *= 180 / M_PI;
	lon *= 180 / M_PI;


	fprintf (f, "#\n"
	            "# Put this in your SSC file:\n"
	            "#\n");
	if (n <= 1){
	    fprintf (f, "##\"%%name%%\" \"%%parent%%\"\n"
			"##{\n"
			"##    Mesh \"%s\"\n"
			"##    MeshCenter [ %f %f %f ]\n"
			"##    Radius %f\n"
			"##    EllipticalOrbit {\n"
			"##        Period %%orbitperiod%%\n"
			"##        SemiMajorAxis %%orbitradius%%\n"
			"##        Eccentricity %%orbiteccentricity%%\n"
			"##        Inclination %%orbitinclination%%\n"
			"##        MeanAnomaly %%orbitmeananomaly%%\n"
			"##        AscendingNode %%orbitascendingnode%%\n"
			"##    }\n"
			"##    RotationPeriod 2.4e21\n"
			"##    Obliquity %%obliquity%%\n"
			"##    EquatorAscendingNode %%equatorascendingnode%%\n"
			"##}\n"
			"#\n",
			fname, -c.z, -c.y, -c.x, radius / 1000);
	} else {
	    fprintf (f, "##\"%s\" \"%%parent%%/%%name%%",
	             names[n]);
	    for (i=2; i < n; i++){
	        fprintf (f, "/%s", names[i]);
	    }
	    fprintf (f, "\"\n"
			"##{\n"
			"##    Mesh \"%s\"\n"
			"##    MeshCenter [ %f %f %f ]\n"
			"##    Radius %f\n"
			"##    EllipticalOrbit {\n"
			"##        Period 1e20\n"
			"##        SemiMajorAxis %f\n"
			"##        Eccentricity 0\n"
			"##        Inclination 90\n"
			"##        MeanAnomaly %f\n"
			"##        AscendingNode %f\n"
			"##    }\n"
			"###   FixedPosition [ %f %f %f ]\n"
			"##    RotationPeriod %g\n"
			"##    RotationOffset %f\n"
			"##    Obliquity %f\n"
			"##    EquatorAscendingNode %f\n"
			"##}\n"
			"#\n",
			fname,
			-c.z, -c.y, -c.x,
			radius / 1000,
			dist / 1000, lat, lon,
			o.z / 1000, 
			o.y / 1000,
			o.x / 1000,
			-rotate / 3600,
			rotofs, obliq, eqascnod);
	}
    }
    free (fname);
    DEBUG_PRINTF ("# Printing materials\n");
    fprintf (f, "\n");
    for (i=0; i<model->nr_mat; i++){
	RGBA c, e, s;
	float o, sp;
	char *em, *sm, *nm, *tm[4];
	DEBUG_PRINTF ("#  Material %d\n", i);
	c = model->mat[i].diffuse;
	e = model->mat[i].emissive;
	s = model->mat[i].specular;
	o = model->mat[i].opacity;
	sp = model->mat[i].specpower;
	em = model->mat[i].emissivemap;
	sm = model->mat[i].specularmap;
	nm = model->mat[i].normalmap;
	tm[0] = model->mat[i].texture[0];
	tm[1] = model->mat[i].texture[1];
	tm[2] = model->mat[i].texture[2];
	tm[3] = model->mat[i].texture[3];
        fprintf (f, "material # index %d\n", i);
	DEBUG_PRINTF ("#   Diffuse: %f %f %f\n", c.r, c.g, c.b);
	fprintf (f, " diffuse %f %f %f\n", c.r, c.g, c.b);
	DEBUG_PRINTF ("#   Opacity: %f\n", o);
	fprintf (f, " opacity %f\n", o);
        if (e.r != 0 || e.g != 0 || e.b != 0){
	    DEBUG_PRINTF ("#   Emissive: %f %f %f\n", e.r, e.g, e.b);
	    fprintf (f, " emissive %f %f %f\n", e.r, e.g, e.b);
	}
	if (s.r != 0 || s.g != 0 || s.b != 0){
	    DEBUG_PRINTF ("#   Specular: %f %f %f\n", s.r, s.g, s.b);
	    fprintf (f, " specular %f %f %f\n", s.r, s.g, s.b);
	}
	if (sp != 0){
	    DEBUG_PRINTF ("#   SpecPower: %f\n", sp);
	    fprintf (f, " specpower %f\n", sp);
	}
	if (tm[0] != NULL){
	    int te;
	    te = texture_exists (tm[0]);
	    DEBUG_PRINTF ("#   Texture0: %s\n", tm[0]);
	    fprintf (f, " texture0 \"%s.*\"\n", tm[0]);
	    if (em == NULL && (te & TEXTURE_GLOW) != 0){
	        DEBUG_PRINTF ("#   EmissiveMap: %s-glow\n", tm[0]);
	        fprintf (f, " emissivemap \"%s-glow.*\"\n", tm[0]);
	    } 
#if CELESTIAVERSION >= 150
	    if ((te & TEXTURE_SHINE) != 0){
		if (s.r == 0 && s.g == 0 && s.b == 0){
		    DEBUG_PRINTF ("#   Specular: [ 1 1 1 ]\n", tm[0]);
		    fprintf (f, " specular: [ 1 1 1 ]\n", tm[0]);
		}
		if (sp == 0){
		    DEBUG_PRINTF ("#   SpecPower: 1\n", tm[0]);
		    fprintf (f, " specpower: 1\n", tm[0]);
		}
		if (sm == NULL){
		    DEBUG_PRINTF ("#   SpecularMap: %s-shine\n", tm[0]);
		    fprintf (f, " specularmap \"%s-shine.*\"\n", tm[0]);
		} 
	    }
#endif
        }
	if (tm[1] != NULL){
	    DEBUG_PRINTF ("#   Texture1: %s\n", tm[1]);
	    fprintf (f, " texture1 \"%s.*\"\n", tm[1]);
	}
	if (tm[2] != NULL){
	    DEBUG_PRINTF ("#   Texture2: %s\n", tm[2]);
	    fprintf (f, " texture2 \"%s.*\"\n", tm[2]);
	}
	if (tm[3] != NULL){
	    DEBUG_PRINTF ("#   Texture3: %s\n", tm[3]);
	    fprintf (f, " texture3 \"%s.*\"\n", tm[3]);
	}
	if (em != NULL){
	    DEBUG_PRINTF ("#   EmissiveMap: %s\n", em);
	    fprintf (f, " emissivemap \"%s.*\"\n", em);
	}
#if CELESTIAVERSION >= 150
	if (sm != NULL){
	    DEBUG_PRINTF ("#   SpecularMap: %s\n", sm);
	    fprintf (f, " specularmap \"%s.*\"\n", sm);
	}
        if (nm != NULL){
	    DEBUG_PRINTF ("#   NormalMap: %s\n", nm);
	    fprintf (f, " normalmap \"%s.*\"\n", nm);
	}
#endif
	fprintf (f, "end_material\n\n");
    }
#ifdef DEBUGAXIS
    fprintf (f, "material\n"
                " emissive 1 0 0\n"
		" opacity 1\n"
		"end_material\n\n");
    fprintf (f, "material\n"
                " emissive 0 1 1\n"
		" opacity 1\n"
		"end_material\n\n");
    fprintf (f, "material\n"
                " emissive 0 1 0\n"
		" opacity 1\n"
		"end_material\n\n");
    fprintf (f, "material\n"
                " emissive 1 0 1\n"
		" opacity 1\n"
		"end_material\n\n");
    fprintf (f, "material\n"
                " emissive 0 0 1\n"
		" opacity 1\n"
		"end_material\n\n");
    fprintf (f, "material\n"
                " emissive 1 1 0\n"
		" opacity 1\n"
		"end_material\n\n");
#endif
    DEBUG_PRINTF ("# Printing Meshes\n");
    for (i=0; i < model->nr_mat; i++){
        int j;
	int n;
	POLY_VTX *v;
	VECTOR_3D a;

	a = model->axis;
	if (a.x == 0 && a.y == 0 && a.z == 0){
	    a.y = 1;
	}
	n = 0;
        for (j=0; j < model->nr_polyvtx; j++){
	    if (model->polyvtx[j].matn == i){
	        n++;
	    }
	}
	if (n == 0){
	    continue;
	}
	v = malloc (n * sizeof(POLY_VTX));
	ASSERT_PERROR (v != NULL, "Unable to allocate memory for polygons for mesh");
	memset (v, 0, n * sizeof(POLY_VTX));

        n = 0;

	for (j=0; j < model->nr_polyvtx; j++){
	    if (model->polyvtx[j].matn == i){
	        v[n] = model->polyvtx[j];
		n++;
	    }
	}       

	DEBUG_PRINTF ("#  Starting mesh %d\n", i);

	fprintf (f, "mesh\n"
	            "\n"
	            " vertexdesc\n"
	            "  position f3\n"
	            "  normal f3\n"
	            "  texcoord0 f2\n"
	            " end_vertexdesc\n"
		    "\n"
		    " vertices %d\n", n);
	for (j=0; j < n; j++){
	    VECTOR_3D vtx;
	    VECTOR_3D norm;
	    VECTOR_UV tex;

	    tex = v[j].vtx.tex;
	    vtx = rotate_axis (v[j].vtx.pos, a);
	    norm = rotate_axis (v[j].vtx.norm, a);

	    fprintf (f, "  %f %f %f %f %f %f %f %f\n",
		     vtx.z, vtx.y, vtx.x,
		     norm.z, norm.y, norm.x,
		     tex.u, tex.v);
	}
	DEBUG_PRINTF ("#   Vertices done\n");
	for (j=0; j < n; j+=v[j].nverts){
	    VECTOR_3D norm;
	    float t;
	    int line;
	    int vn;
            line = 0;
	    norm = v[j].vtx.norm;
	    t = sqrt (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
	    if (v[j].nverts == 1){
	        line = 0;
	        fprintf (f, "\n points %d 1\n", v[j].matn);
	    } else if (t < 0.001 && v[j].vtx.tex.u == 0 && v[j].vtx.tex.v == 0){
	        line = 1;
	        fprintf (f, "\n linestrip %d %d\n ", 
	                 v[j].matn, v[j].nverts + 1);
	    } else {
	        line = 0;
	        fprintf (f, "\n trifan %d %d\n ", 
	                 v[j].matn, v[j].nverts);
	    }
	    for (vn = v[j].nverts - 1; vn >= 0; vn--){
	        fprintf (f, " %d", j + vn);
	    }
	    if (line == 1){
	        fprintf (f, " %d", j + v[j].nverts - 1);
	    }
	    fprintf (f, "\n");
	}
	DEBUG_PRINTF ("#   Polygons done\n");
	fprintf (f, "\n"
	            "end_mesh\n"
		    "\n");
	free(v);
    }
    DEBUG_PRINTF ("# Meshes done\n");
#ifdef DEBUGAXIS
    fprintf (f, "mesh\n"
                "\n"
		" vertexdesc\n"
		"  position f3\n"
		" end_vertexdesc\n"
		"\n"
		" vertices 7\n"
		"  0 0 0\n"
		"  %f 0 0\n"
		"  %f 0 0\n"
		"  0 %f 0\n"
		"  0 %f 0\n"
		"  0 0 %f\n"
		"  0 0 %f\n"
		"\n"
		" linelist %d 2\n"
		"  0 1\n"
		" linelist %d 2\n"
		"  0 2\n"
		" linelist %d 2\n"
		"  0 3\n"
		" linelist %d 2\n"
		"  0 4\n"
		" linelist %d 2\n"
		"  0 5\n"
		" linelist %d 2\n"
		"  0 6\n"
		"\n"
		"end_mesh\n\n",
		max.z, min.z, max.y, min.y, max.x, min.x,
		model->nr_mat, model->nr_mat + 1, model->nr_mat + 2,
		model->nr_mat + 3, model->nr_mat + 4, model->nr_mat + 5);
#endif
    DEBUG_PRINTF ("# cmod out\n");
    fclose (f);

    return 0;
}
コード例 #14
0
ファイル: main.c プロジェクト: yin8086/psplinkusb
int main_thread(SceSize args, void *argp)
{
	struct PsplinkContext *ctx;
	int ret;
	SceUInt timeout;
	SceUID thids[20];
	int count;
	int intc;

	printf("PSPLink USB GDBServer (c) 2k7 TyRaNiD\n");
	if(!initialise(args, argp))
	{
		printf("Usage: usbgdb.prx program [args]\n");
		sceKernelExitDeleteThread(0);
	}

	if(usbAsyncRegister(ASYNC_GDB, &g_endp) < 0)
	{
		printf("Could not register GDB provider\n");
		sceKernelExitDeleteThread(0);
	}

	usbWaitForConnect();
	memset(&g_handler, 0, sizeof(g_handler));
	g_handler.size = sizeof(g_handler);
	g_handler.membase = g_context.info.text_addr;
	g_handler.memtop = g_context.info.text_addr + g_context.info.text_size;
	g_handler.mbox = sceKernelCreateMbx("GDBMbx", 0, NULL);
	if(g_handler.mbox < 0)
	{
		printf("Could not create message box\n");
		sceKernelExitDeleteThread(0);
	}

	if(debugRegisterEventHandler(&g_handler) < 0)
	{
		printf("Could not register event handler\n");
		sceKernelExitDeleteThread(0);
	}

	if(GdbHandleException(&g_context.ctx))
	{
		while(1)
		{
			timeout = GDB_POLL_TIMEOUT;
			ret = debugWaitDebugEvent(&g_handler, &ctx, &timeout);
			
			if(ret == 0)
			{
				DEBUG_PRINTF("ctx %p, epc 0x%08X\n", ctx, ctx->regs.epc);
				ret = GdbHandleException(ctx);
				sceKernelWakeupThread(ctx->thid);
				if(ret == 0)
				{
					break;
				}
			}
			else if(ret == SCE_KERNEL_ERROR_WAIT_TIMEOUT)
			{
				unsigned char ch;

				if(peekDebugChar(&ch) && (ch == 3))
				{
					DEBUG_PRINTF("Break Issued\n");
					intc = pspSdkDisableInterrupts();
					count = psplinkReferThreadsByModule(SCE_KERNEL_TMID_Thread, g_context.uid, thids, 20);
					if(count > 0)
					{
						/* We just break the first thread */
						/* Could in theory break on the thread which we are interested in ? */
						debugBreakThread(thids[0]);
					}
					pspSdkEnableInterrupts(intc);

					/* Should have a fallback if it just wont stop
						GdbHandleException(&g_context.ctx);
					*/
				}
				continue;
			}
			else
			{
				printf("Error waiting for debug event 0x%08X\n", ret);
				break;
			}
		}
	}

	debugUnregisterEventHandler(&g_handler);
	sceKernelExitDeleteThread(0);

	return 0;
}
コード例 #15
0
ファイル: ng_utf8.cpp プロジェクト: tomzhang/hyperscan
static
bool expandCyclic(NGHolder &h, NFAVertex v) {
    DEBUG_PRINTF("inspecting %zu\n", h[v].index);
    bool changes = false;

    auto v_preds = preds(v, h);
    auto v_succs = succs(v, h);

    set<NFAVertex> start_siblings;
    set<NFAVertex> end_siblings;

    CharReach &v_cr = h[v].char_reach;

    /* We need to find start vertices which have all of our preds.
     * As we have a self loop, it must be one of our succs. */
    for (auto a : adjacent_vertices_range(v, h)) {
        auto a_preds = preds(a, h);

        if (a_preds == v_preds && isutf8start(h[a].char_reach)) {
            DEBUG_PRINTF("%zu is a start v\n", h[a].index);
            start_siblings.insert(a);
        }
    }

    /* We also need to find full cont vertices which have all our own succs;
     * As we have a self loop, it must be one of our preds. */
    for (auto a : inv_adjacent_vertices_range(v, h)) {
        auto a_succs = succs(a, h);

        if (a_succs == v_succs && h[a].char_reach == UTF_CONT_CR) {
            DEBUG_PRINTF("%zu is a full tail cont\n", h[a].index);
            end_siblings.insert(a);
        }
    }

    for (auto s : start_siblings) {
        if (out_degree(s, h) != 1) {
            continue;
        }

        const CharReach &cr = h[s].char_reach;
        if (cr.isSubsetOf(UTF_TWO_START_CR)) {
            if (end_siblings.find(*adjacent_vertices(s, h).first)
                == end_siblings.end()) {
                DEBUG_PRINTF("%zu is odd\n", h[s].index);
                continue;
            }
        } else if (cr.isSubsetOf(UTF_THREE_START_CR)) {
            NFAVertex m = *adjacent_vertices(s, h).first;

            if (h[m].char_reach != UTF_CONT_CR
                || out_degree(m, h) != 1) {
                continue;
            }
            if (end_siblings.find(*adjacent_vertices(m, h).first)
                == end_siblings.end()) {
                DEBUG_PRINTF("%zu is odd\n", h[s].index);
                continue;
            }
        } else if (cr.isSubsetOf(UTF_FOUR_START_CR)) {
            NFAVertex m1 = *adjacent_vertices(s, h).first;

            if (h[m1].char_reach != UTF_CONT_CR
                || out_degree(m1, h) != 1) {
                continue;
            }

            NFAVertex m2 = *adjacent_vertices(m1, h).first;

            if (h[m2].char_reach != UTF_CONT_CR
                || out_degree(m2, h) != 1) {
                continue;
            }

            if (end_siblings.find(*adjacent_vertices(m2, h).first)
                == end_siblings.end()) {
                DEBUG_PRINTF("%zu is odd\n", h[s].index);
                continue;
            }
        } else {
            DEBUG_PRINTF("%zu is bad\n", h[s].index);
          continue;
        }

        v_cr |= cr;
        clear_vertex(s, h);
        changes = true;
    }

    if (changes) {
        v_cr |= UTF_CONT_CR; /* we need to add in cont reach */
        v_cr.set(0xc0); /* we can also add in the forbidden bytes as we require
                         * valid unicode data */
        v_cr.set(0xc1);
        v_cr |= CharReach(0xf5, 0xff);
    }

    return changes;
}
コード例 #16
0
ファイル: ftpfs.c プロジェクト: aniwang2013/leon-rtems
static int rtems_ftpfs_open_data_connection_passive(
  rtems_ftpfs_entry *e,
  uint32_t client_address,
  const char *file_command,
  const char *filename,
  bool verbose,
  const struct timeval *timeout
)
{
  int rv = 0;
  rtems_ftpfs_reply reply = RTEMS_FTPFS_REPLY_ERROR;
  struct sockaddr_in sa;
  uint32_t data_address = 0;
  uint16_t data_port = 0;

  rtems_ftpfs_pasv_entry pe = {
    .state = RTEMS_FTPFS_PASV_START
  };

  /* Send PASV command */
  reply = rtems_ftpfs_send_command_with_parser(
    e,
    "PASV",
    NULL,
    rtems_ftpfs_pasv_parser,
    &pe,
    verbose
  );
  if (reply != RTEMS_FTPFS_REPLY_2) {
    return ENOTSUP;
  }
  data_address = ((uint32_t)(pe.data [0]) << 24) + ((uint32_t)(pe.data [1]) << 16)
    + ((uint32_t)(pe.data [2]) << 8) + ((uint32_t)(pe.data [3]));
  data_port = (uint16_t) ((pe.data [4] << 8) + pe.data [5]);
  rtems_ftpfs_create_address(&sa, htonl(data_address), htons(data_port));
  DEBUG_PRINTF(
    "server data = %s:%u\n",
    inet_ntoa(sa.sin_addr),
    (unsigned) ntohs(sa.sin_port)
  );

  /* Create data socket */
  e->data_socket = socket(AF_INET, SOCK_STREAM, 0);
  if (e->data_socket < 0) {
    return ENOMEM;
  }

  /* Open data connection */
  rv = connect(
    e->data_socket,
    (struct sockaddr *) &sa,
    sizeof(sa)
  );
  if (rv != 0) {
    return EIO;
  }

  /* Send RETR or STOR command with filename */
  reply = rtems_ftpfs_send_command(e, file_command, filename, verbose);
  if (reply != RTEMS_FTPFS_REPLY_1) {
    return EIO;
  }

  return 0;
}
コード例 #17
0
static void output_suggest_visit(rb_node *node, void *data){
  FILE *out = data;
  string *word = node->data;
  DEBUG_PRINTF("\t%.*s\n", (int)word->sz, word->str);
  fprintf(out, "\t%.*s\n", (int)word->sz, word->str);
}
コード例 #18
0
ファイル: ftpfs.c プロジェクト: aniwang2013/leon-rtems
static int rtems_ftpfs_open(
  rtems_libio_t *iop,
  const char *path,
  int oflag,
  mode_t mode
)
{
  int eno = 0;
  bool ok = false;
  rtems_ftpfs_entry *e = NULL;
  rtems_ftpfs_mount_entry *me = iop->pathinfo.mt_entry->fs_info;
  bool verbose = me->verbose;
  const struct timeval *timeout = &me->timeout;
  const char *user = NULL;
  const char *password = NULL;
  const char *hostname = NULL;
  const char *filename = NULL;
  const char *file_command = (iop->flags & LIBIO_FLAGS_WRITE) != 0
    ? "STOR "
    : "RETR ";
  uint32_t client_address = 0;
  char *location = iop->pathinfo.node_access;

  /* Invalidate data handle */
  iop->data1 = NULL;

  /* Split location into parts */
  ok = rtems_ftpfs_split_names(
      location,
      &user,
      &password,
      &hostname,
      &filename
  );
  if (!ok) {
    rtems_set_errno_and_return_minus_one(ENOENT);
  }
  DEBUG_PRINTF(
    "user = '******', password = '******', filename = '%s'\n",
    user,
    password,
    filename
  );

  /* Check for either read-only or write-only flags */
  if (
    (iop->flags & LIBIO_FLAGS_WRITE) != 0
      && (iop->flags & LIBIO_FLAGS_READ) != 0
  ) {
    rtems_set_errno_and_return_minus_one(ENOTSUP);
  }

  /* Allocate connection entry */
  e = calloc(1, sizeof(*e));
  if (e == NULL) {
    rtems_set_errno_and_return_minus_one(ENOMEM);
  }

  /* Initialize connection entry */
  e->ctrl_socket = -1;
  e->data_socket = -1;

  /* Save connection state */
  iop->data1 = e;

  /* Open control connection */
  eno = rtems_ftpfs_open_ctrl_connection(
    e,
    user,
    password,
    hostname,
    &client_address,
    verbose,
    timeout
  );
  if (eno != 0) {
    goto cleanup;
  }

  /* Open passive data connection */
  eno = rtems_ftpfs_open_data_connection_passive(
    e,
    client_address,
    file_command,
    filename,
    verbose,
    timeout
  );
  if (eno == ENOTSUP) {
    /* Open active data connection */
    eno = rtems_ftpfs_open_data_connection_active(
      e,
      client_address,
      file_command,
      filename,
      verbose,
      timeout
    );
  }
  if (eno != 0) {
    goto cleanup;
  }

  /* Set data connection timeout */
  eno = rtems_ftpfs_set_connection_timeout(e->data_socket, timeout);

cleanup:

  if (eno == 0) {
    return 0;
  } else {
    /* Free all resources if an error occured */
    rtems_ftpfs_terminate(iop, true);

    rtems_set_errno_and_return_minus_one(eno);
  }
}
コード例 #19
0
ファイル: ubasic.c プロジェクト: EtchedPixels/ubasic
/*---------------------------------------------------------------------------*/
static void factor(struct typevalue *v)
{
  uint8_t t = current_token;
  int len;
  struct typevalue arg[3];

  DEBUG_PRINTF("factor: token %d\n", current_token);
  switch(t) {
  case TOKENIZER_STRING:
    v->type = TYPE_STRING;
    len = tokenizer_string_len();
    v->d.p = string_temp(len);
    memcpy(v->d.p + 1, tokenizer_string(), len);
    DEBUG_PRINTF("factor: string %p\n", v->d.p);
    accept_tok(TOKENIZER_STRING);
    break;
  case TOKENIZER_NUMBER:
    v->d.i = tokenizer_num();
    v->type = TYPE_INTEGER;
    DEBUG_PRINTF("factor: number %d\n", v->d.i);
    accept_tok(TOKENIZER_NUMBER);
    break;
  case TOKENIZER_LEFTPAREN:
    accept_tok(TOKENIZER_LEFTPAREN);
    expr(v);
    accept_tok(TOKENIZER_RIGHTPAREN);
    break;
  case TOKENIZER_INTVAR:
  case TOKENIZER_STRINGVAR:
    varfactor(v);
    break;
  default:
    if (TOKENIZER_NUMEXP(t)) {
      accept_tok(t);
      switch(t) {
      case TOKENIZER_PEEK:
        funcexpr(arg,"I");
        v->d.i = peek_function(arg[0].d.i);
        break;
      case TOKENIZER_ABS:
        funcexpr(arg,"I");
        v->d.i = arg[0].d.i;
        if (v->d.i < 0)
          v->d.i = -v->d.i;
        break;
      case TOKENIZER_INT:
        funcexpr(arg,"I");
        v->d.i = arg[0].d.i;
        break;
      case TOKENIZER_SGN:
        funcexpr(arg,"I");
        v->d.i = arg[0].d.i;
        if (v->d.i > 1 ) v->d.i = 1;
        if (v->d.i < 0) v->d.i = -1;
        break;
      case TOKENIZER_LEN:
        funcexpr(arg,"S");
        v->d.i = *arg[0].d.p;
        break;
      case TOKENIZER_CODE:
        funcexpr(arg,"S");
        if (*arg[0].d.p)
          v->d.i = arg[0].d.p[1];
        else
          v->d.i = 0;
        break;
      case TOKENIZER_VAL:
        funcexpr(arg,"S");
        v->d.i = string_val(&arg[0]);
        break;
      default:
        syntax_error();
      }
      v->type = TYPE_INTEGER;
    }
    else if (TOKENIZER_STRINGEXP(t)) {
      accept_tok(t);
      switch(t) {
      case TOKENIZER_LEFTSTR:
        funcexpr(arg, "SI");
        string_cut(v, &arg[0], 1, arg[1].d.i);
        break;
      case TOKENIZER_RIGHTSTR:
        funcexpr(arg, "SI");
        string_cut_r(v, &arg[0], arg[1].d.i);
        break;
      case TOKENIZER_MIDSTR:
        funcexpr(arg, "SII");
        string_cut(v, &arg[0], arg[1].d.i, arg[2].d.i);
        break;
      case TOKENIZER_CHRSTR:
        funcexpr(arg, "I");
        v->d.p = string_temp(2);
        v->d.p[1] = arg[0].d.i;
        v->type = TYPE_STRING;
        break;
      default:
        syntax_error();
      }
    }
    else
      syntax_error();
  }
}
コード例 #20
0
ファイル: dirent.c プロジェクト: c0ns0le/SysToolsLib
static int report_workaround(char *s) {
  DEBUG_PRINTF((s));
  return 1;
}
コード例 #21
0
/**
 @brief Callback for system_init_done_cb()
  Sends message to run task
 @return void
*/
MEMSPACE 
LOCAL void init_done_cb( void)
{
	DEBUG_PRINTF("System init done \r\n");
}
コード例 #22
0
ファイル: dirent.c プロジェクト: c0ns0le/SysToolsLib
int closedir(DIR *pDir) { /* Close the directory. Return 0 if successful, -1 if not. */
  DEBUG_PRINTF(("closedir(0x%p);\n", pDir));
  if (pDir) free(pDir);
  return 0;
}
コード例 #23
0
/**
 @brief main() Initialize user task
 @return void
*/
MEMSPACE 
void user_init(void)
{
	int i;
	os_event_t *handlerQueue;
    char time[20];
	int ret;
	uint16_t *ptr;
	uint32_t time1,time2;
	uint32_t ID;
	extern uint16_t tft_ID;
	double ang;

	os_delay_us(200000L);	// Power Up dalay - lets power supplies and devices settle

	// Configure the UART
	uart_init(BIT_RATE_115200,BIT_RATE_115200);

	DEBUG_PRINTF("\n");
	DEBUG_PRINTF("System init...\n");

	DEBUG_PRINTF("HSPI init...\n");
	hspi_init(1,0);

	DEBUG_PRINTF("Timers init...\n");
	init_timers();

	DEBUG_PRINTF("SD Card init...\n");
	mmc_init(1);

// CPU
// 160MHZ
//  REG_SET_BIT(0x3ff00014, BIT(0));
// 80MHZ
//   REG_CLR_BIT(0x3ff00014, BIT(0));


	DEBUG_PRINTF("Display Init\n");
	// Initialize TFT
	master = tft_init();
	ID = tft_ID;
	// Set master rotation
	tft_setRotation(1);

	/* Setup main status window */
	tft_window_init(winstats,0,0, master->w * 7 / 10, master->h/2);

	tft_setpos(winstats, 0,0);
	tft_set_font(winstats,5);
	tft_font_var(winstats);
	tft_setTextColor(winstats, ILI9341_RED,0);
	tft_printf(winstats, "DISP ID: %04lx\n", ID);
	ip_xpos = winstats->x;
	ip_ypos = winstats->y;
	tft_printf(winstats, "\n");
	tft_setTextColor(winstats, ILI9341_WHITE,0);
#if ILI9341_DEBUG & 1
	DEBUG_PRINTF("\nDisplay ID=%08lx\n",ID);
#endif
	tft_font_fixed(winstats);

	// Save last display offset of the status update line - used in the demo task
	xpos = winstats->x;
	ypos = winstats->y;

	/* Setup cube/wireframe demo window */
	tft_window_init(windemo,winstats->w,0, master->w - winstats->w, master->h/2);

// Cube points were defined with sides of 1.0 
// We want a scale of +/- w/2
	if(windemo->w < windemo->h) 
		dscale_max = windemo->w/2;
	else
		dscale_max = windemo->h/2;

	dscale = dscale_max;
	dscale_inc = dscale_max / 100;

/* Setup second window for window testing*/
	tft_window_init(wintest,0,master->h/2, master->w/2, master->h/2);
	tft_setTextColor(wintest, ILI9341_WHITE,ILI9341_NAVY);
    tft_fillWin(wintest, wintest->bg);
	tft_set_font(wintest,3);
	//tft_font_var(wintest);

	// write some text
	tft_setpos(wintest, 0,0);
	tft_printf(wintest, "Test1\nTest2\nTest3");

	/* Test demo area window */
	tft_window_init(wintestdemo,master->w/2,master->h/2,master->w/2, master->h/2);
	tft_setTextColor(wintestdemo, ILI9341_WHITE,0);
    tft_fillWin(wintestdemo, wintestdemo->bg);
	tft_set_font(wintestdemo,3);
	tft_font_var(wintestdemo);

#if ILI9341_DEBUG & 1
	DEBUG_PRINTF("Test Display Read\n");
	read_tests(wintest);
#endif

/* Draw cube in the second window as a test */
#if defined(WIRECUBE) && !defined(EARTH)
	DEBUG_PRINTF("Draw Cube\n");
// Cube points were defined with sides of 1.0 
// We want a scale of +/- w/2
	double tscale_max;
	if(wintestdemo->w < wintestdemo->h) 
		tscale_max = wintestdemo->w/2;
	else
		tscale_max = wintestdemo->h/2;
	ang = 45.0;
	V.x = ang;
	V.y = ang;
	V.z = ang;
	wire_draw(wintestdemo, cube_points, cube_edges, &V, wintestdemo->w/2, wintestdemo->h/2, tscale_max, ILI9341_RED);
#endif

#ifdef EARTH
	DEBUG_PRINTF("Draw Earth\n");
// Earth points were defined with radius of 0.5, diameter of 1.0
// We want a scale of +/- w/2
	double tscale_max;
	if(wintestdemo->w < wintestdemo->h) 
		tscale_max = wintestdemo->w;
	else
		tscale_max = wintestdemo->h;
	V.x = -90;
	V.y = -90;
	V.z = -90;
	// draw earth
	//time1 = system_get_time();
// Earth points were defined over with a scale of -0.5/+0.5 scale - so scale must be 1 or less
	wire_draw(wintestdemo, earth_data, NULL, &V, wintestdemo->w/2, wintestdemo->h/2, tscale_max, wintestdemo->fg);
	//time2 = system_get_time();
#endif

	wdt_reset();

	DEBUG_PRINTF("User Task\n");
	// Set up a timer to send the message to User Task
	os_timer_disarm(&UserTimerHandler);
	os_timer_setfn(&UserTimerHandler,(os_timer_func_t *)sendMsgToUserTask,(void *)0);
	os_timer_arm(&UserTimerHandler, USER_TASK_DELAY_TIMER, 1);
	// Setup the user task
	system_os_task(UserTask, UserTaskPrio, UserTaskQueue, UserTaskQueueLen);

#ifdef TELNET_SERIAL
	DEBUG_PRINTF("Setup Network Serial Bridge\n");
	bridge_task_init(23);
#endif

#ifdef NETWORK_TEST
	DEBUG_PRINTF("Setup Network TFT DIsplay Client\n");
	setup_networking(TCP_PORT);
#endif

#if 0
	// Misc Task init - testing only
	system_os_task(HighTask, HighTaskPrio, HighTaskQueue, HighTaskQueueLen);
	system_os_task(NormalTask, NormalTaskPrio, NormalTaskQueue, NormalTaskQueueLen);
	system_os_task(IdleTask, IdleTaskPrio, IdleTaskQueue, IdleTaskQueueLen);
	system_os_post(IdleTaskPrio, 0, 0);
#endif
	DEBUG_PRINTF("Done Setup\n");
    DEBUG_PRINTF("Heap Size(%d) bytes\n" , system_get_free_heap_size());

	// disable os_printf at this time
	system_set_os_print(0);

    system_init_done_cb(init_done_cb);
}
コード例 #24
0
static bool
markFastSafeFn(FnSymbol *fn, int recurse, Vec<FnSymbol*> *visited) {
  if (fn->hasFlag(FLAG_FAST_ON))
    return true;

  if (fn->hasFlag(FLAG_EXPORT))
    return true;

  if (fn->hasFlag(FLAG_EXTERN)) {
    // consider a pragma to indicate that it would be "fast"
    return false;
  }

  if (fn->hasFlag(FLAG_NON_BLOCKING))
    return false;

  visited->add_exclusive(fn);

  std::vector<CallExpr*> calls;

  collectCallExprs(fn, calls);

  for_vector(CallExpr, call, calls) {
    DEBUG_PRINTF("\tcall %p (id=%d): ", call, call->id);
    bool isLocal = fn->hasFlag(FLAG_LOCAL_FN) || inLocalBlock(call);

    if (!call->primitive) {
      DEBUG_PRINTF("(non-primitive CALL)\n");
      if ((recurse>0) && call->isResolved()) {
        if (call->isResolved()->hasFlag(FLAG_ON_BLOCK)) {
          visited->add_exclusive(call->isResolved());
          call->isResolved()->removeFlag(FLAG_FAST_ON);
          DEBUG_PRINTF("%d: recurse FAILED (nested on block, id=%d).\n",
                       recurse-1, call->id);
          return false;
        }
        if (!visited->in(call->isResolved())) {
          DEBUG_PRINTF("%d: recurse %p (block=%p, id=%d)\n", recurse-1,
                       call->isResolved(), call->isResolved()->body,
                       call->isResolved()->id);
          DEBUG_PRINTF("\tlength=%d\n", call->isResolved()->body->length());
          if (!markFastSafeFn(call->isResolved(), recurse-1, visited)) {
            DEBUG_PRINTF("%d: recurse FAILED (id=%d).\n", recurse-1, call->id);
            return false;
          }
        } else {
          DEBUG_PRINTF("%d: recurse ALREADY VISITED %p (id=%d)\n", recurse-1,
                       call->isResolved(), call->isResolved()->id);
          DEBUG_PRINTF("\tlength=%d\n", call->isResolved()->body->length());
        }
        DEBUG_PRINTF("%d: recurse DONE.\n", recurse-1);
      } else {
        // No function calls allowed
        DEBUG_PRINTF("%d: recurse FAILED (%s, id=%d).\n", recurse-1,
                     recurse == 1 ? "too deep" : "function not resolved",
                     call->id);
        return false;
      }
    } else if (isFastPrimitive(call, isLocal)) {
      DEBUG_PRINTF(" (FAST primitive CALL)\n");
    } else {
      DEBUG_PRINTF("%d: FAILED (non-FAST primitive CALL: %s, id=%d)\n",
                   recurse-1, call->primitive->name, call->id);
      return false;
    }
  }
コード例 #25
0
int freespace_private_devicePerform(struct FreespaceDeviceStruct* device) {
    int idx;
    BOOL overlappedResult;
    struct FreespaceSendStruct* send;
	int rc;
	struct freespace_message m;

    // Handle the send messages
    for (idx = 0; idx < FREESPACE_MAXIMUM_SEND_MESSAGE_COUNT; idx++) {
        send = &device->send_[idx];
        if (send->interface_ == NULL) {
            continue;
        }
        overlappedResult = GetOverlappedResult(
                                               send->interface_->handle_,
                                               &send->overlapped_,
                                               &send->numBytes_,
                                               FALSE);

        if (!overlappedResult) {
            // No message available yet.
            continue;
        } else if (send->numBytes_ != send->interface_->info_.outputReportByteLength_) {
            // Unexpected error on the sent message.
            DEBUG_PRINTF("freespace_private_devicePerform: error on message size: %d != %d\n",
                         send->numBytes_, send->interface_->info_.outputReportByteLength_);
            if (send->callback_ != NULL) {
                send->callback_(device->id_, send->cookie_, FREESPACE_ERROR_IO);
            }
        } else {
            // successfully sent message
            if (send->callback_ != NULL) {
                send->callback_(device->id_, send->cookie_, FREESPACE_SUCCESS);
            }
        }
        if (finalizeSendStruct(send, FALSE) != FREESPACE_SUCCESS) {
            DEBUG_PRINTF("freespace_private_devicePerform: error while sending message");
        }
    }

    // Call GetOverlappedResult() on everything to check what
    // messages were received.
    for (idx = 0; idx < device->handleCount_; idx++) {
        struct FreespaceSubStruct* s = &device->handle_[idx];

        if (s->readStatus_) {
            int lastErr;
            BOOL bResult = GetOverlappedResult(
                                               s->handle_,                 /* handle to device */
                                               &s->readOverlapped_,        /* long pointer to an OVERLAPPED structure */
                                               &s->readBufferSize,         /* returned buffer size */
                                               FALSE);
            lastErr = GetLastError();
            if (bResult) {
                // Got something, so report it.
                if (device->receiveCallback_ || device->receiveMessageCallback_) {
					if (device->receiveCallback_) {
						device->receiveCallback_(device->id_, (char *) (s->readBuffer), s->readBufferSize, device->receiveCookie_, FREESPACE_SUCCESS);
					}
					if (device->receiveMessageCallback_) {
						rc = freespace_decode_message((char *) (s->readBuffer), s->readBufferSize, &m, device->hVer_);
						if (rc == FREESPACE_SUCCESS) {
							device->receiveMessageCallback_(device->id_, &m, device->receiveMessageCookie_, FREESPACE_SUCCESS);
						} else {
							device->receiveMessageCallback_(device->id_, NULL, device->receiveMessageCookie_, rc);
							DEBUG_PRINTF("freespace_decode_message failed with code %d\n", rc);
						}
					}
				}
                s->readStatus_ = FALSE;
            } else if (lastErr != ERROR_IO_INCOMPLETE) {
                // Something severe happened to our device!
				DEBUG_PRINTF("freespace_private_devicePerform : Error on %d : %d\n", idx, lastErr);
                if (device->receiveCallback_) {
				    device->receiveCallback_(device->id_, NULL, 0, device->receiveCookie_, FREESPACE_ERROR_NO_DATA);
				}
				if (device->receiveMessageCallback_) {
				    device->receiveMessageCallback_(device->id_, NULL, device->receiveMessageCookie_, FREESPACE_ERROR_NO_DATA);
				}
                return handleDeviceFailure(device, lastErr);
            }
        }
    }

    // Re-initiate the ReadFile calls for the next go around.
    return initiateAsyncReceives(device);
}
コード例 #26
0
//
// Return true if this primitive function is safe for fast on optimization
// (e.g., no communication, no sync/single accesses)
//
static bool
isFastPrimitive(CallExpr *call, bool isLocal) {
  INT_ASSERT(call->primitive);
  // Check primitives for communication
  switch (call->primitive->tag) {
  case PRIM_UNKNOWN:
    // TODO: Return true for PRIM_UNKNOWNs that are side-effect free
    return false;

  case PRIM_NOOP:
  case PRIM_REF_TO_STRING:
  case PRIM_RETURN:
  case PRIM_UNARY_MINUS:
  case PRIM_UNARY_PLUS:
  case PRIM_UNARY_NOT:
  case PRIM_UNARY_LNOT:
  case PRIM_ADD:
  case PRIM_SUBTRACT:
  case PRIM_MULT:
  case PRIM_DIV:
  case PRIM_MOD:
  case PRIM_LSH:
  case PRIM_RSH:
  case PRIM_EQUAL:
  case PRIM_NOTEQUAL:
  case PRIM_LESSOREQUAL:
  case PRIM_GREATEROREQUAL:
  case PRIM_LESS:
  case PRIM_GREATER:
  case PRIM_AND:
  case PRIM_OR:
  case PRIM_XOR:
  case PRIM_POW:
  case PRIM_MIN:
  case PRIM_MAX:

  case PRIM_GET_MEMBER:
  case PRIM_GET_SVEC_MEMBER:
  case PRIM_GET_PRIV_CLASS:
  case PRIM_NEW_PRIV_CLASS:

  case PRIM_CHECK_NIL:
  case PRIM_GET_REAL:
  case PRIM_GET_IMAG:

  case PRIM_ADDR_OF:
  case PRIM_LOCAL_CHECK:

  case PRIM_INIT_FIELDS:
  case PRIM_PTR_EQUAL:
  case PRIM_PTR_NOTEQUAL:
  case PRIM_CAST:

  case PRIM_BLOCK_LOCAL:

  case PRIM_ON_LOCALE_NUM:
  case PRIM_GET_SERIAL:
  case PRIM_SET_SERIAL:

  case PRIM_START_RMEM_FENCE:
  case PRIM_FINISH_RMEM_FENCE:

  case PRIM_STRING_COPY:
  case PRIM_C_STRING_FROM_STRING:
  case PRIM_CAST_TO_VOID_STAR:
  case PRIM_SIZEOF:

  case PRIM_GET_USER_LINE:
  case PRIM_GET_USER_FILE:
    DEBUG_PRINTF(" *** OK (default): %s\n", call->primitive->name);
    return true;

  case PRIM_MOVE:
  case PRIM_ASSIGN:
  case PRIM_ADD_ASSIGN:
  case PRIM_SUBTRACT_ASSIGN:
  case PRIM_MULT_ASSIGN:
  case PRIM_DIV_ASSIGN:
  case PRIM_MOD_ASSIGN:
  case PRIM_LSH_ASSIGN:
  case PRIM_RSH_ASSIGN:
  case PRIM_AND_ASSIGN:
  case PRIM_OR_ASSIGN:
  case PRIM_XOR_ASSIGN:
    if (!isCallExpr(call->get(2))) { // callExprs checked in calling function
      if (!call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_REF) &&
          !call->get(2)->typeInfo()->symbol->hasFlag(FLAG_WIDE_REF)) {
        DEBUG_PRINTF(" *** OK (PRIM_MOVE 1): %s\n", call->primitive->name);
        return true;
      }
    } else {
      DEBUG_PRINTF(" *** OK (PRIM_MOVE 2): %s\n", call->primitive->name);
      // Not necessarily true, but we return true because
      // the callExpr will be checked in the calling function
      return true;
    }
    break;

// I think these can always return true. <hilde>
// But that works only if the remote get is removed from code generation.
  case PRIM_WIDE_GET_LOCALE:
  case PRIM_WIDE_GET_NODE:
  case PRIM_WIDE_GET_ADDR:
    // If this test is true, a remote get is required.
    if (!(call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_REF) &&
          call->get(1)->getValType()->symbol->hasFlag(FLAG_WIDE_CLASS))) {
      DEBUG_PRINTF(" *** OK (PRIM_WIDE_GET_LOCALE, etc.): %s\n",
                   call->primitive->name);
      return true;
    }
    break;

  case PRIM_SET_UNION_ID:
  case PRIM_GET_UNION_ID:
  case PRIM_GET_MEMBER_VALUE:
  case PRIM_GET_SVEC_MEMBER_VALUE:
    if (!call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_REF)) {
      return true;
      DEBUG_PRINTF(" *** OK (PRIM_SET_UNION_ID, etc.): %s\n",
                   call->primitive->name);
    }
    break;

  case PRIM_ARRAY_SET:
  case PRIM_ARRAY_SET_FIRST:
  case PRIM_SETCID:
  case PRIM_TESTCID:
  case PRIM_GETCID:
  case PRIM_ARRAY_GET:
  case PRIM_ARRAY_GET_VALUE:
  case PRIM_DYNAMIC_CAST:
    if (!call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) {
      DEBUG_PRINTF(" *** OK (PRIM_ARRAY_SET, etc.): %s\n",
                   call->primitive->name);
      return true;
    }
    break;

  case PRIM_DEREF:
  case PRIM_SET_MEMBER:
  case PRIM_SET_SVEC_MEMBER:
    if (!call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_REF) &&
        !call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) {
      DEBUG_PRINTF(" *** OK (PRIM_DEREF, etc.): %s\n", call->primitive->name);
      return true;
    }
    break;

  case PRIM_CHPL_COMM_GET:
  case PRIM_CHPL_COMM_PUT:
  case PRIM_CHPL_COMM_REMOTE_PREFETCH:
  case PRIM_CHPL_COMM_GET_STRD:
  case PRIM_CHPL_COMM_PUT_STRD:
    // These may involve communication, so are deemed slow.
    return false;

  case PRIM_SYNC_INIT: // Maybe fast?
  case PRIM_SYNC_DESTROY: // Maybe fast?
  case PRIM_SYNC_LOCK:
  case PRIM_SYNC_UNLOCK:
  case PRIM_SYNC_WAIT_FULL:
  case PRIM_SYNC_WAIT_EMPTY:
  case PRIM_SYNC_SIGNAL_FULL:
  case PRIM_SYNC_SIGNAL_EMPTY:
  case PRIM_SINGLE_INIT: // Maybe fast?
  case PRIM_SINGLE_DESTROY: // Maybe fast?
  case PRIM_SINGLE_LOCK:
  case PRIM_SINGLE_UNLOCK:
  case PRIM_SINGLE_WAIT_FULL:
  case PRIM_SINGLE_SIGNAL_FULL:

  case PRIM_WRITEEF:
  case PRIM_WRITEFF:
  case PRIM_WRITEXF:
  case PRIM_READFE:
  case PRIM_READFF:
  case PRIM_READXX:
  case PRIM_SYNC_IS_FULL:
  case PRIM_SINGLE_WRITEEF:
  case PRIM_SINGLE_READFF:
  case PRIM_SINGLE_READXX:
  case PRIM_SINGLE_IS_FULL:
   // These may block, so are deemed slow.
   return false;

  case PRIM_NEW:
  case PRIM_INIT:
  case PRIM_NO_INIT:
  case PRIM_TYPE_INIT:
  case PRIM_LOGICAL_FOLDER:
  case PRIM_TYPEOF:
  case PRIM_TYPE_TO_STRING:
  case PRIM_ENUM_MIN_BITS:
  case PRIM_ENUM_IS_SIGNED:
  case PRIM_IS_UNION_TYPE:
  case PRIM_IS_ATOMIC_TYPE:
  case PRIM_IS_SYNC_TYPE:
  case PRIM_IS_SINGLE_TYPE:
  case PRIM_IS_TUPLE_TYPE:
  case PRIM_IS_STAR_TUPLE_TYPE:
  case PRIM_IS_SUBTYPE:
  case PRIM_TUPLE_EXPAND:
  case PRIM_TUPLE_AND_EXPAND:
  case PRIM_QUERY:
  case PRIM_QUERY_PARAM_FIELD:
  case PRIM_QUERY_TYPE_FIELD:
  case PRIM_ERROR:
  case PRIM_WARNING:

  case PRIM_BLOCK_PARAM_LOOP:
  case PRIM_BLOCK_BEGIN:
  case PRIM_BLOCK_COBEGIN:
  case PRIM_BLOCK_COFORALL:
  case PRIM_BLOCK_ON:
  case PRIM_BLOCK_BEGIN_ON:
  case PRIM_BLOCK_COBEGIN_ON:
  case PRIM_BLOCK_COFORALL_ON:
  case PRIM_BLOCK_UNLOCAL:

  case PRIM_ACTUALS_LIST:
  case PRIM_YIELD:

  case PRIM_USE:
  case PRIM_USED_MODULES_LIST:

  case PRIM_WHEN:
  case PRIM_INT_ERROR:
  case PRIM_CAPTURE_FN:
  case PRIM_CREATE_FN_TYPE:

  case PRIM_NUM_FIELDS:
  case PRIM_FIELD_NUM_TO_NAME:
  case PRIM_FIELD_VALUE_BY_NUM:
  case PRIM_FIELD_ID_BY_NUM:
  case PRIM_FIELD_VALUE_BY_NAME:
    INT_FATAL("This primitive should have been removed from the tree by now.");
    break;

    // By themselves, loops are considered "fast".
  case PRIM_BLOCK_WHILEDO_LOOP:
  case PRIM_BLOCK_DOWHILE_LOOP:
  case PRIM_BLOCK_FOR_LOOP:
  case PRIM_BLOCK_C_FOR_LOOP:
    return true;
 
   // These don't block in the Chapel sense, but they may require a system
    // call so we don't consider them eligible.
    //
  case PRIM_FREE_TASK_LIST:
  case PRIM_ARRAY_ALLOC:
  case PRIM_ARRAY_FREE:
  case PRIM_ARRAY_FREE_ELTS:
  case PRIM_STRING_FROM_C_STRING:
    return false;

    // Temporarily unclassified (legacy) cases.
    // These formerly defaulted to false (slow), so we leave them
    // here until they are proven fast.
  case PRIM_GET_END_COUNT:
  case PRIM_SET_END_COUNT:
  case PRIM_PROCESS_TASK_LIST:
  case PRIM_EXECUTE_TASKS_IN_LIST:
  case PRIM_TO_LEADER:
  case PRIM_TO_FOLLOWER:
  case PRIM_DELETE:
  case PRIM_CALL_DESTRUCTOR:
  case PRIM_HEAP_REGISTER_GLOBAL_VAR:
  case PRIM_HEAP_BROADCAST_GLOBAL_VARS:
  case PRIM_PRIVATE_BROADCAST:
  case PRIM_RT_ERROR:
  case PRIM_RT_WARNING:
  case PRIM_FTABLE_CALL:
  case PRIM_VIRTUAL_METHOD_CALL:
    return false;

  default:
    INT_FATAL("Unhandled case.");
    break;
  }

  return isLocal;
}
コード例 #27
0
int freespace_private_send(FreespaceDeviceId id,
                           const uint8_t* report,
                           int length) {

    struct FreespaceSendStruct* send;
    int retVal = 0;
    DWORD lastError = 0;

    retVal = prepareSend(id, &send, report, length);
    if (retVal != FREESPACE_SUCCESS) {
        return retVal;
    }

    // Send the message
    retVal = freespace_send_activate(send);
    if (retVal != FREESPACE_ERROR_IO) {
        return retVal;
    }

    // Wait for the message to be sent
    lastError = WaitForSingleObject(send->overlapped_.hEvent, SEND_TIMEOUT);

    if (lastError != WAIT_OBJECT_0) {
        // timed out
        BOOL overlappedResult = GetOverlappedResult(send->interface_->handle_,
                                                    &send->overlapped_,
                                                    &send->numBytes_,
                                                    FALSE);

        // Abort any pending messages and return
        // WARNING: CancelIo will also affect READ!
        DEBUG_PRINTF("freespace_send: error on WaitForSingleObject = %d\n", lastError);
        CancelIo(send->interface_->handle_);
        send->interface_->readStatus_ = FALSE;

        if (overlappedResult) {
            send->rc_ = FREESPACE_ERROR_TIMEOUT;
        } else {
            send->rc_ = FREESPACE_ERROR_IO; //FREESPACE_OS_ERROR_BASE - lastError;
        }
    } else {
        // success
        BOOL overlappedResult = GetOverlappedResult(send->interface_->handle_,
                                                    &send->overlapped_,
                                                    &send->numBytes_,
                                                    TRUE);

        if (!overlappedResult) {
            DEBUG_PRINTF("freespace_send: error on GetOverlappedResult\n");
            send->rc_ = FREESPACE_ERROR_IO;
        } else if (send->numBytes_ != send->interface_->info_.outputReportByteLength_) {
            DEBUG_PRINTF("freespace_send: error on message size: %d != %d\n",
                         send->numBytes_, send->interface_->info_.outputReportByteLength_);
            send->rc_ = FREESPACE_ERROR_IO;
        } else {
            // successfully sent message
            send->rc_ = FREESPACE_SUCCESS;
        }
    }

    return finalizeSendStruct(send, FALSE);
}
コード例 #28
0
ファイル: ng_utf8.cpp プロジェクト: tomzhang/hyperscan
static
void findSeeds(const NGHolder &h, const bool som, vector<NFAVertex> *seeds) {
    set<NFAVertex> bad; /* from zero-width asserts near accepts, etc */
    for (auto v : inv_adjacent_vertices_range(h.accept, h)) {
        const CharReach &cr = h[v].char_reach;
        if (!isutf8ascii(cr) && !isutf8start(cr)) {
            bad.insert(v);
        }
    }

    for (auto v : inv_adjacent_vertices_range(h.acceptEod, h)) {
        const CharReach &cr = h[v].char_reach;
        if (!isutf8ascii(cr) && !isutf8start(cr)) {
            bad.insert(v);
        }
    }

    // we want to be careful with asserts connected to starts
    // as well as they may not finish a code point
    for (auto v : vertices_range(h)) {
        if (is_virtual_start(v, h)) {
            bad.insert(v);
            insert(&bad, adjacent_vertices(v, h));
        }
    }

    /* we cannot handle vertices connected to accept as would report matches in
     * the middle of codepoints. acceptEod is not a problem as the input must
     * end at a codepoint boundary */
    bad.insert(h.accept);

    // If we're in SOM mode, we don't want to mess with vertices that have a
    // direct edge from startDs.
    if (som) {
        insert(&bad, adjacent_vertices(h.startDs, h));
    }

    set<NFAVertex> already_seeds; /* already marked as seeds */
    for (auto v : vertices_range(h)) {
        const CharReach &cr = h[v].char_reach;

        if (!isutf8ascii(cr) || !hasSelfLoop(v, h)) {
            continue;
        }

        if (hasSuccInSet(h, v, bad)) {
            continue;
        }

        // Skip vertices that are directly connected to other vertices already
        // in the seeds list: we can't collapse two of these directly next to
        // each other.
        if (hasPredInSet(h, v, already_seeds) ||
            hasSuccInSet(h, v, already_seeds)) {
            continue;
        }

        DEBUG_PRINTF("%zu is a seed\n", h[v].index);
        seeds->push_back(v);
        already_seeds.insert(v);
    }
}
コード例 #29
0
ファイル: usb_task.c プロジェクト: faa/purethermal1-firmware
void HAL_RCC_CSSCallback(void) {
	DEBUG_PRINTF("Oh no! HAL_RCC_CSSCallback()\r\n");
}
コード例 #30
0
static void fc3d_AC_initialize(FrictionContactProblem* problem,
                               FrictionContactProblem* localproblem,
                               SolverOptions * options)
{
  /** In initialize, these operators are "connected" to their corresponding static variables,
   * that will be used to build local problem for each considered contact.
   * Local problem is built during call to update (which depends on the storage type for M).
   */

  DEBUG_PRINTF("fc3d_AC_initialize starts with options->iparam[10] = %i\n",
               options->iparam[SICONOS_FRICTION_3D_NSN_FORMULATION]);

  if (options->iparam[SICONOS_FRICTION_3D_NSN_FORMULATION] ==
      SICONOS_FRICTION_3D_NSN_FORMULATION_ALARTCURNIER_STD )
  {
    Function = &(computeAlartCurnierSTD);
  }
  else if (options->iparam[SICONOS_FRICTION_3D_NSN_FORMULATION] ==
           SICONOS_FRICTION_3D_NSN_FORMULATION_JEANMOREAU_STD )
  {
    Function = &(computeAlartCurnierJeanMoreau);
  }
  else if (options->iparam[SICONOS_FRICTION_3D_NSN_FORMULATION] ==
           SICONOS_FRICTION_3D_NSN_FORMULATION_ALARTCURNIER_GENERATED )
  {
    Function = &(fc3d_AlartCurnierFunctionGenerated);
  }
  else if (options->iparam[SICONOS_FRICTION_3D_NSN_FORMULATION] ==
           SICONOS_FRICTION_3D_NSN_FORMULATION_JEANMOREAU_GENERATED )
  {
    Function = &fc3d_AlartCurnierJeanMoreauFunctionGenerated;;
  }
  else if (options->iparam[SICONOS_FRICTION_3D_NSN_FORMULATION] ==
           SICONOS_FRICTION_3D_NSN_FORMULATION_NULL)
  {
    Function = NULL;
  }

  /* Compute and store default value of rho value */
  int nc = problem->numberOfContacts;

  double avg_rho[3] = {0.0, 0.0, 0.0};

  if (options->solverId == SICONOS_FRICTION_3D_ONECONTACT_NSN ||
      options->solverId == SICONOS_FRICTION_3D_ONECONTACT_NSN_GP)
  {
    if (!options->dWork ||
        options->dWorkSize < 3*nc)
    {
      options->dWork = (double *)realloc(options->dWork,
                                         3*nc * sizeof(double));
      options->dWorkSize = 3*nc ;
    }
  }
  else if (options->solverId == SICONOS_FRICTION_3D_ONECONTACT_NSN_GP_HYBRID)
  {
    if (!options->dWork ||
        options->dWorkSize < 4*nc)
    {
      options->dWork = (double *)realloc(options->dWork,
                                         4*nc * sizeof(double));
      options->dWorkSize = 4*nc ;
    }
  }

  

  double  * rho;
  for (int contact =0; contact <nc ; contact++)
  {
    if (options->solverId == SICONOS_FRICTION_3D_ONECONTACT_NSN ||
        options->solverId == SICONOS_FRICTION_3D_ONECONTACT_NSN_GP)
    {
      rho = &options->dWork[3*contact];
    }
    else if (options->solverId == SICONOS_FRICTION_3D_ONECONTACT_NSN_GP_HYBRID)
    {
      options->dWork[contact] = 1.0; // for PLI algorithm.
      rho = &options->dWork[3*contact+nc];
    }
    numerics_printf("fc3d_AC_initialize "" compute rho for contact = %i",contact);

    if (options->iparam[SICONOS_FRICTION_3D_NSN_RHO_STRATEGY] == SICONOS_FRICTION_3D_NSN_FORMULATION_RHO_STRATEGY_SPLIT_SPECTRAL_NORM_COND)
    {
      fc3d_local_problem_fill_M(problem, localproblem, contact);
      compute_rho_split_spectral_norm_cond(localproblem, rho);
    }
    else if (options->iparam[SICONOS_FRICTION_3D_NSN_RHO_STRATEGY] == SICONOS_FRICTION_3D_NSN_FORMULATION_RHO_STRATEGY_SPLIT_SPECTRAL_NORM)
    {
      fc3d_local_problem_fill_M(problem, localproblem, contact);
      compute_rho_split_spectral_norm(localproblem, rho);
    }
    else if (options->iparam[SICONOS_FRICTION_3D_NSN_RHO_STRATEGY] == SICONOS_FRICTION_3D_NSN_FORMULATION_RHO_STRATEGY_SPECTRAL_NORM)
    {
      fc3d_local_problem_fill_M(problem, localproblem, contact);
      compute_rho_spectral_norm(localproblem, rho);
    }
    else if (options->iparam[SICONOS_FRICTION_3D_NSN_RHO_STRATEGY] == SICONOS_FRICTION_3D_NSN_FORMULATION_RHO_STRATEGY_CONSTANT)
    {
      rho[0]=options->dparam[SICONOS_FRICTION_3D_NSN_RHO];
      rho[1]=options->dparam[SICONOS_FRICTION_3D_NSN_RHO];
      rho[2]=options->dparam[SICONOS_FRICTION_3D_NSN_RHO];
    }
    else if (options->iparam[SICONOS_FRICTION_3D_NSN_RHO_STRATEGY] == SICONOS_FRICTION_3D_NSN_FORMULATION_RHO_STRATEGY_ADAPTIVE)
    {
      numerics_error("fc3d_AC_initialize", "Adaptive strategy for computing rho not yet implemented");
    }
    else
      numerics_error("fc3d_AC_initialize", "unknown strategy for computing rho");


    if (verbose >0)
    {
      avg_rho[0] += rho[0];
      avg_rho[1] += rho[1];
      avg_rho[2] += rho[2];
    }
    numerics_printf("fc3d_AC_initialize""contact = %i, rho[0] = %4.2e, rho[1] = %4.2e, rho[2] = %4.2e", contact, rho[0], rho[1], rho[2]);

    fc3d_local_problem_fill_M(problem, localproblem, contact);
    double m_row_norm = 0.0, sum;
    for (int i =0; i<3; i++ )
    {
      sum =0.0;
      for (int j =0; j<3; j++ )
      {
        sum += fabs(localproblem->M->matrix0[i+j*3]);
      }
      m_row_norm = max(sum, m_row_norm);
    }
    numerics_printf("fc3d_AC_initialize" " inverse of norm of M = %e", 1.0/hypot9(localproblem->M->matrix0) );
    numerics_printf("fc3d_AC_initialize" " inverse of row norm of M = %e", 1.0/m_row_norm );

    DEBUG_EXPR(NM_display(localproblem->M););

  }