Example #1
0
File: main.cpp Project: CCJY/coliru
int main()
{
    std::function<void()> func = f_display;
    std::thread t(func);
    t.join();
}
Example #2
0
/*
 * Notify registered targets except 'self' about register value change
 */
static void
s1394_cmp_notify_reg_change(s1394_hal_t *hal, t1394_cmp_reg_t reg,
    s1394_target_t *self)
{
	s1394_target_t	*target;
	s1394_fa_target_t *fat;
	uint_t		saved_gen;
	int		num_retries = 0;
	void		(*cb)(opaque_t, t1394_cmp_reg_t);
	opaque_t	arg;

	TNF_PROBE_0_DEBUG(s1394_cmp_notify_reg_change_enter,
	    S1394_TNF_SL_CMP_STACK, "");

	rw_enter(&hal->target_list_rwlock, RW_READER);

start:
	target = hal->hal_fa[S1394_FA_TYPE_CMP].fal_head;

	for (; target; target = fat->fat_next) {
		fat = &target->target_fa[S1394_FA_TYPE_CMP];

		/*
		 * even if the target list changes when the lock is dropped,
		 * comparing with self is safe because the target should
		 * not unregister until all CMP operations are completed
		 */
		if (target == self) {
			continue;
		}

		cb = fat->fat_u.cmp.cm_evts.cmp_reg_change;
		if (cb == NULL) {
			continue;
		}
		arg = fat->fat_u.cmp.cm_evts.cmp_arg;

		saved_gen = s1394_fa_list_gen(hal, S1394_FA_TYPE_CMP);

		rw_exit(&hal->target_list_rwlock);
		cb(arg, reg);
		rw_enter(&hal->target_list_rwlock, RW_READER);

		/*
		 * List could change while we dropped the lock. In such
		 * case, start all over again, because missing a register
		 * change can have more serious consequences for a
		 * target than receiving same notification more than once
		 */
		if (saved_gen != s1394_fa_list_gen(hal, S1394_FA_TYPE_CMP)) {
			TNF_PROBE_2(s1394_cmp_notify_reg_change_error,
			    S1394_TNF_SL_CMP_ERROR, "",
			    tnf_string, msg, "list gen changed",
			    tnf_opaque, num_retries, num_retries);
			if (++num_retries <= s1394_cmp_notify_retry_cnt) {
				goto start;
			} else {
				break;
			}
		}
	}

	rw_exit(&hal->target_list_rwlock);

	TNF_PROBE_0_DEBUG(s1394_cmp_notify_reg_change_exit,
	    S1394_TNF_SL_CMP_STACK, "");
}
Example #3
0
void _start()
{
	asm(
		"lis %r1, 0x1ab5 ;"
		"ori %r1, %r1, 0xd138 ;"
	);
	unsigned int coreinit_handle, gx2_handle;
	OSDynLoad_Acquire("coreinit", &coreinit_handle);
	OSDynLoad_Acquire("gx2", &gx2_handle);
	//OS Memory functions
	void*(*memset)(void * dest, unsigned int value, unsigned int bytes);
	void*(*OSAllocFromSystem)(unsigned int size, int align);
	void(*OSFreeToSystem)(void *ptr);
	//IM functions
	int(*IM_Open)();
	int(*IM_Close)(int fd);
	int(*IM_SetDeviceState)(int fd, void *mem, int state, int a, int b);

	//OS Memory functions
	OSDynLoad_FindExport(coreinit_handle, 0, "memset", &memset);
	OSDynLoad_FindExport(coreinit_handle, 0, "OSAllocFromSystem", &OSAllocFromSystem);
	OSDynLoad_FindExport(coreinit_handle, 0, "OSFreeToSystem", &OSFreeToSystem);
	//IM functions
	OSDynLoad_FindExport(coreinit_handle, 0, "IM_Open", &IM_Open);
	OSDynLoad_FindExport(coreinit_handle, 0, "IM_Close", &IM_Close);
	OSDynLoad_FindExport(coreinit_handle, 0, "IM_SetDeviceState", &IM_SetDeviceState);
	//Restart system to get lib access
	int fd = IM_Open();
	void *mem = OSAllocFromSystem(0x100, 64);
	memset(mem, 0, 0x100);
	//set restart flag to force quit browser
	IM_SetDeviceState(fd, mem, 3, 0, 0); 
	IM_Close(fd);
	OSFreeToSystem(mem);
	//wait a bit for browser end
	unsigned int t1 = 0x1FFFFFFF;
	while(t1--) ;

	/* Get the framebuffer of the TV or DRC */
	void(*GX2SwapScanBuffers)();
	OSDynLoad_FindExport(gx2_handle, 0, "GX2SwapScanBuffers", &GX2SwapScanBuffers);
	unsigned char *abuseFunc = (unsigned char*)GX2SwapScanBuffers;
	unsigned short f_hi = *(unsigned short*)(abuseFunc+0x12);
	unsigned short f_lo = *(unsigned short*)(abuseFunc+0x16);
	unsigned int gx2settingBase = (((f_lo & 0x8000) ? (f_hi-1) : f_hi) << 16) | f_lo;
	unsigned int args[2];
	args[0] = *((unsigned int*)(gx2settingBase + 0x304));
	args[1] = *((unsigned int*)(gx2settingBase + 0x304 + 0x20));
	int(*OSGetCoreId)();
	OSDynLoad_FindExport(coreinit_handle, 0, "OSGetCoreId", &OSGetCoreId);
	void(*OSTestThreadCancel)();
	OSDynLoad_FindExport(coreinit_handle, 0, "OSTestThreadCancel", &OSTestThreadCancel);
	void(*GX2Shutdown)();
	OSDynLoad_FindExport(gx2_handle, 0, "GX2Shutdown", &GX2Shutdown);
	int(*GX2GetMainCoreId)();
	OSDynLoad_FindExport(gx2_handle, 0, "GX2GetMainCoreId", &GX2GetMainCoreId);

	/* Prepare for our own death */
	void*(*OSGetCurrentThread)();
	OSDynLoad_FindExport(coreinit_handle, 0, "OSGetCurrentThread", &OSGetCurrentThread);
	void *myBorkedThread = OSGetCurrentThread();
	int (*OSSuspendThread)(void *thread);
	OSDynLoad_FindExport(coreinit_handle, 0, "OSSuspendThread", &OSSuspendThread);

	/* Prepare for thread startups */
	int (*OSCreateThread)(void *thread, void *entry, int argc, void *args, unsigned int stack, unsigned int stack_size, int priority, unsigned short attr);
	int (*OSResumeThread)(void *thread);
	int (*OSIsThreadTerminated)(void *thread);

	OSDynLoad_FindExport(coreinit_handle, 0, "OSCreateThread", &OSCreateThread);
	OSDynLoad_FindExport(coreinit_handle, 0, "OSResumeThread", &OSResumeThread);
	OSDynLoad_FindExport(coreinit_handle, 0, "OSIsThreadTerminated", &OSIsThreadTerminated);

	/* Allocate a stack for the thread */
	unsigned int stack = (unsigned int) OSAllocFromSystem(0x1000, 0x10);
	stack += 0x1000;
	/* Create the thread */
	void *thread = OSAllocFromSystem(OSTHREAD_SIZE, 8);
	
	if(OSGetCoreId() != GX2GetMainCoreId()) //needed for access without crashing
	{
		int ret = OSCreateThread(thread, GX2Shutdown, 0, (void*)0, stack, 0x1000, 0, 0x10 | (1<<GX2GetMainCoreId()));
		if (ret == 0)
			OSFatal("Failed to create thread");
		/* Schedule it for execution */
		OSResumeThread(thread);
		while(OSIsThreadTerminated(thread) == 0) ;
	}
	else //same core, easy
		GX2Shutdown();

	//current thread is broken, switch to a working one in core 1
	int ret = OSCreateThread(thread, myGXthread, 2, args, stack, 0x1000, 0, 0xA);
	if (ret == 0)
		OSFatal("Failed to create thread");

	/* Schedule it for execution */
	OSResumeThread(thread);
	/* SO UGLY but it works magically */
	while(1) ;
	//would be better but again, crashes 5.3.2
	//OSSuspendThread(myBorkedThread);
	//OSFatal("I am still not dead!");
}
Example #4
0
    { "vtshow",		do_vtshow, NULL },		/*  9 */
    { "vtmode",		do_vtmode, NULL },		/* 10 */
    { "tekhide",	do_tekhide, NULL }};		/* 11 */
#endif

static Widget create_menu (
		XtermWidget xtw,
		Widget toplevelw,
		char *name,
		struct _MenuEntry *entries,
		int nentries);

static void handle_send_signal (Widget gw, int sig);

static void handle_toggle (
		void (*proc)PROTO_XT_CALLBACK_ARGS,
		int var,
		String *params,
		Cardinal nparams,
		Widget w,
		XtPointer closure,
		XtPointer data);

extern Widget toplevel;


/*
 * we really want to do these dynamically
 */
#define check_width 9
#define check_height 8
Example #5
0
int main(int argc, char** argv)
{
  // in case generate shared memory to pointer area_addr
  // address work area
  char *area_addr = NULL; 

  // work area
  register int area_id=0;

  // ptr to current state entry
  register struct state *pState=NULL;

  // SIGSEGV state hold area func ptr
  void (*savefunc) ();

  // action to be performed
  register int action=0;
  while(0 != (action = ask())){
    if(0 < nap){
      fprintf(stderr, "currently attached segments");
      fprintf(stderr, " shm_id address\n");
      fprintf(stderr, "------- ---------\n");
      pState = &attached_segments[nap+1];
      while(--pState != attached_segments){
	fprintf(stderr, "%6d", pState->shm_id);
	fprintf(stderr, "%#11x", (unsigned int) pState->shm_addr);
	fprintf(stderr, " Read%s\n", (pState->shm_flag & SHM_RDONLY) ? "-Only" : "/Write");	
      }
      fprintf(stderr, "\n");

    }else{
      fprintf(stderr, "no segments are currently attached\n");      
      switch(action){
      case 1:
	// 1 - verify that there is space for another attach
	if(nap == MAXnap){
	  fprintf(stderr, "this simple example will only allow %d attached segments\n", MAXnap);
	  break;
	}
	// get the arguments, make the call, report the result and update the current state array
	pState = &attached_segments[++nap];

	readnumber(&pState->shm_id, ID_DIGITS, "enter shm_id of segment to attach:");
	readstring(pState->shm_addr, ADDR_DIGITS, "enter shm_addr");
	fprintf(stderr, "meaningful shm_flag vlaues are:\n");
	fprintf(stderr, "1\tSHM_RDONLY (%d)\n", SHM_RDONLY);
	fprintf(stderr, "2\tSHM_RND (%d)\n", SHM_RND);
	unsigned int select=0;
	unsigned int askagain=0;
	do{
	  askagain=0;
	  readdigit(&select, "select a shm_flag");
	  switch(select){
	  case 1:
	    puts("SHM_RDONLY");
	    pState->shm_flag = SHM_RDONLY;
	    break;

	  case 2:
	    puts("SHM_RND");
	    pState->shm_flag = SHM_RND;
	    break;

	  default:
	    puts("wrong input - try again");
	    askagain = 1;
	    break;
	  }
	}while(askagain);
	fprintf(stderr, "now attach the segment - shmat(%d, %#x, %#o)\n"
		, pState->shm_id, (unsigned int) pState->shm_addr, pState->shm_flag);

	if(0 > (pState->shm_addr = shmat(pState->shm_id, pState->shm_addr, pState->shm_flag))){
	  perror("shmat() failed");
	  --nap; // decrement, because already incremented above, for new pointer element!
	}else{
	  fprintf(stderr, "shmat returned %#8.8x\n", (unsigned int) pState->shm_addr);
	}
	break;
	
      case 2:
	// 2 - shmdt requested
	/*
	  get the address, make the call, report the results and make the 
	  internal state match
	//*/
	readstring(area_addr, ADDR_DIGITS, "enter detach shm_addr");
     	if(-1 == (area_id = shmdt(area_addr))){
	  perror("shmdt failed");
	}else{
	  fprintf(stderr, "shmdt returned %d\n", area_id);
	  for(pState = attached_segments, area_id = nap; --area_id; ++pState){
	    if(0 != (pState->shm_addr = area_addr)) 
	      *pState = attached_segments[--nap];
	  }
	}	
	break;
	
      case 3:
	if(nap == 0) break;
	
	readstring(area_addr, ADDR_DIGITS, "enter address of an attached segment");
	if(good_addr(area_addr))
	  fprintf(stderr, "string @ %#x is '%s'\n",(unsigned int) area_addr, area_addr);
	break;

      case 4:
	if(nap == 0) break;
	readstring(area_addr, ADDR_DIGITS, "enter address of an attached segment");
	
	/*
	  set up SIGSEGV signal handler to trap attempts to write into a read-only 
	  attached segment
	//*/
	savefunc = signal(SIGSEGV, signalhandler);

	if(setjmp(segvbuf)){
	  fprintf(stderr, "SIGSEGV signal caught: write aborted\n");
	  fflush(stdin); 
	  signal(SIGSEGV, savefunc);
	}else{
	  if(good_addr(area_addr)){
	    fflush(stdin);
	    readstring(area_addr, AREA_DIGITS, "enter one line to e copied to the shared segment attached");
	    // TODO: check
	    if(NULL == strncpy(pState->shm_addr, (char*) -1, sizeof(char*))){
	      perror("strncpy to shared memory failed");
	      break;
	    }
	  }
	}
	break;
      }
    }
  }

  // not reached
  puts("READY.");
  exit(EXIT_SUCCESS);
}
Example #6
0
void setupEfiTables64(void)
{
	struct fake_efi_pages
	{
		EFI_SYSTEM_TABLE_64 efiSystemTable;
		EFI_RUNTIME_SERVICES_64 efiRuntimeServices;
		EFI_CONFIGURATION_TABLE_64 efiConfigurationTable[MAX_CONFIGURATION_TABLE_ENTRIES];
		EFI_CHAR16 firmwareVendor[sizeof(FIRMWARE_VENDOR)/sizeof(EFI_CHAR16)];
		uint8_t voidret_instructions[sizeof(VOIDRET_INSTRUCTIONS)/sizeof(uint8_t)];
		uint8_t unsupportedret_instructions[sizeof(UNSUPPORTEDRET_INSTRUCTIONS)/sizeof(uint8_t)];
	};
	
	struct fake_efi_pages *fakeEfiPages = (struct fake_efi_pages*)AllocateKernelMemory(sizeof(struct fake_efi_pages));
	
	// Zero out all the tables in case fields are added later
	bzero(fakeEfiPages, sizeof(struct fake_efi_pages));
	
	// --------------------------------------------------------------------
	// Initialize some machine code that will return EFI_UNSUPPORTED for
	// functions returning int and simply return for void functions.
	memcpy(fakeEfiPages->voidret_instructions, VOIDRET_INSTRUCTIONS, sizeof(VOIDRET_INSTRUCTIONS));
	memcpy(fakeEfiPages->unsupportedret_instructions, UNSUPPORTEDRET_INSTRUCTIONS, sizeof(UNSUPPORTEDRET_INSTRUCTIONS));
	
	// --------------------------------------------------------------------
	// System table
	EFI_SYSTEM_TABLE_64 *efiSystemTable = gST64 = &fakeEfiPages->efiSystemTable;
	efiSystemTable->Hdr.Signature = EFI_SYSTEM_TABLE_SIGNATURE;
	efiSystemTable->Hdr.Revision = EFI_SYSTEM_TABLE_REVISION;
	efiSystemTable->Hdr.HeaderSize = sizeof(EFI_SYSTEM_TABLE_64);
	efiSystemTable->Hdr.CRC32 = 0; // Initialize to zero and then do CRC32
	efiSystemTable->Hdr.Reserved = 0;
	
	efiSystemTable->FirmwareVendor = ptov64((EFI_PTR32)&fakeEfiPages->firmwareVendor);
	memcpy(fakeEfiPages->firmwareVendor, FIRMWARE_VENDOR, sizeof(FIRMWARE_VENDOR));
	efiSystemTable->FirmwareRevision = FIRMWARE_REVISION;
	
	// XXX: We may need to have basic implementations of ConIn/ConOut/StdErr
	// The EFI spec states that all handles are invalid after boot services have been
	// exited so we can probably get by with leaving the handles as zero.
	efiSystemTable->ConsoleInHandle = 0;
	efiSystemTable->ConIn = 0;
	
	efiSystemTable->ConsoleOutHandle = 0;
	efiSystemTable->ConOut = 0;
	
	efiSystemTable->StandardErrorHandle = 0;
	efiSystemTable->StdErr = 0;
	
	efiSystemTable->RuntimeServices = ptov64((EFI_PTR32)&fakeEfiPages->efiRuntimeServices);
	// According to the EFI spec, BootServices aren't valid after the
	// boot process is exited so we can probably do without it.
	// Apple didn't provide a definition for it in pexpert/i386/efi.h
	// so I'm guessing they don't use it.
	efiSystemTable->BootServices = 0;
	
	efiSystemTable->NumberOfTableEntries = 0;
	efiSystemTable->ConfigurationTable = ptov64((EFI_PTR32)fakeEfiPages->efiConfigurationTable);
	
	// We're done.	Now CRC32 the thing so the kernel will accept it
	gST64->Hdr.CRC32 = crc32(0L, gST64, gST64->Hdr.HeaderSize);
	
	// --------------------------------------------------------------------
	// Runtime services
	EFI_RUNTIME_SERVICES_64 *efiRuntimeServices = &fakeEfiPages->efiRuntimeServices;
	efiRuntimeServices->Hdr.Signature = EFI_RUNTIME_SERVICES_SIGNATURE;
	efiRuntimeServices->Hdr.Revision = EFI_RUNTIME_SERVICES_REVISION;
	efiRuntimeServices->Hdr.HeaderSize = sizeof(EFI_RUNTIME_SERVICES_64);
	efiRuntimeServices->Hdr.CRC32 = 0;
	efiRuntimeServices->Hdr.Reserved = 0;
	
	// There are a number of function pointers in the efiRuntimeServices table.
	// These are the Foundation (e.g. core) services and are expected to be present on
	// all EFI-compliant machines.	Some kernel extensions (notably AppleEFIRuntime)
	// will call these without checking to see if they are null.
	//
	// We don't really feel like doing an EFI implementation in the bootloader
	// but it is nice if we can at least prevent a complete crash by
	// at least providing some sort of implementation until one can be provided
	// nicely in a kext.
	
	void (*voidret_fp)() = (void*)fakeEfiPages->voidret_instructions;
	void (*unsupportedret_fp)() = (void*)fakeEfiPages->unsupportedret_instructions;
	efiRuntimeServices->GetTime = ptov64((EFI_PTR32)unsupportedret_fp);
	efiRuntimeServices->SetTime = ptov64((EFI_PTR32)unsupportedret_fp);
	efiRuntimeServices->GetWakeupTime = ptov64((EFI_PTR32)unsupportedret_fp);
	efiRuntimeServices->SetWakeupTime = ptov64((EFI_PTR32)unsupportedret_fp);
	efiRuntimeServices->SetVirtualAddressMap = ptov64((EFI_PTR32)unsupportedret_fp);
	efiRuntimeServices->ConvertPointer = ptov64((EFI_PTR32)unsupportedret_fp);
	efiRuntimeServices->GetVariable = ptov64((EFI_PTR32)unsupportedret_fp);
	efiRuntimeServices->GetNextVariableName = ptov64((EFI_PTR32)unsupportedret_fp);
	efiRuntimeServices->SetVariable = ptov64((EFI_PTR32)unsupportedret_fp);
	efiRuntimeServices->GetNextHighMonotonicCount = ptov64((EFI_PTR32)unsupportedret_fp);
	efiRuntimeServices->ResetSystem = ptov64((EFI_PTR32)voidret_fp);
	
	// We're done.	Now CRC32 the thing so the kernel will accept it
	efiRuntimeServices->Hdr.CRC32 = crc32(0L, efiRuntimeServices, efiRuntimeServices->Hdr.HeaderSize);
	
	// --------------------------------------------------------------------
	// Finish filling in the rest of the boot args that we need.
	bootArgs->efiSystemTable = (uint32_t)efiSystemTable;
	bootArgs->efiMode = kBootArgsEfiMode64;
	
	// The bootArgs structure as a whole is bzero'd so we don't need to fill in
	// things like efiRuntimeServices* and what not.
	//
	// In fact, the only code that seems to use that is the hibernate code so it
	// knows not to save the pages.	 It even checks to make sure its nonzero.
}
static void displayQRCode(const char *secret) {
  char *encoderURL;
  const char *url = getURL(secret, &encoderURL);
  puts(encoderURL);

  // Only newer systems have support for libqrencode. So, instead of requiring
  // it at build-time, we look for it at run-time. If it cannot be found, the
  // user can still type the code in manually, or he can copy the URL into
  // his browser.
  if (isatty(1)) {
    void *qrencode = dlopen("libqrencode.so.2", RTLD_NOW | RTLD_LOCAL);
    if (!qrencode) {
      qrencode = dlopen("libqrencode.so.3", RTLD_NOW | RTLD_LOCAL);
    }
    if (qrencode) {
      typedef struct {
        int version;
        int width;
        unsigned char *data;
      } QRcode;
      QRcode *(*QRcode_encodeString8bit)(const char *, int, int) =
        (QRcode *(*)(const char *, int, int))
        dlsym(qrencode, "QRcode_encodeString8bit");
      void (*QRcode_free)(QRcode *qrcode) =
        (void (*)(QRcode *))dlsym(qrencode, "QRcode_free");
      if (QRcode_encodeString8bit && QRcode_free) {
        QRcode *qrcode = QRcode_encodeString8bit(url, 0, 1);
        char *ptr = (char *)qrcode->data;
        // Output QRCode using ANSI colors. Instead of black on white, we
        // output black on grey, as that works independently of whether the
        // user runs his terminals in a black on white or white on black color
        // scheme.
        // But this requires that we print a border around the entire QR Code.
        // Otherwise, readers won't be able to recognize it.
        if (!useBlockElements) {
          for (int i = 0; i < 2; ++i) {
            printf(ANSI_BLACKONGREY);
            for (int x = 0; x < qrcode->width + 4; ++x) printf("  ");
            puts(ANSI_RESET);
          }
          for (int y = 0; y < qrcode->width; ++y) {
            printf(ANSI_BLACKONGREY"    ");
            int isBlack = 0;
            for (int x = 0; x < qrcode->width; ++x) {
              if (*ptr++ & 1) {
                if (!isBlack) {
                  printf(ANSI_BLACK);
                }
                isBlack = 1;
              } else {
                if (isBlack) {
                  printf(ANSI_WHITE);
                }
                isBlack = 0;
              }
              printf("  ");
            }
            if (isBlack) {
              printf(ANSI_WHITE);
            }
            puts("    "ANSI_RESET);
          }
          for (int i = 0; i < 2; ++i) {
            printf(ANSI_BLACKONGREY);
            for (int x = 0; x < qrcode->width + 4; ++x) printf("  ");
            puts(ANSI_RESET);
          }
        } else {
          // Drawing the QRCode with Unicode block elements is desirable as
          // it makes the code much smaller, which is often easier to scan.
          // Unfortunately, many terminal emulators do not display these
          // Unicode characters properly.
          printf(ANSI_BLACKONGREY);
          for (int i = 0; i < qrcode->width + 4; ++i) {
            printf(" ");
          }
          puts(ANSI_RESET);
          for (int y = 0; y < qrcode->width; y += 2) {
            printf(ANSI_BLACKONGREY"  ");
            for (int x = 0; x < qrcode->width; ++x) {
              int top = qrcode->data[y*qrcode->width + x] & 1;
              int bottom = 0;
              if (y+1 < qrcode->width) {
                bottom = qrcode->data[(y+1)*qrcode->width + x] & 1;
              }
              if (top) {
                if (bottom) {
                  printf(UTF8_BOTH);
                } else {
                  printf(UTF8_TOPHALF);
                }
              } else {
                if (bottom) {
                  printf(UTF8_BOTTOMHALF);
                } else {
                  printf(" ");
                }
              }
            }
            puts("  "ANSI_RESET);
          }
          printf(ANSI_BLACKONGREY);
          for (int i = 0; i < qrcode->width + 4; ++i) {
            printf(" ");
          }
          puts(ANSI_RESET);
        }
        QRcode_free(qrcode);
      }
      dlclose(qrencode);
    }
  }

  free((char *)url);
  free(encoderURL);
}
Example #8
0
File: malloc.c Project: efcs/clang
void mallocCastToFP() {
  void *p = malloc(2);
  void (*fp)() = p; // not crash
  free(p);
}
Example #9
0
File: event.c Project: xorg62/wmfs
static void
event_clientmessageevent(XEvent *e)
{
     XClientMessageEvent *ev = &e->xclient;
     struct client *c;
     struct _systray *sy;
     int type = 0;

     while(type < net_last && W->net_atom[type] != ev->message_type)
          ++type;

     /*
      * Systray message
      * _NET_WM_SYSTRAY_TRAY_OPCODE
      */
     if(ev->window == W->systray.win && type == net_system_tray_opcode)
     {
          if(ev->data.l[1] == XEMBED_EMBEDDED_NOTIFY)
          {
               systray_add(ev->data.l[2]);
               systray_update();
          }
          else if(ev->data.l[1] == XEMBED_REQUEST_FOCUS)
          {
               if((sy = systray_find(ev->data.l[2])))
                    ewmh_send_message(sy->win, sy->win, "_XEMBED", XEMBED_FOCUS_IN,
                                      XEMBED_FOCUS_CURRENT, 0, 0, 0);
          }
     }
     else if(ev->window == W->root)
     {
          /* WMFS message */
          if(ev->data.l[4])
          {
               /* Manage _WMFS_FUNCTION && _WMFS_CMD */
               if(type == wmfs_function || type == wmfs_cmd)
               {
                    Atom rt;
                    int d;
                    long unsigned int len, il;
                    unsigned char *ret = NULL, *ret_cmd = NULL;
                    void (*func)(Uicb);

                    if(XGetWindowProperty(EVDPY(e), W->root, W->net_atom[wmfs_function], 0, 65536,
                                          False, W->net_atom[utf8_string], &rt, &d,
                                          &len, &il, &ret) == Success
                       && ret && ((func = uicb_name_func((char*)ret))))
                    {
                         if(XGetWindowProperty(EVDPY(e), W->root, W->net_atom[wmfs_cmd], 0, 65536,
                                               False, W->net_atom[utf8_string], &rt, &d,
                                               &len, &il, &ret_cmd) == Success
                            && len && ret_cmd)
                         {
                              func((Uicb)ret_cmd);
                              XFree(ret_cmd);
                         }
                         else
                              func(NULL);

                         XFree(ret);
                    }
               }
          }

          if(type == net_active_window)
               if((sy = systray_find(ev->data.l[0])))
                    XSetInputFocus(W->dpy, sy->win, RevertToNone, CurrentTime);
     }

     switch(type)
     {
          /* _NET_WM_STATE */
          case net_wm_state:
               if((c = client_gb_win(ev->window)))
                    ewmh_manage_state(ev->data.l, c);
               break;
          /* _NET_CLOSE_WINDOW */
          case net_close_window:
               if((c = client_gb_win(ev->window)))
                    client_close(c);
               break;
          /* _NET_WM_DESKTOP */
          case net_wm_desktop:
               break;
     }
}
Example #10
0
int do_exec(char* com, char* wd)
{
	char    path[MAXPATHLEN];
	char    pcom[MAXCOMSZ];
	char   *arglist[MAXARGS];
	char   *tz;
	register int i, len;
	register int argptr;
	int     status, pid, w;
	int     pmode;
	void    (*isig) (), (*qsig) ();

	strncpy(path, BINDIR, MAXPATHLEN);
	strncpy(pcom, com, MAXCOMSZ);
	len = Min(strlen(com) + 1, MAXCOMSZ);
	pmode = LOOKFIRST;
	for (i = 0, argptr = 0; i < len; i++)
	{
		if (pcom[i] == '\0')
			break;
		if (pmode == QUOTEMODE)
		{
			if (pcom[i] == '\001')
			{
				pmode = LOOKFIRST;
				pcom[i] = '\0';
				continue;
			}
			continue;
		}
		if (pcom[i] == '\001')
		{
			pmode = QUOTEMODE;
			arglist[argptr++] = &pcom[i + 1];
			if (argptr + 1 == MAXARGS)
				break;
			continue;
		}
		if (pmode == LOOKFIRST)
			if (pcom[i] != ' ')
			{
				arglist[argptr++] = &pcom[i];
				if (argptr + 1 == MAXARGS)
					break;
				pmode = LOOKLAST;
			}
			else
				continue;
		if (pcom[i] == ' ')
		{
			pmode = LOOKFIRST;
			pcom[i] = '\0';
		}
	}
	arglist[argptr] = NULL;
	if (argptr == 0)
		return -1;
	if (*arglist[0] == '/')
		strncpy(path, arglist[0], MAXPATHLEN);
	else
		strncat(path, arglist[0], MAXPATHLEN);
	reset_tty();
	alarm(0);
#ifdef IRIX

	if ((pid = fork()) == 0)
	{
#else
	if ((pid = vfork()) == 0)
	{
#endif

#ifdef BBSD
		waitpid(pid, &status, 0);
#endif

		if (wd)
			if (chdir(wd))
			{
				sprintf(genbuf, "Unable to chdir to '%s'\n", wd);
				report(genbuf);
				exit(-1);
			}

		bbssetenv("PATH", "/bin:.");
		bbssetenv("TERM", currentuser.termtype);
		bbssetenv("USER", currentuser.userid);
		bbssetenv("USERNAME", currentuser.username);

		if ((tz = getenv("TZ")) != NULL)
			bbssetenv("TZ", tz);
		if (numbbsenvs == 0)
			bbsenv[0] = NULL;
		//dup2(0,1);
		//dup2(0,2);
		execve(path, arglist, bbsenv);
		sprintf(genbuf, "EXECV FAILED... path = '%s'\n", path);
		report(genbuf);
		exit(-1);
	}
	isig = signal(SIGINT, SIG_IGN);
	qsig = signal(SIGQUIT, SIG_IGN);
#ifndef BBSD

	while ((w = wait(&status)) != pid && w != 1)
		/* NULL STATEMENT */
		;
#endif

	signal(SIGINT, isig);
	signal(SIGQUIT, qsig);
	restore_tty();
#ifdef DOTIMEOUT

	alarm(IDLE_TIMEOUT);
#endif

	return ((w == -1) ? w : status);
}

char* horoscope(int month, int day)
{
	char   *name[12] = {
	                       "ĦôÉ", "ˮƿ", "Ë«Óã", "ĵÑò", "½ðÅ£", "Ë«×Ó",
	                       "¾Þз", "ʨ×Ó", "´¦Å®", "Ìì³Ó", "ÌìЫ", "ÉäÊÖ"
	                   };
	switch (month)
	{
	case 1:
		if (day < 21)
			return (name[0]);
		else
			return (name[1]);
	case 2:
		if (day < 19)
			return (name[1]);
		else
			return (name[2]);
	case 3:
		if (day < 21)
			return (name[2]);
		else
			return (name[3]);
	case 4:
		if (day < 21)
			return (name[3]);
		else
			return (name[4]);
	case 5:
		if (day < 21)
			return (name[4]);
		else
			return (name[5]);
	case 6:
		if (day < 22)
			return (name[5]);
		else
			return (name[6]);
	case 7:
		if (day < 23)
			return (name[6]);
		else
			return (name[7]);
	case 8:
		if (day < 23)
			return (name[7]);
		else
			return (name[8]);
	case 9:
		if (day < 23)
			return (name[8]);
		else
			return (name[9]);
	case 10:
		if (day < 24)
			return (name[9]);
		else
			return (name[10]);
	case 11:
		if (day < 23)
			return (name[10]);
		else
			return (name[11]);
	case 12:
		if (day < 22)
			return (name[11]);
		else
			return (name[0]);
	}
	return ("²»Ïê");
}
Example #11
0
File: main.cpp Project: CCJY/coliru
void doPrint(std::ostream& out, Arg&& arg, Args&&... args)
{
    std::cout << std::forward<Arg>(arg);
    using expander = int[];
    (void)expander{0, (void(std::cout << "," << std::forward<Args>(args)),0)...};
}
Example #12
0
void mtvm_menu_main(switch_core_session_t *session, vmivr_profile_t *profile) {
	switch_channel_t *channel = switch_core_session_get_channel(session);
	switch_event_t *msg_list_params = NULL;
	size_t msg_count = 0;
	size_t current_msg = 1;
	size_t next_msg = current_msg;
	size_t previous_msg = current_msg;
	char *cmd = NULL;
	int retry;

	/* Different switch to control playback of phrases */
	switch_bool_t initial_count_played = SWITCH_FALSE;
	switch_bool_t skip_header = SWITCH_FALSE;
	switch_bool_t msg_deleted = SWITCH_FALSE;
	switch_bool_t msg_undeleted = SWITCH_FALSE;
	switch_bool_t msg_saved = SWITCH_FALSE;

	vmivr_menu_profile_t menu = { "std_navigator" };

	/* Initialize Menu Configs */
	populate_profile_menu_event(profile, &menu);

	if (!menu.event_keys_dtmf || !menu.event_phrases) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing Menu Phrases and Keys\n");
		return;
	}

	/* Get VoiceMail List And update msg count */
	cmd = switch_core_session_sprintf(session, "json %s %s %s", profile->api_profile, profile->domain, profile->id);
	msg_list_params = jsonapi2event(session, NULL, profile->api_msg_list, cmd);
	msg_count = atol(switch_event_get_header(msg_list_params,"VM-List-Count"));

	/* TODO Add Detection of new message and notify the user */

	for (retry = MAX_ATTEMPT; switch_channel_ready(channel) && retry > 0; retry--) {
		dtmf_ss_t loc;
		char *dtmfa[16] = { 0 };
		switch_event_t *phrase_params = NULL;

		switch_event_create(&phrase_params, SWITCH_EVENT_REQUEST_PARAMS);

		append_event_profile(phrase_params, profile, menu);

		populate_dtmfa_from_event(phrase_params, profile, menu, dtmfa);

		previous_msg = current_msg;

		/* Simple Protection to not go out of msg list scope */
		/* TODO: Add Prompt to notify they reached the begining or the end */
		if (next_msg == 0) {
			next_msg = 1;
		} else if (next_msg > msg_count) {
			next_msg = msg_count;
		} 

		current_msg = next_msg;

		captureMenuInitialize(&loc, dtmfa);

		/* Prompt related to previous Message here */
		append_event_message(session, profile, phrase_params, msg_list_params, previous_msg);
		if (msg_deleted) {
			msg_deleted = SWITCH_FALSE;
			captureMenu(session, &loc, switch_event_get_header(menu.event_phrases, "ack"), "deleted", phrase_params, NULL, 0);
		}
		if (msg_undeleted) {
			msg_undeleted = SWITCH_FALSE;
			captureMenu(session, &loc, switch_event_get_header(menu.event_phrases, "ack"), "undeleted", phrase_params, NULL, 0);
		} 
		if (msg_saved) {
			msg_saved = SWITCH_FALSE;
			captureMenu(session, &loc, switch_event_get_header(menu.event_phrases, "ack"), "saved", phrase_params, NULL, 0);
		}

		/* Prompt related the current message */
		append_event_message(session, profile, phrase_params, msg_list_params, current_msg);

		/* TODO check if msg is gone (purged by another session, notify user and auto jump to next message or something) */
		if (!skip_header) {
			if (!initial_count_played) {
				cmd = switch_core_session_sprintf(session, "json %s %s %s", profile->api_profile, profile->domain, profile->id);
				jsonapi2event(session, phrase_params, profile->api_msg_count, cmd);
				initial_count_played = SWITCH_TRUE;
				captureMenu(session, &loc, switch_event_get_header(menu.event_phrases, "msg_count"), NULL, phrase_params, NULL, 0);
			}
			if (msg_count > 0) {
				captureMenu(session, &loc, switch_event_get_header(menu.event_phrases, "say_msg_number"), NULL, phrase_params, NULL, 0);
				captureMenu(session, &loc, switch_event_get_header(menu.event_phrases, "say_date"), NULL, phrase_params, NULL, 0);
			}
		}
		if (msg_count > 0) {
			/* TODO Update the Read date of a message (When msg start, or when it listen compleatly ??? To be determined */
			captureMenu(session, &loc, switch_event_get_header(menu.event_phrases, "play_message"), NULL, phrase_params, NULL, 0);
		}
		skip_header = SWITCH_FALSE;

		captureMenu(session, &loc, switch_event_get_header(menu.event_phrases, "menu_options"), NULL, phrase_params, NULL, DEFAULT_IVR_TIMEOUT);

		if (loc.result == RES_TIMEOUT) {
			/* TODO Ask for the prompt Again IF retry != 0 */
		} else if (loc.result == RES_INVALID) {
			/* TODO Say invalid option, and ask for the prompt again IF retry != 0 */
		} else if (loc.result == RES_FOUND) {  /* Matching DTMF Key Pressed */
			const char *action = switch_event_get_header(menu.event_keys_dtmf, loc.dtmf_stored);

			/* Reset the try count */
			retry = MAX_ATTEMPT;

			if (action) {
				if (!strcasecmp(action, "skip_intro")) { /* Skip Header / Play the recording again */
					skip_header = SWITCH_TRUE;
				} else if (!strcasecmp(action, "next_msg")) { /* Next Message */
					next_msg++;
				} else if (!strcasecmp(action, "prev_msg")) { /* Previous Message */
					next_msg--;
				} else if (!strcasecmp(action, "delete_msg")) { /* Delete / Undelete Message */
					if (strncasecmp(switch_event_get_header(phrase_params, "VM-Message-Flags"), "delete", 6)) {
						cmd = switch_core_session_sprintf(session, "%s %s %s %s", profile->api_profile, profile->domain, profile->id, switch_event_get_header(phrase_params, "VM-Message-UUID"));
						mt_api_execute(session, profile->api_msg_delete, cmd);

						msg_deleted = SWITCH_TRUE;
						/* TODO Option for auto going to next message or just return to the menu (So user used to do 76 to delete and next message wont be confused) */
						next_msg++;
					} else { 
						cmd = switch_core_session_sprintf(session, "%s %s %s %s", profile->api_profile, profile->domain, profile->id, switch_event_get_header(phrase_params, "VM-Message-UUID"));
						mt_api_execute(session, profile->api_msg_undelete, cmd);

						msg_undeleted = SWITCH_TRUE;
					}
				} else if (!strcasecmp(action, "save_msg")) { /* Save Message */
					cmd = switch_core_session_sprintf(session, "%s %s %s %s", profile->api_profile, profile->domain, profile->id, switch_event_get_header(phrase_params, "VM-Message-UUID"));
					mt_api_execute(session, profile->api_msg_save, cmd);

					msg_saved = SWITCH_TRUE;
				} else if (!strncasecmp(action, "menu:", 5)) { /* Sub Menu */
					void (*fPtr)(switch_core_session_t *session, vmivr_profile_t *profile) = mtvm_get_menu_function(action+5);
					if (fPtr) {
						fPtr(session, profile);
					}
				} else if (!strcasecmp(action, "return")) { /* Return */
					retry = -1;
				}
			}
		}

		/* IF the API to get the message returned us a COPY of the file locally (temp file create from a DB or from a web server), delete it */
		if (switch_true(switch_event_get_header(phrase_params, "VM-Message-Private-Local-Copy"))) {
			const char *file_path = switch_event_get_header(phrase_params, "VM-Message-File-Path");
			if (file_path && unlink(file_path) != 0) {
				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Failed to delete temp file [%s]\n", file_path);
			}
		}
		switch_event_destroy(&phrase_params);
	}

	switch_event_destroy(&msg_list_params);

	free_profile_menu_event(&menu);

	return;
}
Example #13
0
switch_status_t mtvm_menu_record(switch_core_session_t *session, vmivr_profile_t *profile, vmivr_menu_profile_t menu, const char *file_name) {
	switch_status_t status = SWITCH_STATUS_FALSE;
	switch_channel_t *channel = switch_core_session_get_channel(session);
	int retry;

	switch_bool_t record_prompt = SWITCH_TRUE;
	switch_bool_t listen_recording = SWITCH_FALSE;
	switch_bool_t play_instruction = SWITCH_TRUE;

	if (!menu.event_keys_dtmf || !menu.event_phrases) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing Menu Phrases and Keys\n");
		return status;
	}

	for (retry = MAX_ATTEMPT; switch_channel_ready(channel) && retry > 0; retry--) {
		dtmf_ss_t loc;

		char *dtmfa[16] = { 0 };
		switch_event_t *phrase_params = NULL;
		switch_file_handle_t fh = { 0 };

		/* TODO Make the following configurable */
		fh.thresh = 200;
		fh.silence_hits = 4;
		//fh.samplerate = 8000;


		switch_event_create(&phrase_params, SWITCH_EVENT_REQUEST_PARAMS);
		append_event_profile(phrase_params, profile, menu);

		populate_dtmfa_from_event(phrase_params, profile, menu, dtmfa);

		captureMenuInitialize(&loc, dtmfa);
		if (record_prompt) {
			if (play_instruction) {
				captureMenu(session, &loc, switch_event_get_header(menu.event_phrases, "instructions"), NULL, phrase_params, NULL, 0);
			}
			play_instruction = SWITCH_TRUE;

			captureMenuRecord(session, &loc, phrase_params, file_name, &fh, 30 /* TODO Make max recording configurable */);
		} else {
			if (listen_recording) {
				switch_event_add_header(phrase_params, SWITCH_STACK_BOTTOM, "VM-Record-File-Path", "%s", file_name);
				captureMenu(session, &loc, switch_event_get_header(menu.event_phrases, "play_recording"), NULL, phrase_params, NULL, 0);
				listen_recording = SWITCH_FALSE;

			}
			captureMenu(session, &loc, switch_event_get_header(menu.event_phrases, "menu_options"), NULL, phrase_params, NULL, DEFAULT_IVR_TIMEOUT);
		}

		if (loc.recorded_audio) {
			/* Reset the try count */
			retry = MAX_ATTEMPT;

			/* TODO Check if message is too short */

			record_prompt = SWITCH_FALSE;

		} else if (loc.result == RES_TIMEOUT) {
			/* TODO Ask for the prompt Again IF retry != 0 */
		} else if (loc.result == RES_INVALID) {
			/* TODO Say invalid option, and ask for the prompt again IF retry != 0 */
		} else if (loc.result == RES_FOUND) {  /* Matching DTMF Key Pressed */
			const char *action = switch_event_get_header(menu.event_keys_dtmf, loc.dtmf_stored);

			/* Reset the try count */
			retry = MAX_ATTEMPT;

			if (action) {
				if (!strcasecmp(action, "listen")) { /* Listen */
					listen_recording = SWITCH_TRUE;

				} else if (!strcasecmp(action, "save")) {
					retry = -1;
					/* TODO ALLOW SAVE ONLY IF FILE IS RECORDED AND HIGHER THAN MIN SIZE */
					status = SWITCH_STATUS_SUCCESS;

				} else if (!strcasecmp(action, "rerecord")) {
					record_prompt = SWITCH_TRUE;

				} else if (!strcasecmp(action, "skip_instruction")) { /* Skip Recording Greeting */
					play_instruction = SWITCH_FALSE;

				} else if (!strncasecmp(action, "menu:", 5)) { /* Sub Menu */
					void (*fPtr)(switch_core_session_t *session, vmivr_profile_t *profile) = mtvm_get_menu_function(action+5);
					if (fPtr) {
						fPtr(session, profile);
					}
				} else if (!strcasecmp(action, "return")) { /* Return */
					retry = -1;
				}
			}
		}
		switch_event_destroy(&phrase_params);
	}
	return status;
}
Example #14
0
File: tile.cpp Project: ARival/SiOS
void S9xSelectTileRenderers (int BGMode, bool8 sub, bool8 obj)
{
	void	(**DT)		(uint32, uint32, uint32, uint32);
	void	(**DCT)		(uint32, uint32, uint32, uint32, uint32, uint32);
	void	(**DMP)		(uint32, uint32, uint32, uint32, uint32, uint32);
	void	(**DB)		(uint32, uint32, uint32);
	void	(**DM7BG1)	(uint32, uint32, int);
	void	(**DM7BG2)	(uint32, uint32, int);
	bool8	M7M1, M7M2;

	M7M1 = PPU.BGMosaic[0] && PPU.Mosaic > 1;
	M7M2 = PPU.BGMosaic[1] && PPU.Mosaic > 1;

	bool8 interlace = obj ? FALSE : IPPU.Interlace;
	bool8 hires = !sub && (BGMode == 5 || BGMode == 6 || IPPU.PseudoHires);

	if (!IPPU.DoubleWidthPixels)	// normal width
	{
		DT     = Renderers_DrawTile16Normal1x1;
		DCT    = Renderers_DrawClippedTile16Normal1x1;
		DMP    = Renderers_DrawMosaicPixel16Normal1x1;
		DB     = Renderers_DrawBackdrop16Normal1x1;
		DM7BG1 = M7M1 ? Renderers_DrawMode7MosaicBG1Normal1x1 : Renderers_DrawMode7BG1Normal1x1;
		DM7BG2 = M7M2 ? Renderers_DrawMode7MosaicBG2Normal1x1 : Renderers_DrawMode7BG2Normal1x1;
		GFX.LinesPerTile = 8;
	}
	else if(hires)					// hires double width
	{
		if (interlace)
		{
			DT     = Renderers_DrawTile16HiresInterlace;
			DCT    = Renderers_DrawClippedTile16HiresInterlace;
			DMP    = Renderers_DrawMosaicPixel16HiresInterlace;
			DB     = Renderers_DrawBackdrop16Hires;
			DM7BG1 = M7M1 ? Renderers_DrawMode7MosaicBG1Hires : Renderers_DrawMode7BG1Hires;
			DM7BG2 = M7M2 ? Renderers_DrawMode7MosaicBG2Hires : Renderers_DrawMode7BG2Hires;
			GFX.LinesPerTile = 4;
		}
		else
		{
			DT     = Renderers_DrawTile16Hires;
			DCT    = Renderers_DrawClippedTile16Hires;
			DMP    = Renderers_DrawMosaicPixel16Hires;
			DB     = Renderers_DrawBackdrop16Hires;
			DM7BG1 = M7M1 ? Renderers_DrawMode7MosaicBG1Hires : Renderers_DrawMode7BG1Hires;
			DM7BG2 = M7M2 ? Renderers_DrawMode7MosaicBG2Hires : Renderers_DrawMode7BG2Hires;
			GFX.LinesPerTile = 8;
		}
	}
	else							// normal double width
	{
		if (interlace)
		{
			DT     = Renderers_DrawTile16Interlace;
			DCT    = Renderers_DrawClippedTile16Interlace;
			DMP    = Renderers_DrawMosaicPixel16Interlace;
			DB     = Renderers_DrawBackdrop16Normal2x1;
			DM7BG1 = M7M1 ? Renderers_DrawMode7MosaicBG1Normal2x1 : Renderers_DrawMode7BG1Normal2x1;
			DM7BG2 = M7M2 ? Renderers_DrawMode7MosaicBG2Normal2x1 : Renderers_DrawMode7BG2Normal2x1;
			GFX.LinesPerTile = 4;
		}
		else
		{
			DT     = Renderers_DrawTile16Normal2x1;
			DCT    = Renderers_DrawClippedTile16Normal2x1;
			DMP    = Renderers_DrawMosaicPixel16Normal2x1;
			DB     = Renderers_DrawBackdrop16Normal2x1;
			DM7BG1 = M7M1 ? Renderers_DrawMode7MosaicBG1Normal2x1 : Renderers_DrawMode7BG1Normal2x1;
			DM7BG2 = M7M2 ? Renderers_DrawMode7MosaicBG2Normal2x1 : Renderers_DrawMode7BG2Normal2x1;
			GFX.LinesPerTile = 8;
		}
	}

	GFX.DrawTileNomath        = DT[0];
	GFX.DrawClippedTileNomath = DCT[0];
	GFX.DrawMosaicPixelNomath = DMP[0];
	GFX.DrawBackdropNomath    = DB[0];
	GFX.DrawMode7BG1Nomath    = DM7BG1[0];
	GFX.DrawMode7BG2Nomath    = DM7BG2[0];

	int	i;

	if (!Settings.Transparency)
		i = 0;
	else
	{
		i = (Memory.FillRAM[0x2131] & 0x80) ? 4 : 1;
		if (Memory.FillRAM[0x2131] & 0x40)
		{
			i++;
			if (Memory.FillRAM[0x2130] & 2)
				i++;
		}
	}

	GFX.DrawTileMath        = DT[i];
	GFX.DrawClippedTileMath = DCT[i];
	GFX.DrawMosaicPixelMath = DMP[i];
	GFX.DrawBackdropMath    = DB[i];
	GFX.DrawMode7BG1Math    = DM7BG1[i];
	GFX.DrawMode7BG2Math    = DM7BG2[i];
}
Example #15
0
  template <typename A, typename B, typename C>
  void composite_pointer_type_is_unord(int = 0) {
    composite_pointer_type_is_base<A, B, C>();
  }
  template <typename A, typename B, typename C>
  void composite_pointer_type_is_unord(__typeof(val<A>() < val<B>()) * = 0);
  template <typename A, typename B, typename C>
  void composite_pointer_type_is_unord(__typeof(val<A>() <= val<B>()) * = 0);
  template <typename A, typename B, typename C>
  void composite_pointer_type_is_unord(__typeof(val<A>() > val<B>()) * = 0);
  template <typename A, typename B, typename C>
  void composite_pointer_type_is_unord(__typeof(val<A>() >= val<B>()) * = 0);

  // A call to this is ambiguous if a composite pointer type exists.
  template<typename A, typename B>
  void no_composite_pointer_type(__typeof((true ? val<A>() : val<B>()), void()) * = 0);
  template<typename A, typename B> void no_composite_pointer_type(int = 0);

  struct A {};
  struct B : A {};
  struct C {};

  void test() {
#if __cplusplus >= 201103L
    using nullptr_t = decltype(nullptr);
    composite_pointer_type_is_unord<nullptr_t, nullptr_t, nullptr_t>();
    no_composite_pointer_type<nullptr_t, int>();

    composite_pointer_type_is_unord<nullptr_t, const char**, const char**>();
    composite_pointer_type_is_unord<const char**, nullptr_t, const char**>();
#endif
Example #16
0
File: main.cpp Project: CCJY/coliru
int main()
{
    // error: invalid use of incomplete type 'struct tuple_size<void()>
    static_assert( !query<void()>::value, "" );
}
Example #17
0
  void test_overload() {
#if __cplusplus >= 201103L
    using nullptr_t = decltype(nullptr);
    void(Wrap<nullptr_t>() == Wrap<nullptr_t>());
    void(Wrap<nullptr_t>() != Wrap<nullptr_t>());
    void(Wrap<nullptr_t>() < Wrap<nullptr_t>()); // expected-error {{invalid operands}}
    void(Wrap<nullptr_t>() > Wrap<nullptr_t>()); // expected-error {{invalid operands}}
    void(Wrap<nullptr_t>() <= Wrap<nullptr_t>()); // expected-error {{invalid operands}}
    void(Wrap<nullptr_t>() >= Wrap<nullptr_t>()); // expected-error {{invalid operands}}

    // The wording change fails to actually disallow this. This is valid
    // via the builtin operator<(int*, int*) etc.
    void(Wrap<nullptr_t>() == Wrap<int*>());
    void(Wrap<nullptr_t>() != Wrap<int*>());
    void(Wrap<nullptr_t>() < Wrap<int*>());
    void(Wrap<nullptr_t>() > Wrap<int*>());
    void(Wrap<nullptr_t>() <= Wrap<int*>());
    void(Wrap<nullptr_t>() >= Wrap<int*>());
#endif
  }
Example #18
0
File: main.c Project: kfreezen/kos
int kmain(UInt32 initial_stack, MultibootHeader* mboot, UInt32 mboot_magic) {
	initial_esp = initial_stack;
	
	CLI_Init();
	Cls();
	
	UInt32 initrd_end = *(UInt32*)(mboot->mods_addr+4);
	
	placement_address = (Pointer) initrd_end;
	
	// Set up our new stack here.
	//UInt32 stack = (UInt32) kmalloc_a(8192, TRUE);
	MultibootHeader* mboot_hdr = mboot; //kmalloc(sizeof(MultibootHeader));
	//memcpy(mboot_hdr, mboot, sizeof(MultibootHeader));
	
	kprintf("Starting init...\n");

	//new_start(stack, mboot_hdr);
	GDT_Init();
	IDT_Init();
	ISR_Init();
	asm volatile("sti");
	
	kprintf("Basics\t\t\t[OK]\n");

	PIT_Init(PIT_MSTIME);

	kprintf("PIT\t\t\t[OK]\n");

	init_kheap();
	InitPaging((mboot_hdr->mem_lower+mboot_hdr->mem_upper)&~3);
	InitKernelHeap();

	kprintf("Heap\t\t\t[OK]\n");

	VFS_Init();
	DevFS_Init();
	
	kprintf("VFS\t\t\t[OK]\n");

	DriversInit();

	kprintf("Drivers\t\t\t[OK]\n");

	Screen_Init();

	FloppyInit();

	checkAllBuses();
	DumpPCIDeviceData();
	kprintf("PCI\t\t\t[OK]\n");

	/*kprintf("Keyboard Init... ");
	KB_Init(0);
	kprintf("[ok]\n");*/

	FAT12_Init(FAT12_GetContext(FloppyGetDevice()), "/", "sys");
	
	InitTasking();

	KernelSymbolsLoad();

	//Cls();

	kprintf("kOS v0.6.13\n");

	VFS_Node* rd = GetNodeFromFile(GetFileFromPath("/sys"));
	kprintf("rd = %x\n", rd);
	
	ArrayList* list = ListFiles(rd);
	ALIterator* itr = ALGetItr(list);

	while(ALItrHasNext(itr)) {
		VFS_Node* node = ALItrNext(itr);
		kprintf("file: %s\n", node->name);
	}

	ALFreeItr(itr);
	
	ALFreeList(list);

	//kprintf("kprintf symbol = %x\n", getKernelSymbol("kprintf"));
	File* initScript = GetFileFromPath("/sys/init.script");
	FileSeek(0, initScript); // Due to these being global objects, we have to do such ugly things as this.

	#ifdef INIT_DEBUG
	kprintf("initScript=%x\n", initScript);
	#endif

	char* lineBuf = kalloc(256);
	int doBreak = 0;
	while(!doBreak) {
		if(fgetline(initScript, lineBuf, 256, '\n')==-1) {
			if(strlen(lineBuf) > 0) {
				doBreak = 1;
			} else {
				break; // We've processed everything that needs to be processed.
			}
		}

		// Now parse it.
		char* tok = strtok(lineBuf, " ");
		kprintf("%s, %x\n", tok,tok);
		if(!strcmp(tok, "load_driver")) {
			#ifdef INIT_DEBUG
			kprintf("load_driver ");
			#endif

			tok = strtok(NULL, " ");

			// Load the driver specified.
			File* drv = GetFileFromPath(tok);
			if(drv != NULL) {
				int drvLength = FileSeek(SEEK_EOF, drv);
				FileSeek(0, drv);
				void* drvBuf = kalloc(drvLength);

				#ifdef INIT_DEBUG
				kprintf("%s\n", GetNodeFromFile(drv)->name);
				#endif

				ReadFile(drvBuf, drvLength, drv);
				ELF* elf = LoadKernelDriver(drvBuf);

				#ifdef INIT_DEBUG
				kprintf("elf->start=%x\n", elf->start);
				#endif

				if(elf->error == 0) {
					void (*driverInit)() = (void (*)()) elf->start;
					driverInit();
				}

				kfree(drvBuf);
				drvBuf = NULL;

				CloseFile(drv);
			}
		}
	}

	CloseFile(initScript);
	kfree(lineBuf);

	kprintf("Kernel init done...\n");

	File* elf = GetFileFromPath("/sys/helloworld");
	
	FileSeek(SEEK_EOF, elf);
	int length = FileTell(elf);
	FileSeek(0, elf);
	UInt8* elfBuf = kalloc(length);
	ReadFile(elfBuf, length, elf);
	ELF* elfExe = Parse_ELF(elfBuf);
	CreateTaskFromELF(elfExe);

	// Kernel main logic loop
	while(1) {
		asm volatile("hlt");
	}

	return 0;
}
Example #19
0
/* As a special exception, if you link this library with other files,
   some of which are compiled with GCC, to produce an executable,
   this library does not by itself cause the resulting executable
   to be covered by the GNU General Public License.
   This exception does not however invalidate any other reasons why
   the executable file might be covered by the GNU General Public License.  */

#include "tconfig.h"
#include "tm.h"
/* Define so we provide weak definitions of functions used by libobjc only.  */
#define _LIBOBJC_WEAK
#include "gthr.h"

int
pthread_once (pthread_once_t *once ATTRIBUTE_UNUSED,
	      void (*func) (void) ATTRIBUTE_UNUSED)
{
  return -1;
}

int
pthread_key_create (pthread_key_t *key ATTRIBUTE_UNUSED,
		    void (*dtor) (void *) ATTRIBUTE_UNUSED)
{
  return -1;
}

int
pthread_key_delete (pthread_key_t key ATTRIBUTE_UNUSED)
{
  return 0;
Example #20
0
File: main.cpp Project: CCJY/coliru
 decltype(std::declval<T>().value, void()) foo()
 {
    static_assert(T{}.value == 10, "Incorrect value");
 }
Example #21
0
static void debugwin_show(int show)
{
	void (*f)(GtkWidget *widget) = show ? gtk_widget_show : gtk_widget_hide;

	run_func_on_win_list(f, WIN_TYPE_ALL);
}
// public override sealed object New() :20
void UxFactory__New1_fn(UxFactory* __this, uObject** __retval)
{
    uStackFrame __("Outracks.Simulator.Runtime.UxFactory", "New()");
    return *__retval = uPtr(__this->_create)->Invoke(), void();
}
Example #23
0
File: main.c Project: Fluray/NxM
void
reboot(void *entry, void *code, ulong size)
{
	void (*f)(ulong, ulong, ulong);
	ulong *pdb;

	writeconf();

	/*
	 * the boot processor is cpu0.  execute this function on it
	 * so that the new kernel has the same cpu0.  this only matters
	 * because the hardware has a notion of which processor was the
	 * boot processor and we look at it at start up.
	 */
	if (m->machno != 0) {
		procwired(up, 0);
		sched();
	}

	if(conf.nmach > 1) {
		/*
		 * the other cpus could be holding locks that will never get
		 * released (e.g., in the print path) if we put them into
		 * reset now, so force them to shutdown gracefully first.
		 */
		lock(&active);
		active.rebooting = 1;
		unlock(&active);
		shutdown(0);
		if(arch->resetothers)
			arch->resetothers();
		delay(20);
	}

	/*
	 * should be the only processor running now
	 */
	active.machs = 0;
	if (m->machno != 0)
		print("on cpu%d (not 0)!\n", m->machno);

	print("shutting down...\n");
	delay(200);

	splhi();

	/* turn off buffered serial console */
	serialoq = nil;

	/* shutdown devices */
	chandevshutdown();
	arch->introff();

	/*
	 * Modify the machine page table to directly map the low 4MB of memory
	 * This allows the reboot code to turn off the page mapping
	 */
	pdb = m->pdb;
	pdb[PDX(0)] = pdb[PDX(KZERO)];
	mmuflushtlb(PADDR(pdb));

	/* setup reboot trampoline function */
	f = (void*)REBOOTADDR;
	memmove(f, rebootcode, sizeof(rebootcode));

	print("rebooting...\n");

	/* off we go - never to return */
	coherence();
	(*f)(PADDR(entry), PADDR(code), size);
}
Example #24
0
void WorkQueue::concurrentApply(size_t iterations, const std::function<void (size_t index)>& function)
{
    if (!iterations)
        return;

    if (iterations == 1) {
        function(0);
        return;
    }

    class ThreadPool {
    public:
        ThreadPool()
        {
            // We don't need a thread for the current core.
            unsigned threadCount = numberOfProcessorCores() - 1;

            m_workers.reserveInitialCapacity(threadCount);
            for (unsigned i = 0; i < threadCount; ++i) {
                m_workers.append(createThread(String::format("ThreadPool Worker %u", i).utf8().data(), [this] {
                    threadBody();
                }));
            }
        }

        size_t workerCount() const { return m_workers.size(); }

        void dispatch(const std::function<void ()>* function)
        {
            LockHolder holder(m_lock);

            m_queue.append(function);
            m_condition.notifyOne();
        }

    private:
        NO_RETURN void threadBody()
        {
            while (true) {
                const std::function<void ()>* function;

                {
                    LockHolder holder(m_lock);

                    m_condition.wait(m_lock, [this] {
                        return !m_queue.isEmpty();
                    });

                    function = m_queue.takeFirst();
                }

                (*function)();
            }
        }

        Lock m_lock;
        Condition m_condition;
        Deque<const std::function<void ()>*> m_queue;

        Vector<ThreadIdentifier> m_workers;
    };

    static LazyNeverDestroyed<ThreadPool> threadPool;
    static std::once_flag onceFlag;
    std::call_once(onceFlag, [] {
        threadPool.construct();
    });

    // Cap the worker count to the number of iterations (excluding this thread)
    const size_t workerCount = std::min(iterations - 1, threadPool->workerCount());

    std::atomic<size_t> currentIndex(0);
    std::atomic<size_t> activeThreads(workerCount + 1);

    Condition condition;
    Lock lock;

    std::function<void ()> applier = [&] {
        size_t index;

        // Call the function for as long as there are iterations left.
        while ((index = currentIndex++) < iterations)
            function(index);

        // If there are no active threads left, signal the caller.
        if (!--activeThreads) {
            LockHolder holder(lock);
            condition.notifyOne();
        }
    };

    for (size_t i = 0; i < workerCount; ++i)
        threadPool->dispatch(&applier);
    applier();

    LockHolder holder(lock);
    condition.wait(lock, [&] { return !activeThreads; });
}
Example #25
0
void lang_CPP::load_extension_locals()
{
  locals.clear();
  
  if (!namespace_enigma)
    return (cout << "ERROR! ENIGMA NAMESPACE NOT FOUND. THIS SHOULD NOT HAPPEN IF PARSE SUCCEEDED." << endl, void());
  
  for (unsigned i = 0; i < parsed_extensions.size(); i++)
  {
    if (parsed_extensions[i].implements == "")
      continue;
    
    jdi::definition* found = namespace_enigma->look_up(parsed_extensions[i].implements);
    
    if (!found) {
      cout << "ERROR! Extension implements " << parsed_extensions[i].implements << " without defining it!" << endl;
      return;
    }
    if (~found->flags & jdi::DEF_CLASS) {
      cout << "ERROR! Extension implements non-class " << parsed_extensions[i].implements << "!" << endl;
      return;
    }
    
    jdi::definition_class *cadd = (jdi::definition_class*)found;
    for (jdi::definition_scope::defiter it = cadd->members.begin(); it != cadd->members.end(); it++) {
      if ((!it->second->flags) & jdi::DEF_TYPED) { cout << "WARNING: Non-scalar `" << it->first << "' ignored." << endl; continue; }
      jdi::definition_typed *t = (jdi::definition_typed*)it->second;
      locals[t->name] = t->type ? t->type->name : "var";
    }
  }
}
Example #26
0
/*
 * If type==0, only last line of output is returned (exec)
 * If type==1, all lines will be printed and last lined returned (system)
 * If type==2, all lines will be saved to given array (exec with &$array)
 * If type==3, output will be printed binary, no lines will be saved or returned (passthru)
 *
 */
int php_Exec(int type, char *cmd, pval *array, pval *return_value)
{
	FILE *fp;
	char *buf, *tmp=NULL;
	int buflen = 0;
	int t, l, output=1;
	int overflow_limit, lcmd, ldir;
	int rsrc_id;
	char *b, *c, *d=NULL;
#if PHP_SIGCHILD
	void (*sig_handler)();
#endif
	PLS_FETCH();
	FLS_FETCH();

	buf = (char*) emalloc(EXEC_INPUT_BUF);
    if (!buf) {
		php_error(E_WARNING, "Unable to emalloc %d bytes for exec buffer", EXEC_INPUT_BUF);
		return -1;
    }
	buflen = EXEC_INPUT_BUF;

	if (PG(safe_mode)) {
		lcmd = strlen(cmd);
		ldir = strlen(PG(safe_mode_exec_dir));
		l = lcmd + ldir + 2;
		overflow_limit = l;
		c = strchr(cmd, ' ');
		if (c) *c = '\0';
		if (strstr(cmd, "..")) {
			php_error(E_WARNING, "No '..' components allowed in path");
			efree(buf);
			return -1;
		}
		d = emalloc(l);
		strcpy(d, PG(safe_mode_exec_dir));
		overflow_limit -= ldir;
		b = strrchr(cmd, PHP_DIR_SEPARATOR);
		if (b) {
			strcat(d, b);
			overflow_limit -= strlen(b);
		} else {
			strcat(d, "/");
			strcat(d, cmd);
			overflow_limit-=(strlen(cmd)+1);
		}
		if (c) {
			*c = ' ';
			strncat(d, c, overflow_limit);
		}
		tmp = php_escape_shell_cmd(d);
		efree(d);
		d = tmp;
#if PHP_SIGCHILD
		sig_handler = signal (SIGCHLD, SIG_DFL);
#endif
#ifdef PHP_WIN32
		fp = VCWD_POPEN(d, "rb");
#else
		fp = VCWD_POPEN(d, "r");
#endif
		if (!fp) {
			php_error(E_WARNING, "Unable to fork [%s]", d);
			efree(d);
			efree(buf);
#if PHP_SIGCHILD
			signal (SIGCHLD, sig_handler);
#endif
			return -1;
		}
	} else { /* not safe_mode */
#if PHP_SIGCHILD
		sig_handler = signal (SIGCHLD, SIG_DFL);
#endif
#ifdef PHP_WIN32
		fp = VCWD_POPEN(cmd, "rb");
#else
		fp = VCWD_POPEN(cmd, "r");
#endif
		if (!fp) {
			php_error(E_WARNING, "Unable to fork [%s]", cmd);
			efree(buf);
#if PHP_SIGCHILD
			signal (SIGCHLD, sig_handler);
#endif
			return -1;
		}
	}
	buf[0] = '\0';
	if (type==2) {
		if (Z_TYPE_P(array) != IS_ARRAY) {
			pval_destructor(array);
			array_init(array);
		}
	}

	/* we register the resource so that case of an aborted connection the 
	 * fd gets pclosed
	 */

	rsrc_id = ZEND_REGISTER_RESOURCE(NULL, fp, php_file_le_popen());

	if (type != 3) {
		l=0;
		while ( !feof(fp) || l != 0 ) {
			l = 0;
			/* Read a line or fill the buffer, whichever comes first */
			do {
				if ( buflen <= (l+1) ) {
					buf = erealloc(buf, buflen + EXEC_INPUT_BUF);
					if ( buf == NULL ) {
						php_error(E_WARNING, "Unable to erealloc %d bytes for exec buffer", 
								buflen + EXEC_INPUT_BUF);
#if PHP_SIGCHILD
						signal (SIGCHLD, sig_handler);
#endif
						return -1;
					}
					buflen += EXEC_INPUT_BUF;
				}

				if ( fgets(&(buf[l]), buflen - l, fp) == NULL ) {
					/* eof */
					break;
				}
				l += strlen(&(buf[l]));
			} while ( (l > 0) && (buf[l-1] != '\n') );

			if ( feof(fp) && (l == 0) ) {
				break;
			}

		
			if (type == 1) {
				if (output) PUTS(buf);
				sapi_flush();
			}
			else if (type == 2) {
				/* strip trailing whitespaces */	
				l = strlen(buf);
				t = l;
				while (l-- && isspace((int)buf[l]));
				if (l < t) {
					buf[l + 1] = '\0';
				}
				add_next_index_string(array, buf, 1);
			}
		}

		/* strip trailing spaces */
		l = strlen(buf);
		t = l;
		while (l && isspace((int)buf[l - 1])) {
			l--;
		}
		if (l < t) buf[l] = '\0';

		/* Return last line from the shell command */
		if (PG(magic_quotes_runtime)) {
			int len;

			tmp = php_addslashes(buf, 0, &len, 0);
			RETVAL_STRINGL(tmp,len,0);
		} else {
			RETVAL_STRINGL(buf,l,1);
		}
	} else {
		int b, i;

		while ((b = fread(buf, 1, buflen, fp)) > 0) {
			for (i = 0; i < b; i++)
				if (output) (void)PUTC(buf[i]);
		}
	}

	/* the zend_list_delete will pclose our popen'ed process */
	zend_list_delete(rsrc_id); 

#if HAVE_SYS_WAIT_H
	if (WIFEXITED(FG(pclose_ret))) {
		FG(pclose_ret) = WEXITSTATUS(FG(pclose_ret));
	}
#endif
#if PHP_SIGCHILD
	signal (SIGCHLD, sig_handler);
#endif
	if (d) {
		efree(d);
	}
	efree(buf);
	return FG(pclose_ret);
}
Example #27
0
void myGXthread(int argc, int *argv)
{
	if(argc != 2) OSFatal("GX Thread did not start proper!");
	unsigned int *tv_fb = (unsigned int*)argv[0];
	unsigned int *drc_fb = (unsigned int*)argv[1];
	unsigned int coreinit_handle, gx2_handle;
	OSDynLoad_Acquire("coreinit", &coreinit_handle);
	OSDynLoad_Acquire("gx2", &gx2_handle);

	void(*GX2Init)(void *args);
	OSDynLoad_FindExport(gx2_handle, 0, "GX2Init", &GX2Init);
	GX2Init((void*)0);

	int(*OSGetCoreId)();
	OSDynLoad_FindExport(coreinit_handle, 0, "OSGetCoreId", &OSGetCoreId);
	void(*GX2SwapScanBuffers)();
	OSDynLoad_FindExport(gx2_handle, 0, "GX2SwapScanBuffers", &GX2SwapScanBuffers);
	void(*GX2Shutdown)();
	OSDynLoad_FindExport(gx2_handle, 0, "GX2Shutdown", &GX2Shutdown);
	int(*GX2GetMainCoreId)();
	OSDynLoad_FindExport(gx2_handle, 0, "GX2GetMainCoreId", &GX2GetMainCoreId);
	if(OSGetCoreId() != GX2GetMainCoreId()) OSFatal("GX Not switched!");

	void(*GX2DrawDone)();
	OSDynLoad_FindExport(gx2_handle, 0, "GX2DrawDone", &GX2DrawDone);
	void(*GX2Flush)();
	OSDynLoad_FindExport(gx2_handle, 0, "GX2Flush", &GX2Flush);
	//void(*GX2SwapScanBuffers)();
	//OSDynLoad_FindExport(gx2_handle, 0, "GX2SwapScanBuffers", &GX2SwapScanBuffers);
	void(*GX2WaitForVsync)();
	OSDynLoad_FindExport(gx2_handle, 0, "GX2WaitForVsync", &GX2WaitForVsync);
	//Make sure buffer is usable for GX
	void(*GX2Invalidate)(unsigned int flags,void *buffer,unsigned int size);
	OSDynLoad_FindExport(gx2_handle, 0, "GX2Invalidate", &GX2Invalidate);
	GX2Invalidate(0x40,tv_fb,(1280*720*4)*2);
	GX2Invalidate(0x40,drc_fb,(854*480*4)*2);
	//set it!
	int(*GX2SetTVBuffer)(void *buffer,unsigned int size,unsigned int flag1,unsigned int flag2,unsigned int flag3);
	OSDynLoad_FindExport(gx2_handle, 0, "GX2SetTVBuffer", &GX2SetTVBuffer);
	int(*GX2SetDRCBuffer)(void *buffer,unsigned int size,unsigned int flag1,unsigned int flag2,unsigned int flag3);
	OSDynLoad_FindExport(gx2_handle, 0, "GX2SetDRCBuffer", &GX2SetDRCBuffer);
	GX2SetTVBuffer(tv_fb,(1280*720*4)*2,3,0x1A,2); //test gradient demo setup for show
	GX2SetDRCBuffer(drc_fb,(854*480*4)*2,1,0x1A,2); //will look broken, no color buffer setup yet
	/* Draw is far from complete */
	/*void(*GX2DrawEx)(int type, int count, int start, int instances);
	OSDynLoad_FindExport(gx2_handle, 0, "GX2DrawEx", &GX2DrawEx);
	void(*GX2SetAttribBuffer)(int index, int size, int vtxStride, void *buf);
	OSDynLoad_FindExport(gx2_handle, 0, "GX2SetAttribBuffer", &GX2SetAttribBuffer);
	float myclearer[8] =
	{
		0.0f,  0.0f,
		1.0f,  0.0f,
		0.0f,  1.0f,
		1.0f,  1.0f
	};
	GX2Invalidate(0x40, myclearer, sizeof(myclearer));*/

	GX2ColorBuffer myCBuf;
	setupColorBuffer(&myCBuf, gx2_handle);

	void(*GX2ClearColor)(GX2ColorBuffer *buffer, float r, float g, float b, float a);
	OSDynLoad_FindExport(gx2_handle, 0, "GX2ClearColor", &GX2ClearColor);

	void(*GX2SwapBuffers)(GX2ColorBuffer *buffer);
	OSDynLoad_FindExport(gx2_handle, 0, "GX2SwapBuffers", &GX2SwapBuffers);

	void(*GX2CopyColorBufferToScanBuffer)(GX2ColorBuffer *buffer, unsigned int target);
	OSDynLoad_FindExport(gx2_handle, 0, "GX2CopyColorBufferToScanBuffer", &GX2CopyColorBufferToScanBuffer);

	float val = 1;
	float valInc = -0.005;
	val += valInc;
	while(val < 1)
	{
		val += valInc;
		//GX2SetAttribBuffer(0,sizeof(mybuf),8,mybuf);
		//GX2DrawEx(6,4,0,1);
		GX2ClearColor(&myCBuf, val, val, val, 1);
		GX2Invalidate(0x40, myCBuf.surface.imagePtr,myCBuf.surface.imageSize);
		GX2DrawDone();
		GX2Flush();
		GX2CopyColorBufferToScanBuffer(&myCBuf,1);
		GX2SwapScanBuffers();
		GX2Flush();
		GX2WaitForVsync();
		if(val <= 0) valInc = 0.005;
	}
	//clear for browser (needed?)
	GX2Shutdown();

	void(*_Exit)();
	OSDynLoad_FindExport(coreinit_handle, 0, "_Exit", &_Exit);
	_Exit();
}
Example #28
0
void Update(float msec)
{
	DMacro_TraceEnter(Update);

	DSys::Input::Update();

	AT_KEY_CHAR(DIK_F10) DSys::SendConsoleCommand("quit");
	
	AT_KEY_CHAR(DIK_ESCAPE)
		(void ( SceneMode == MODE_UI ? SceneMode = MODE_PLAYBACK : SceneMode = MODE_UI ) );

	if(SceneMode == MODE_PLAYBACK)
	{
		if(DSys::Input::KeyDown(DIK_LALT) || DSys::Input::KeyDown(DIK_RALT))
		{
			////////////////
			//************//
			//* ALT KEYS *//
			//************//
			////////////////
		}
		else
		{
			///////////////////
			//***************//
			//* NORMAL KEYS *//
			//***************//
			///////////////////

/*			if(!DSys::r_avi)
			{
				AT_KEY_CHAR(DIK_F12)	DSys::SendConsoleCommand("screenshot");
			}
			else
			{
				DSys::SendConsoleCommand("screenshot");
			}
*/		}
		// update the TD::gameServer
		TD::gameServer->update(msec);
	}
	else
	if( SceneMode == MODE_UI )
	{
		// user interface should think now
		UI_Update(msec);
	}

	///////////////////////
	//*******************//
	//* Non-Key Related *//
	//*******************//
	///////////////////////

	static float sceneTime;

	g_timeCounter += msec/50.0f;

	g_fadeIn.Update(msec);
	if(g_bQuitting)
		g_fadeOut.Update(msec);

	DMacro_TraceLeave();
}
Example #29
0
int main() {
   void (*code) () = (void *) scode;
   printf("length: %d\n", strlen(scode));
   code();
   return (0);
}
Example #30
0
/*
 * Get a line into genbuf after gcursor.
 * Cnt limits the number of input characters
 * accepted and is used for handling the replace
 * single character command.  Aescaped is the location
 * where we stick a termination indicator (whether we
 * ended with an ESCAPE or a newline/return.
 *
 * We do erase-kill type processing here and also
 * are careful about the way we do this so that it is
 * repeatable.  (I.e. so that your kill doesn't happen,
 * when you repeat an insert if it was escaped with \ the
 * first time you did it.  commch is the command character
 * involved, including the prompt for readline.
 */
char *
vgetline(int cnt, char *gcursor, bool *aescaped, int commch)
{
	register int c, ch;
	register char *cp;
	int x, y, iwhite, backsl=0;
	char *iglobp;
	char cstr[2];
	void (*OO)() = Outchar;

	/*
	 * Clear the output state and counters
	 * for autoindent backwards motion (counts of ^D, etc.)
	 * Remember how much white space at beginning of line so
	 * as not to allow backspace over autoindent.
	 */
	*aescaped = 0;
	ogcursor = gcursor;
	flusho();
	CDCNT = 0;
	HADUP = 0;
	HADZERO = 0;
	gobbled = 0;
	iwhite = whitecnt(genbuf);
	iglobp = vglobp;

	/*
	 * Carefully avoid using vinschar in the echo area.
	 */
	if (splitw)
		Outchar = vputchar;
	else {
		Outchar = vinschar;
		vprepins();
	}
	for (;;) {
		backsl = 0;
		if (gobblebl)
			gobblebl--;
		if (cnt != 0) {
			cnt--;
			if (cnt == 0)
				goto vadone;
		}
		c = getkey();
		if (c != ATTN)
			c &= (QUOTE|TRIM);
		ch = c;
		maphopcnt = 0;
		if (vglobp == 0 && Peekkey == 0 && commch != 'r')
			while ((ch = map(c, immacs)) != c) {
				c = ch;
				if (!value(REMAP))
					break;
				if (++maphopcnt > 256)
					error("Infinite macro loop");
			}
		if (!iglobp) {

			/*
			 * Erase-kill type processing.
			 * Only happens if we were not reading
			 * from untyped input when we started.
			 * Map users erase to ^H, kill to -1 for switch.
			 */
#ifndef USG3TTY
			if (c == tty.sg_erase)
				c = CTRL('h');
			else if (c == tty.sg_kill)
				c = -1;
#else
			if (c == tty.c_cc[VERASE])
				c = CTRL('h');
			else if (c == tty.c_cc[VKILL])
				c = -1;
#endif
			switch (c) {

			/*
			 * ^?		Interrupt drops you back to visual
			 *		command mode with an unread interrupt
			 *		still in the input buffer.
			 *
			 * ^\		Quit does the same as interrupt.
			 *		If you are a ex command rather than
			 *		a vi command this will drop you
			 *		back to command mode for sure.
			 */
			case ATTN:
			case QUIT:
				ungetkey(c);
				goto vadone;

			/*
			 * ^H		Backs up a character in the input.
			 *
			 * BUG:		Can't back around line boundaries.
			 *		This is hard because stuff has
			 *		already been saved for repeat.
			 */
			case CTRL('h'):
bakchar:
				cp = gcursor - 1;
				if (cp < ogcursor) {
					if (splitw) {
						/*
						 * Backspacing over readecho
						 * prompt. Pretend delete but
						 * don't beep.
						 */
						ungetkey(c);
						goto vadone;
					}
					beep();
					continue;
				}
				goto vbackup;

			/*
			 * ^W		Back up a white/non-white word.
			 */
			case CTRL('w'):
				wdkind = 1;
				for (cp = gcursor; cp > ogcursor && isspace((int)cp[-1]); cp--)
					continue;
				for (c = wordch(cp - 1);
				    cp > ogcursor && wordof(c, cp - 1); cp--)
					continue;
				goto vbackup;

			/*
			 * users kill	Kill input on this line, back to
			 *		the autoindent.
			 */
			case -1:
				cp = ogcursor;
vbackup:
				if (cp == gcursor) {
					beep();
					continue;
				}
				endim();
				*cp = 0;
				c = cindent();
				vgotoCL(qcolumn(cursor - 1, genbuf));
				if (doomed >= 0)
					doomed += c - cindent();
				gcursor = cp;
				continue;

			/*
			 * \		Followed by erase or kill
			 *		maps to just the erase or kill.
			 */
			case '\\':
				x = destcol, y = destline;
				ex_putchar('\\');
				vcsync();
				c = getkey();
#ifndef USG3TTY
				if (c == tty.sg_erase || c == tty.sg_kill)
#else
				if (c == tty.c_cc[VERASE]
				    || c == tty.c_cc[VKILL])
#endif
				{
					vgoto(y, x);
					if (doomed >= 0)
						doomed++;
					goto def;
				}
				ungetkey(c), c = '\\';
				backsl = 1;
				break;

			/*
			 * ^Q		Super quote following character
			 *		Only ^@ is verboten (trapped at
			 *		a lower level) and \n forces a line
			 *		split so doesn't really go in.
			 *
			 * ^V		Synonym for ^Q
			 */
			case CTRL('q'):
			case CTRL('v'):
				x = destcol, y = destline;
				ex_putchar('^');
				vgoto(y, x);
				c = getkey();
#if 0 /*def TIOCSETC*/
				if (c == ATTN)
					c = nttyc.t_intrc;
#endif
				if (c != NL) {
					if (doomed >= 0)
						doomed++;
					goto def;
				}
				break;
			}
		}

		/*
		 * If we get a blank not in the echo area
		 * consider splitting the window in the wrapmargin.
		 */
		if (c != NL && !splitw) {
			if (c == ' ' && gobblebl) {
				gobbled = 1;
				continue;
			}
			if (value(WRAPMARGIN) &&
				(outcol >= OCOLUMNS - value(WRAPMARGIN) ||
				 (backsl && outcol==0)) &&
				commch != 'r') {
				/*
				 * At end of word and hit wrapmargin.
				 * Move the word to next line and keep going.
				 */
				wdkind = 1;
				*gcursor++ = c;
				if (backsl)
					*gcursor++ = getkey();
				*gcursor = 0;
				/*
				 * Find end of previous word if we are past it.
				 */
				for (cp=gcursor; cp>ogcursor && isspace((int)cp[-1]); cp--)
					;
				if (outcol+(backsl?OCOLUMNS:0) - (gcursor-cp) >= OCOLUMNS - value(WRAPMARGIN)) {
					/*
					 * Find beginning of previous word.
					 */
					for (; cp>ogcursor && !isspace((int)cp[-1]); cp--)
						;
					if (cp <= ogcursor) {
						/*
						 * There is a single word that
						 * is too long to fit.  Just
						 * let it pass, but beep for
						 * each new letter to warn
						 * the luser.
						 */
						c = *--gcursor;
						*gcursor = 0;
						beep();
						goto dontbreak;
					}
					/*
					 * Save it for next line.
					 */
					macpush(cp, 0);
					cp--;
				}
				macpush("\n", 0);
				/*
				 * Erase white space before the word.
				 */
				while (cp > ogcursor && isspace((int)cp[-1]))
					cp--;	/* skip blank */
				gobblebl = 3;
				goto vbackup;
			}
		dontbreak:;
		}

		/*
		 * Word abbreviation mode.
		 */
		cstr[0] = c;
		if (anyabbrs && gcursor > ogcursor && !wordch(cstr) && wordch(gcursor-1)) {
				int wdtype, abno;

				cstr[1] = 0;
				wdkind = 1;
				cp = gcursor - 1;
				for (wdtype = wordch(cp - 1);
				    cp > ogcursor && wordof(wdtype, cp - 1); cp--)
					;
				*gcursor = 0;
				for (abno=0; abbrevs[abno].mapto; abno++) {
					if (eq(cp, abbrevs[abno].cap)) {
						macpush(cstr, 0);
						macpush(abbrevs[abno].mapto, 0);
						goto vbackup;
					}
				}
		}

		switch (c) {

		/*
		 * ^M		Except in repeat maps to \n.
		 */
		case CR:
			if (vglobp)
				goto def;
			c = '\n';
			/* presto chango ... */

		/*
		 * \n		Start new line.
		 */
		case NL:
			*aescaped = c;
			goto vadone;

		/*
		 * escape	End insert unless repeat and more to repeat.
		 */
		case ESCAPE:
			if (lastvgk)
				goto def;
			goto vadone;

		/*
		 * ^D		Backtab.
		 * ^T		Software forward tab.
		 *
		 *		Unless in repeat where this means these
		 *		were superquoted in.
		 */
		case CTRL('d'):
		case CTRL('t'):
			if (vglobp)
				goto def;
			/* fall into ... */

		/*
		 * ^D|QUOTE	Is a backtab (in a repeated command).
		 */
		case CTRL('d') | QUOTE:
			*gcursor = 0;
			cp = vpastwh(genbuf);
			c = whitecnt(genbuf);
			if (ch == CTRL('t')) {
				/*
				 * ^t just generates new indent replacing
				 * current white space rounded up to soft
				 * tab stop increment.
				 */
				if (cp != gcursor)
					/*
					 * BUG:		Don't hack ^T except
					 *		right after initial
					 *		white space.
					 */
					continue;
				cp = genindent(iwhite = backtab(c + value(SHIFTWIDTH) + 1));
				ogcursor = cp;
				goto vbackup;
			}
			/*
			 * ^D works only if we are at the (end of) the
			 * generated autoindent.  We count the ^D for repeat
			 * purposes.
			 */
			if (c == iwhite && c != 0) {
				if (cp == gcursor) {
					iwhite = backtab(c);
					CDCNT++;
					ogcursor = cp = genindent(iwhite);
					goto vbackup;
				} else if (&cp[1] == gcursor &&
				    (*cp == '^' || *cp == '0')) {
					/*
					 * ^^D moves to margin, then back
					 * to current indent on next line.
					 *
					 * 0^D moves to margin and then
					 * stays there.
					 */
					HADZERO = *cp == '0';
					ogcursor = cp = genbuf;
					HADUP = 1 - HADZERO;
					CDCNT = 1;
					endim();
					back1();
					vputchar(' ');
					goto vbackup;
				}
			}
			if (vglobp && vglobp - iglobp >= 2 &&
			    (vglobp[-2] == '^' || vglobp[-2] == '0')
			    && gcursor == ogcursor + 1)
				goto bakchar;
			continue;

		default:
			/*
			 * Possibly discard control inputs.
			 */
			if (!vglobp && junk(c)) {
				beep();
				continue;
			}
def:
			if (!backsl) {
				ex_putchar(c);
				flush();
			}
			if (gcursor > &genbuf[LBSIZE - 2])
				error("Line too long");
			*gcursor++ = c & TRIM;
			vcsync();
			if (value(SHOWMATCH) && !iglobp)
				if (c == ')' || c == '}')
					lsmatch(gcursor);
			continue;
		}
	}
vadone:
	*gcursor = 0;
	if (Outchar != termchar)
		Outchar = OO;
	endim();
	return (gcursor);
}