Esempio n. 1
0
int sock_thread( SceSize args, void *argp )
{
	unsigned char buffer[block_size], running = 1;
	SocketOpts * opts = ( SocketOpts * )( *( unsigned int * )argp );
	opts->buf = ( int * )buffer;
	opts->sema = sceKernelCreateSema( "sock_sema", 0, 0, 1, NULL );
	while( running )
	{
		sceKernelSleepThread();
		switch ( opts->operation )
		{
			case S_SEND:
				opts->res = sceNetInetSend( opts->server, opts->buf, opts->length, 0 );
				log( "sent %d res %08x\n", opts->length, opts->res );
				break;
			case S_RECV:
				opts->res = sceNetInetRecv( opts->server, opts->buf, opts->length, 0 );
				break;
			case S_TERM:
				running = 0;
				break;
		}
		sceKernelSignalSema( opts->sema, 1 );
	}
	sceKernelDeleteSema( opts->sema );
	opts->sema = -1;
	opts->thid = -1;
	opts->buf = NULL;
	return sceKernelExitDeleteThread( 0 );
}
Esempio n. 2
0
int hook_sceKernelExitDeleteThread(int res)
{
        SceKernelSemaInfo info;
        globals_t *globals;
        SceUID uid;
        int i;

        globals = getGlobals();
        uid = sceKernelGetThreadId();

        DEBUG_PRINTF("Exiting thread 0x%08X (res: 0x%08X)", uid, res);

        sceKernelLockMutex(globals->threadmgrMutex, 1, NULL);

        info.size = sizeof(info);
        i = sceKernelGetSemaInfo(globals->threadmgrSema, &info);
        if (i == 0) {
                for (i = info.currentCount; i < info.maxCount; i++) {
                        if (globals->threadmgrTable[info.currentCount].uid == uid) {
                                if (i != info.currentCount)
                                       memcpy(globals->threadmgrTable + i,
                                              globals->threadmgrTable + info.currentCount,
                                              sizeof(thInfo_t));

                                sceKernelSignalSema(globals->threadmgrSema, 1);
                                break;
                        }
                }
        }

        sceKernelUnlockMutex(globals->threadmgrMutex, 1);
        sceKernelDelayThread(16384);
        return sceKernelExitDeleteThread(res);
}
Esempio n. 3
0
int installer_thread(SceSize args, void * argp)
{
	//installer load result
	int result = 0;

	//log installer start
	printk("Starting %s\n", installerpath);

	//load installer module
	SceUID mod = sctrlKernelLoadModule(installerpath, 0, NULL);

	//log installer uid
	printk("Module UID: %08X\n", mod);

	//installer loaded
	if (mod >= 0) {
		//start installer
		int status = 0;
		result = sctrlKernelStartModule(mod, strlen(installerpath) + 1, installerpath, &status, NULL);

		//log start result
		printk("Start Result: %08X - Status %08X\n", result, status);
	}

	//kill loader thread
	sceKernelExitDeleteThread(0);

	//return dummy result
	return 0;
}
Esempio n. 4
0
File: main.c Progetto: CDragu/pspsdk
int main(void)
{
	int i;

	pspDebugScreenInit();
	SetupCallbacks();

	/* Clear the existing profile regs */
	pspDebugProfilerClear();
	/* Enable profiling */
	pspDebugProfilerEnable();

	for(i = 0; i < 600; i++)
	{
		pspDebugScreenSetXY(0, 0);
		/* Print profile information to the screen */
		pspDebugProfilerPrint();
		sceDisplayWaitVblankStart();
	}

	/* Let's bug out */
	sceKernelExitDeleteThread(0);

	return 0;
}
Esempio n. 5
0
int update_thread(SceSize args_size, UpdateArguments *args) {
/*
	uint32_t previous_value = current_value;
	SceUInt64 cur_micros = 0, delta_micros = 0, last_micros = 0;
	double kbs = 0;
*/
	while (current_value < args->max && isMessageDialogRunning()) {
		disableAutoSuspend();
/*
		// Show KB/s
		cur_micros = sceKernelGetProcessTimeWide();
		if (cur_micros >= (last_micros + 1000000)) {
			delta_micros = cur_micros - last_micros;
			last_micros = cur_micros;
			kbs = (double)(current_value - previous_value) / 1024.0f;
			previous_value = current_value;

			char msg[32];
			sprintf(msg, "%.2f KB/s", kbs);
			sceMsgDialogProgressBarSetMsg(SCE_MSG_DIALOG_PROGRESSBAR_TARGET_BAR_DEFAULT, (SceChar8 *)msg);
		}
*/
		double progress = (double)((100.0f * (double)current_value) / (double)args->max);
		sceMsgDialogProgressBarSetValue(SCE_MSG_DIALOG_PROGRESSBAR_TARGET_BAR_DEFAULT, (int)progress);

		sceKernelDelayThread(COUNTUP_WAIT);
	}

	return sceKernelExitDeleteThread(0);
}
static int streamThread(unsigned int args, void* arg){

	int vol, dec_vol;

	for(;;) {

		// A pretty bad way to close thread
		if(termStream){
			termStream = false;
			if (bgm_chn != 0xDEAD){
				sceAudioOutReleasePort(bgm_chn);
				bgm_chn = 0xDEAD;
			}
			sceKernelExitDeleteThread(0);
		}

		sceKernelWaitSema(BGM_Mutex, 1, NULL);
		if (BGM == NULL || (!BGM->isPlaying)){
			sceKernelSignalSema(BGM_Mutex, 1);
			continue;
		}

		// Seems like audio ports are thread dependant on PSVITA :/
		if (BGM->isNewTrack){
			uint8_t audio_mode = BGM->isStereo ? SCE_AUDIO_OUT_MODE_STEREO : SCE_AUDIO_OUT_MODE_MONO;
			int nsamples = AUDIO_BUFSIZE / ((audio_mode+1)<<1);
			if (bgm_chn == 0xDEAD) bgm_chn = sceAudioOutOpenPort(SCE_AUDIO_OUT_PORT_TYPE_MAIN, nsamples, 48000, audio_mode);
			sceAudioOutSetConfig(bgm_chn, nsamples, 48000, audio_mode);
			vol = BGM->vol * 327;
			int vol_stereo[] = {vol, vol};
			sceAudioOutSetVolume(bgm_chn, SCE_AUDIO_VOLUME_FLAG_L_CH | SCE_AUDIO_VOLUME_FLAG_R_CH, vol_stereo);
			BGM->isNewTrack = false;
		}

		// Volume changes support
		dec_vol = audio_decoder->GetVolume();
		if (dec_vol != vol){
			vol = dec_vol * 327;
			int vol_stereo[] = {vol, vol};
			sceAudioOutSetVolume(bgm_chn, SCE_AUDIO_VOLUME_FLAG_L_CH | SCE_AUDIO_VOLUME_FLAG_R_CH, vol_stereo);
			vol = dec_vol;
		}


		// Audio streaming feature
		if (BGM->handle != NULL){
			if (BGM->cur_audiobuf == BGM->audiobuf) BGM->cur_audiobuf = BGM->audiobuf2;
			else BGM->cur_audiobuf = BGM->audiobuf;
			audio_decoder->Decode(BGM->cur_audiobuf, AUDIO_BUFSIZE);
			if (audio_decoder->GetLoopCount() > 0){ // EoF
				BGM->endedOnce = true;
			}
			int res = sceAudioOutOutput(bgm_chn, BGM->cur_audiobuf);
			if (res < 0) Output::Error("An error occurred in audio thread (0x%lX)", res);
		}

		sceKernelSignalSema(BGM_Mutex, 1);

	}
}
Esempio n. 7
0
static int main_thread(SceSize args, void *argp)
{
	char cmdbuf[128];
	int cpos;
	int retv;

	cpos = 0;
	while(1){
		if(usbAsyncRead(ASYNC_STDOUT, (unsigned char*)&cmdbuf[cpos], 1)<1){
			sceKernelDelayThread(250000);
			continue;
		}
		if(cmdbuf[cpos]=='\n'){
			cmdbuf[cpos] = 0;
			retv = parse_cmd(cmdbuf);
			cpos = 0;
		}else{
			if(cpos<127)
				cpos++;
		}
	}

	sceKernelExitDeleteThread(0);
	return 0;
}
Esempio n. 8
0
void do_menu(void)
{
	SceCtrlData pad;
	int selected = 0;
	unsigned int lastbut = TRIGGER;
	unsigned int curr = 0;

	redraw_menu(selected);
	while(1)
	{
		sceCtrlPeekBufferPositive(&pad, 1);

		curr = pad.Buttons & ~lastbut;
		
		if(curr & PSP_CTRL_UP)
		{
			if(selected > 0)
			{
				selected--;
			}
			else if(selected == 0)
			{
				selected = opt_count-1;
			}
			redraw_menu(selected);
		}
		if(curr & PSP_CTRL_DOWN)
		{
			if(selected < (opt_count-1))
			{
				selected++;
			}
			else if(selected == (opt_count-1))
			{
				selected = 0;
			}
			redraw_menu(selected);
		}
		if(curr & PSP_CTRL_CIRCLE)
		{
			options[selected].do_option();
		}
		else if(curr & PSP_CTRL_CROSS)
		{
			return;
		}
		lastbut = pad.Buttons;
		if(sceDisplayWaitVblankStart() < 0)
		{
			sceKernelExitDeleteThread(0);
		}
	}
}
Esempio n. 9
0
/*----------------------------------------------------------------------
|       NPT_PSPThread::Terminate
+---------------------------------------------------------------------*/
NPT_Result
NPT_PSPThread::Terminate()
{
    // end the thread
    sceKernelExitDeleteThread(0);

    // if we're detached, we need to delete ourselves
    if (m_Detached) {
        delete m_Delegator;
    }

    return NPT_SUCCESS;
}
Esempio n. 10
0
int main_thread(SceSize args, void *argp)
{
	char *argv0;
	char prx_path[256];
	char *path;
	SceUID modid;
	int ret;

	pspDebugScreenInit();
	sceDisplayWaitVblankStart();

	pspSdkInstallNoDeviceCheckPatch();
	pspSdkInstallNoPlainModuleCheckPatch();
	pspSdkInstallKernelLoadModulePatch();

	argv0 = (char*) argp;
	path = strrchr(argv0, '/');
	if(path != NULL)
	{
		memcpy(prx_path, argv0, path - argv0 + 1);
		prx_path[path - argv0 + 1] = 0;
		strcat(prx_path, "psplink.prx");
	}
	else
	{
		/* Well try for a default */
		strcpy(prx_path, "ms0:/psplink.prx");
	}

	/* Start mymodule.prx and dump its information */
	printf("PSPLink Bootstrap TyRaNiD (c) 2k5 Version %s\n", PSPLINK_VERSION);
	modid = load_module(prx_path, 0, 0);
	if(modid >= 0)
	{
		int status;

		printf("Starting psplink module\n");
		ret = sceKernelStartModule(modid, args, argp, &status, NULL);
		printf("Done\n");
	}
	else
	{
		printf("Error loading psplink module %08X\n", modid);
	}

	/* Let's bug out */
	sceKernelExitDeleteThread(0);

	return 0;
}
Esempio n. 11
0
void _main(SceSize args, void *argp)
{
	static SceUID modid;
	static int retVal, status;
	static SceKernelLMOption option;
	extern u8 *payload;
	extern u32 size_payload;
	extern u32 size_payload_uncomp;
	u8 *buffer;
	SceUID bufferBlock;
	
	pspDebugScreenInit();
    	pspDebugScreenClear();
	pspDebugInstallKprintfHandler(NULL);
	//pspDebugInstallErrorHandler(NULL);
	pspSdkInstallNoPlainModuleCheckPatch();

	memset(&option, 0, sizeof(option));
	option.size = sizeof(option);
	option.mpidtext = 1;
	option.mpiddata = 1;
	option.position = 0;
	option.access = 1;
	bufferBlock = sceKernelAllocPartitionMemory(2, "PSPPackerBuffer", PSP_SMEM_High, size_payload_uncomp, NULL);
	if (bufferBlock < 0) {
		printf("allocpartitionmemory failed with 0x%08X\n", bufferBlock);
		goto exit;
	}
	buffer = sceKernelGetBlockHeadAddr(bufferBlock);
	retVal = sceKernelGzipDecompress(buffer, size_payload_uncomp, (u8*)&payload, 0);
	if (retVal < 0) {
		printf("sceKernelGzipDecompress failed with 0x%08X\n", retVal);
		goto exit;
	}
	
	modid = sceKernelLoadModuleBufferUsbWlan(size_payload, buffer, 0, &option);
	retVal = sceKernelFreePartitionMemory(bufferBlock);
	if (retVal < 0)
		printf("Error freeing decompress buffer (0x%08X)\n", retVal);
		
	if(modid > 0)
		retVal = sceKernelStartModule(modid, 0, NULL, &status, NULL);

exit:
	/* Let's bug out */
	//sceKernelSelfStopUnloadModule(0, 0, NULL);
	//return 0;
	sceKernelExitDeleteThread(0);
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
    #ifdef X_MODULE_WIFI
    pspSdkLoadInetModules();
    pspSdkInetInit();
    #endif
    #ifdef X_MODULE_MP3
    //Reserved
    #endif
    xSetupCallbacks();
    int user_thid = sceKernelCreateThread("xUserThread", xUserThread, 0x18, 0x10000, PSP_THREAD_ATTR_USER|PSP_THREAD_ATTR_VFPU, 0);
    if (user_thid >= 0) sceKernelStartThread(user_thid, 0, 0);
    sceKernelExitDeleteThread(0);
    return 0;
}
Esempio n. 13
0
/**
  * The entry point for our exception "trap"
  */
void _pspDebugTrapEntry(void)
{
	/* No special stack is used here, if the thread's stack is trashed we might be in trouble */
	if(curr_handler != NULL)
	{
		curr_handler(&_pspDebugExceptRegs);
	}
	else
	{
		_pspDebugDefaultHandler(&_pspDebugExceptRegs);
	}

	/* Kill this thread as we cannot necessarily continue */
	/* Technically you might be able to "restart" after something like a break */
	sceKernelExitDeleteThread(0);
}
Esempio n. 14
0
int main_thread(SceSize args, void *argp)
{
	SceUID block_id;
	void *vram;

	block_id = sceKernelAllocPartitionMemory(4, "debugmenu", PSP_SMEM_Low, 512*272*2, NULL);
	if(block_id < 0)
	{
		Kprintf("Error could not allocate memory buffer 0x%08X\n", block_id);
		goto error;
	}
	 
	vram = (void*) (0xA0000000 | (unsigned int) sceKernelGetBlockHeadAddr(block_id));
	g_eventflag = sceKernelCreateEventFlag("DebugMenuEvent", 0, 0, NULL);
	if(g_eventflag < 0)
	{
		Kprintf("Could not create event flag %08X\n", g_eventflag);
		goto error;
	}

	//sceCtrlRegisterButtonCallback(0, PSP_CTRL_HOME, button_callback, NULL);
	sceCtrlRegisterButtonCallback(3, TRIGGER, button_callback, NULL);
	while(1)
	{
		unsigned int bits;
		if(sceKernelWaitEventFlag(g_eventflag, START_MENU,
					PSP_EVENT_WAITOR | PSP_EVENT_WAITCLEAR, &bits, NULL) < 0)
		{
			break;
		}
		sceCtrlSetButtonMasks(0xFFFF, 1);  // Mask lower 16bits
		sceCtrlSetButtonMasks(0x10000, 2); // Always return HOME key
		sceDisplaySetFrameBufferInternal(0, vram, 512, 0, 1);
		pspDebugScreenInitEx(vram, 0, 0);
		do_menu();
		sceDisplaySetFrameBufferInternal(0, 0, 512, 0, 1);
		sceCtrlSetButtonMasks(0x10000, 0); // Unset HOME key
		sceCtrlSetButtonMasks(0xFFFF, 0);  // Unset mask
		sceKernelClearEventFlag(g_eventflag, ~START_MENU);
	}

error:
	sceKernelExitDeleteThread(0);

	return 0;
}
Esempio n. 15
0
static int renderThread(unsigned int args, void* arg){
	
	for (;;){
	
		sceKernelWaitSema(GPU_Mutex, 1, NULL);
		memcpy(vita2d_texture_get_datap(gpu_texture), vita2d_texture_get_datap(next_texture), vita2d_texture_get_stride(gpu_texture)*240);
		sceKernelSignalSema(GPU_Mutex, 1);
		
		sceKernelWaitSema(GPU_Cleanup_Mutex, 1, NULL);
		
		if (main_texture == NULL) sceKernelExitDeleteThread(0); // Exit procedure
		
		vita2d_start_drawing();
   
		if (set_shader){
			Output::Post("Shader set to %s.",shader_names[in_use_shader]);
			set_shader = false;
			vita2d_texture_set_program(shaders[in_use_shader]->vertexProgram, shaders[in_use_shader]->fragmentProgram);
			vita2d_texture_set_wvp(shaders[in_use_shader]->wvpParam);
			vita2d_texture_set_vertexInput(&shaders[in_use_shader]->vertexInput);
			vita2d_texture_set_fragmentInput(&shaders[in_use_shader]->fragmentInput);
		}
   
		vita2d_clear_screen();
		switch (zoom_state){
			case 0: // 640x480
				vita2d_draw_texture_scale(gpu_texture, 160, 32, 2.0, 2.0);
				break;
			case 1: // 725x544
				vita2d_draw_texture_scale(gpu_texture, 117, 0, 2.266, 2.266);
				break;
			case 2: // 960x544
				vita2d_draw_texture_scale(gpu_texture, 0, 0, 3, 2.266);
				break;
		}
		vita2d_end_drawing();
		vita2d_wait_rendering_done();
		vita2d_swap_buffers();
		sceKernelSignalSema(GPU_Cleanup_Mutex, 1);
	
	}
	
}
Esempio n. 16
0
int main()
{
	SceUID thid;

	/* this is the thing we need the kernel mode for */
	pspSdkInstallNoDeviceCheckPatch();

	thid = sceKernelCreateThread("pico_main", (SceKernelThreadEntry) pico_main, 32, 0x2000, PSP_THREAD_ATTR_USER, NULL);
	if (thid >= 0)
		sceKernelStartThread(thid, 0, 0);
#ifndef GCOV
	sceKernelExitDeleteThread(0);
#else
	while (engineState != PGS_Quit)
		sceKernelDelayThread(1024 * 1024);
#endif

	return 0;
}
Esempio n. 17
0
int main(void)
{
	SceCtrlData pad;
	pspDebugScreenInit();
	SetupCallbacks();

	/* Install our custom exception handler. If this was NULL then the default would be used */
	pspDebugInstallErrorHandler(MyExceptionHandler);
	sceCtrlSetSamplingCycle(0);
	sceCtrlSetSamplingMode(PSP_CTRL_MODE_DIGITAL);

	pspDebugScreenPrintf("Exception Sample\n\n");
	pspDebugScreenPrintf("You have two choices, press O for a bus error or X for a breakpoint\n\n");

	while(1)
	{
		sceCtrlReadBufferPositive(&pad, 1);
		if(pad.Buttons & PSP_CTRL_CIRCLE)
		{
			/* Cause a bus error */
			_sw(0, 0);
		}

		if(pad.Buttons & PSP_CTRL_CROSS)
		{
			/* Cause a break exception */
			asm(
				"break\r\n"
			  );
		}

		sceDisplayWaitVblankStart();
	}


	/* We will never end up here, hopefully */
	printf("End\n");

	sceKernelExitDeleteThread(0);

	return 0;
}
Esempio n. 18
0
static int SoundThread()
{
	int err=0;
	int sample_count;
	int chan;
	int realSampleCount;
	int buf = 0;

	//For SMS, we need tighter timings
	if (menuConfig.sound.perfectSynchro && gblMachineType == EM_SMS)
		sample_count = 128;
	else
		sample_count = snd.sample_rate/snd.fps;
	sample_count = PSP_AUDIO_SAMPLE_ALIGN(sample_count);
	realSampleCount = sample_count / (44100 / snd.sample_rate);
	chan = sceAudioChReserve(PSP_AUDIO_NEXT_CHANNEL, sample_count, PSP_AUDIO_FORMAT_STEREO);

	if(chan > 0 && sample_count > 0 && sample_count <= 2048)
	{
		for(; soundRunning; )
		{
			if (soundPause)
				memset(audioOut[buf], 0, sample_count * sizeof(sample_t));
			else
				StandardSoundProcess();

			//Game Boy: réglage du son ne fonctionne pas!
			AudioGet(audioOut[buf], sample_count, realSampleCount);
			sceAudioOutputBlocking(chan, PSP_AUDIO_VOLUME_MAX, (void*)audioOut[buf]);

			if (menuConfig.sound.perfectSynchro)
				buf = 1 - buf;
		}

		sceAudioChRelease(chan);
	}

	soundRunning = -1;
	sceKernelExitDeleteThread(0);
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
    SceUID thid;

    save_argv0 = strdup(argv[0]);

    SetupCallbacks();

#ifdef DEBUG
    pspDebugScreenInit();
#endif

    if(pspSdkLoadInetModules() < 0)
       return 1;

    thid = sceKernelCreateThread("python_thread", main_thread, 0x18, 0x10000,
                                 PSP_THREAD_ATTR_USER|PSP_THREAD_ATTR_VFPU, NULL);
    sceKernelStartThread(thid, 0, NULL);

    sceKernelExitDeleteThread(0);

    return 0;
}
Esempio n. 20
0
static int server_thread(SceSize args, void *argp)
{
	int ret;
	UNUSED(ret);

	SceNetSockaddrIn serveraddr;

	DEBUG("Server thread started!\n");

	/* Create server socket */
	server_sockfd = sceNetSocket("FTPVita_server_sock",
		PSP2_NET_AF_INET,
		PSP2_NET_SOCK_STREAM,
		0);

	DEBUG("Server socket fd: %d\n", server_sockfd);

	/* Fill the server's address */
	serveraddr.sin_family = PSP2_NET_AF_INET;
	serveraddr.sin_addr.s_addr = sceNetHtonl(PSP2_NET_INADDR_ANY);
	serveraddr.sin_port = sceNetHtons(FTP_PORT);

	/* Bind the server's address to the socket */
	ret = sceNetBind(server_sockfd, (SceNetSockaddr *)&serveraddr, sizeof(serveraddr));
	DEBUG("sceNetBind(): 0x%08X\n", ret);

	/* Start listening */
	ret = sceNetListen(server_sockfd, 128);
	DEBUG("sceNetListen(): 0x%08X\n", ret);

	while (1) {

		/* Accept clients */
		SceNetSockaddrIn clientaddr;
		int client_sockfd;
		unsigned int addrlen = sizeof(clientaddr);

		DEBUG("Waiting for incoming connections...\n");

		client_sockfd = sceNetAccept(server_sockfd, (SceNetSockaddr *)&clientaddr, &addrlen);
		if (client_sockfd >= 0) {

			DEBUG("New connection, client fd: 0x%08X\n", client_sockfd);

			/* Get the client's IP address */
			char remote_ip[16];
			sceNetInetNtop(PSP2_NET_AF_INET,
				&clientaddr.sin_addr.s_addr,
				remote_ip,
				sizeof(remote_ip));

			INFO("Client %i connected, IP: %s port: %i\n",
				number_clients, remote_ip, clientaddr.sin_port);

			/* Create a new thread for the client */
			char client_thread_name[64];
			sprintf(client_thread_name, "FTPVita_client_%i_thread",
				number_clients);

			SceUID client_thid = sceKernelCreateThread(
				client_thread_name, client_thread,
				0x10000100, 0x10000, 0, 0, NULL);

			DEBUG("Client %i thread UID: 0x%08X\n", number_clients, client_thid);

			/* Allocate the ClientInfo struct for the new client */
			ClientInfo *client = malloc(sizeof(*client));
			client->num = number_clients;
			client->thid = client_thid;
			client->ctrl_sockfd = client_sockfd;
			client->data_con_type = FTP_DATA_CONNECTION_NONE;
			sprintf(client->cur_path, "%s%s", FTP_DEFAULT_PREFIX, FTP_DEFAULT_PATH);
			memcpy(&client->addr, &clientaddr, sizeof(client->addr));

			/* Add the new client to the client list */
			client_list_add(client);

			/* Start the client thread */
			sceKernelStartThread(client_thid, sizeof(*client), client);

			number_clients++;
		} else {
			/* if sceNetAccept returns < 0, it means that the listening
			 * socket has been closed, this means that we want to
			 * finish the server thread */
			DEBUG("Server socket closed, 0x%08X\n", client_sockfd);
			break;
		}
	}

	DEBUG("Server thread exiting!\n");

	sceKernelExitDeleteThread(0);
	return 0;
}
Esempio n. 21
0
/**
 * Matching IO Handler Thread
 * @param args sizeof(SceNetAdhocMatchingContext *)
 * @param argp SceNetAdhocMatchingContext *
 * @return Exit Point is never reached...
 */
int _matchingInputThread(uint32_t args, void * argp)
{
	// Cast Context
	SceNetAdhocMatchingContext * context = *(SceNetAdhocMatchingContext **)argp;
	
	// Last Ping
	uint64_t lastping = 0;
	
	// Last Hello
	uint64_t lasthello = 0;
	
	// Run while needed...
	while(context->input_thid > 0)
	{
		// Hello Message Sending Context with unoccupied Slots
		if((context->mode == ADHOC_MATCHING_MODE_PARENT && _countChildren(context) < (context->maxpeers - 1)) || (context->mode == ADHOC_MATCHING_MODE_P2P && _findP2P(context) == NULL))
		{
			// Hello Message Broadcast necessary because of Hello Interval
			if((sceKernelGetSystemTimeWide() - lasthello) >= context->hello_int)
			{
				// Broadcast Hello Message
				_broadcastHelloMessage(context);
				
				// Update Hello Timer
				lasthello = sceKernelGetSystemTimeWide();
			}
		}
		
		// Ping Required
		if((sceKernelGetSystemTimeWide() - lastping) >= context->keepalive_int)
		{
			// Broadcast Ping Message
			_broadcastPingMessage(context);
			
			// Update Ping Timer
			lastping = sceKernelGetSystemTimeWide();
		}
		
		// Messages on Stack ready for processing
		if(context->input_stack != NULL && context->input_stack_lock == 0)
		{
			// Claim Stack
			context->input_stack_lock = 1;
			
			// Iterate Message List
			ThreadMessage * msg = context->input_stack; for(; msg != NULL; msg = msg->next)
			{
				// Default Optional Data
				void * opt = NULL;
				
				// Grab Optional Data
				if(msg->optlen > 0) opt = ((void *)msg) + sizeof(ThreadMessage);
				
				// Send Accept Packet
				if(msg->opcode == ADHOC_MATCHING_PACKET_ACCEPT) _sendAcceptPacket(context, &msg->mac, msg->optlen, opt);
				
				// Send Join Packet
				else if(msg->opcode == ADHOC_MATCHING_PACKET_JOIN) _sendJoinPacket(context, &msg->mac, msg->optlen, opt);
				
				// Send Cancel Packet
				else if(msg->opcode == ADHOC_MATCHING_PACKET_CANCEL) _sendCancelPacket(context, &msg->mac, msg->optlen, opt);
				
				// Send Bulk Data Packet
				else if(msg->opcode == ADHOC_MATCHING_PACKET_BULK) _sendBulkDataPacket(context, &msg->mac, msg->optlen, opt);
				
				// Send Birth Packet
				else if(msg->opcode == ADHOC_MATCHING_PACKET_BIRTH) _sendBirthPacket(context, &msg->mac);
				
				// Cancel Bulk Data Transfer (does nothing as of now as we fire and forget anyway)
				// else if(msg->opcode == ADHOC_MATCHING_PACKET_BULK_ABORT) blabla;
			}
			
			// Clear IO Message Stack
			_clearStack(context, ADHOC_MATCHING_INPUT_STACK);
			
			// Free Stack
			context->input_stack_lock = 0;
		}
		
		// Receive PDP Datagram
		SceNetEtherAddr sendermac;
		uint16_t senderport;
		int rxbuflen = context->rxbuflen;
		int recvresult = sceNetAdhocPdpRecv(context->socket, &sendermac, &senderport, context->rxbuf, &rxbuflen, 0, ADHOC_F_NONBLOCK);
		
		// Received Data from a Sender that interests us
		if(recvresult == 0 && rxbuflen > 0 && context->port == senderport)
		{
			// Log Receive Success
			printk("Received %d Bytes (Opcode: %d)\n", rxbuflen, context->rxbuf[0]);
			
			// Ping Packet
			if(context->rxbuf[0] == ADHOC_MATCHING_PACKET_PING) _actOnPingPacket(context, &sendermac);
			
			// Hello Packet
			else if(context->rxbuf[0] == ADHOC_MATCHING_PACKET_HELLO) _actOnHelloPacket(context, &sendermac, rxbuflen);
			
			// Join Packet
			else if(context->rxbuf[0] == ADHOC_MATCHING_PACKET_JOIN) _actOnJoinPacket(context, &sendermac, rxbuflen);
			
			// Accept Packet
			else if(context->rxbuf[0] == ADHOC_MATCHING_PACKET_ACCEPT) _actOnAcceptPacket(context, &sendermac, rxbuflen);
			
			// Cancel Packet
			else if(context->rxbuf[0] == ADHOC_MATCHING_PACKET_CANCEL) _actOnCancelPacket(context, &sendermac, rxbuflen);
			
			// Bulk Data Packet
			else if(context->rxbuf[0] == ADHOC_MATCHING_PACKET_BULK) _actOnBulkDataPacket(context, &sendermac, rxbuflen);
			
			// Birth Packet
			else if(context->rxbuf[0] == ADHOC_MATCHING_PACKET_BIRTH) _actOnBirthPacket(context, &sendermac, rxbuflen);
			
			// Death Packet
			else if(context->rxbuf[0] == ADHOC_MATCHING_PACKET_DEATH) _actOnDeathPacket(context, &sendermac, rxbuflen);
			
			// Bye Packet
			else if(context->rxbuf[0] == ADHOC_MATCHING_PACKET_BYE) _actOnByePacket(context, &sendermac);
			
			// Ignore Incoming Trash Data
		}
		
		// Handle Peer Timeouts
		_handleTimeout(context);
		
		// Share CPU Time
		sceKernelDelayThread(10000);
	}
	
	// Send Bye Messages
	_sendByePacket(context);
	
	// Free Peer List Buffer
	_clearPeerList(context);
	
	// Delete Pointer Reference (and notify caller about finished cleanup)
	context->input_thid = 0;
	
	// Terminate Thread
	sceKernelExitDeleteThread(0);
	
	// Return Zero to shut up Compiler (never reached anyway)
	return 0;
}
Esempio n. 22
0
/**
 * Matching Event Dispatcher Thread
 * @param args sizeof(SceNetAdhocMatchingContext *)
 * @param argp SceNetAdhocMatchingContext *
 * @return Exit Point is never reached...
 */
int _matchingEventThread(uint32_t args, void * argp)
{
	// Cast Context
	SceNetAdhocMatchingContext * context = *(SceNetAdhocMatchingContext **)argp;
	
	// Run while needed...
	while(context->event_thid > 0)
	{
		// Messages on Stack ready for processing
		if(context->event_stack != NULL && context->event_stack_lock == 0)
		{
			// Claim Stack
			context->event_stack_lock = 1;
			
			// Iterate Message List
			ThreadMessage * msg = context->event_stack; for(; msg != NULL; msg = msg->next)
			{
				// Default Optional Data
				void * opt = NULL;
				
				// Grab Optional Data
				if(msg->optlen > 0) opt = ((void *)msg) + sizeof(ThreadMessage);
				
				// Log Matching Events
				printk("Matching Event [ID=%d] [EVENT=%d]\n", context->id, msg->opcode);
				
				// Call Event Handler
				context->handler(context->id, msg->opcode, &msg->mac, msg->optlen, opt);
			}
			
			// Clear Event Message Stack
			_clearStack(context, ADHOC_MATCHING_EVENT_STACK);
			
			// Free Stack
			context->event_stack_lock = 0;
		}
		
		// Share CPU Time
		sceKernelDelayThread(10000);
	}
	
	// Process Last Messages
	if(context->event_stack != NULL)
	{
		// Wait to claim Stack
		while(context->event_stack_lock) sceKernelDelayThread(10000);
		
		// Claim Stack
		context->event_stack_lock = 1;
		
		// Iterate Message List
		ThreadMessage * msg = context->event_stack; for(; msg != NULL; msg = msg->next)
		{
			// Default Optional Data
			void * opt = NULL;
			
			// Grab Optional Data
			if(msg->optlen > 0) opt = ((void *)msg) + sizeof(ThreadMessage);
			
			// Call Event Handler
			context->handler(context->id, msg->opcode, &msg->mac, msg->optlen, opt);
		}
		
		// Clear Event Message Stack
		_clearStack(context, ADHOC_MATCHING_EVENT_STACK);
		
		// Free Stack
		context->event_stack_lock = 0;
	}
	
	// Delete Pointer Reference (and notify caller about finished cleanup)
	context->event_thid = 0;
	
	// Terminate Thread
	sceKernelExitDeleteThread(0);
	
	// Return Zero to shut up Compiler (never reached anyway)
	return 0;
}
Esempio n. 23
0
int psp2link_commands_thread(SceSize args, void *argp)
{
	struct SceNetSockaddrIn serveraddr;
	struct SceNetSockaddrIn remote_addr;
	int ret;
	int len;
	unsigned int addrlen;
	unsigned int cmd;
	psp2link_pkt_hdr *header;
		
	debugNetPrintf(DEBUG,"[PSP2LINK] Command Thread Started.\n" );
	
	configuration->psp2link_commands_sock = sceNetSocket("commands_server_sock",SCE_NET_AF_INET, SCE_NET_SOCK_DGRAM, SCE_NET_IPPROTO_UDP);
	
	if (psp2LinkGetValue(COMMANDS_SOCK) >=0)
	{
		debugNetPrintf(DEBUG,"[PSP2LINK] Created psp2link_commands_sock: %d\n", psp2LinkGetValue(COMMANDS_SOCK));
	}
	else
	{
		debugNetPrintf(DEBUG,"[PSP2LINK] Error creating socket psp2link_commands_sock  0x%08X\n", psp2LinkGetValue(COMMANDS_SOCK));
		psp2LinkFinish();
		return -1;
	}
	/* Fill the server's address */
    memset(&serveraddr, 0, sizeof serveraddr);
	serveraddr.sin_family = SCE_NET_AF_INET;
	serveraddr.sin_addr.s_addr = sceNetHtonl(SCE_NET_INADDR_ANY);
	serveraddr.sin_port = sceNetHtons(psp2LinkGetValue(COMMANDS_PORT));	
	
	ret = sceNetBind(psp2LinkGetValue(COMMANDS_SOCK), (SceNetSockaddr *)&serveraddr, sizeof(serveraddr));
	
	
	
	
	if (ret < 0) 
	{
		debugNetPrintf(DEBUG,"[PSP2LINK] command listener sceNetBind error: 0x%08X\n", ret);
		sceNetSocketClose(psp2LinkGetValue(COMMANDS_SOCK));
		psp2LinkFinish();
		return -1;
	}
	// Do tha thing
	debugNetPrintf(DEBUG,"[PSP2LINK] Command listener waiting for commands...\n");
	
	while(psp2LinkGetValue(CMDSIO_ACTIVE)) {

		addrlen = sizeof(remote_addr);
		//wait for new command
		
		len = sceNetRecvfrom(psp2LinkGetValue(COMMANDS_SOCK), &recvbuf[0], BUF_SIZE, 0, (struct SceNetSockaddr *)&remote_addr,&addrlen);
		debugNetPrintf(DEBUG,"[PSP2LINK] commands listener received packet size (%d)\n", len);

		if (len < 0) {
			debugNetPrintf(DEBUG,"[PSP2LINK] commands listener recvfrom size error (%d)\n", len);
			continue;
		}
		if (len < sizeof(psp2link_pkt_hdr)) {
			debugNetPrintf(DEBUG,"[PSP2LINK] commands listener recvfrom header size error (%d)\n", len);
			continue;
		}

		header = (psp2link_pkt_hdr *)recvbuf;
		cmd = sceNetHtonl(header->cmd);
		
		switch (cmd) {

			case PSP2LINK_EXECELF_CMD:
				psp2LinkCmdExecElf((psp2link_pkt_exec_cmd *)recvbuf);
				break;
			case PSP2LINK_EXECSPRX_CMD:
				psp2LinkCmdExecSprx((psp2link_pkt_exec_cmd *)recvbuf);
				break;
			case PSP2LINK_EXIT_CMD:
				psp2LinkCmdExit((psp2link_pkt_exec_cmd *)recvbuf);
				break;
			default: 
				debugNetPrintf(DEBUG,"[PSP2LINK] Unknown command received\n");
				break;
		}
		debugNetPrintf(DEBUG,"[PSP2LINK] commands listener waiting for next command\n");
	}
	debugNetPrintf(DEBUG,"[PSP2LINK] exit commands listener thread\n");
	if(psp2LinkGetValue(COMMANDS_SOCK))
	{
		debugNetPrintf(DEBUG,"[PSP2LINK] closing server_commands_sock\n");
		sceNetSocketClose(psp2LinkGetValue(COMMANDS_SOCK));
		configuration->psp2link_commands_sock=-1;
	}
	
	sceKernelExitDeleteThread(0);
	return 0;
}
Esempio n. 24
0
int suicideFunc(SceSize argc, void *argv) {
	sceKernelExitDeleteThread(9);
	return 9;
}
Esempio n. 25
0
int main_thread(SceSize args, void *argp)
{
	#ifdef DEBUG
	pspDebugScreenInit();
	printf("Free Memory: %u KB\n",sceKernelTotalFreeMemSize()/1024);
	#else
	initGraphics();
	loadTheme();
	background = loadImageFromMemory(images[BACKGROUND].data, images[BACKGROUND].hdr.size);
	sceKernelFreePartitionMemory(images[BACKGROUND].blockid);
	images[BACKGROUND].blockid = -1;
	mask = loadImageFromMemory(images[MASK].data, images[MASK].hdr.size);
	sceKernelFreePartitionMemory(images[MASK].blockid);
	images[MASK].blockid = -1;
	#endif

	int firstUse = 0;
	int recovery = 0;
	int bytesRead = 0;
	Config cfg;
	char input[11];

	if ((args == 9) && (strcmp(argp, "recovery") == 0))
	{
		recovery = 1;
	}

	SceUID fp;
	fp = sceIoOpen("flash0:/buttons.ini", PSP_O_RDONLY, 0777);

	if (fp < 0)
	{
		#ifdef DEBUG
		printf("\nflash0:/buttons.ini could not be opned. Assuming first usage.");
		#endif
		firstUse = 1;
	}
	else
	{
		bytesRead = sceIoRead(fp, &cfg, sizeof(cfg));
		sceIoClose(fp);

		if(bytesRead != sizeof(cfg))
		{
			firstUse = 1;
		}
	}

	if (firstUse)
	{
		setPassword();
	}
	else if (((args == 0) || (recovery != 0)) || !(cfg.onlyBoot))
	{
		int len;
main_password:
		#ifndef DEBUG
		footer_pressselect = loadImageFromMemory(images[FOOTER_PRESSSELECT].data, images[FOOTER_PRESSSELECT].hdr.size);
		title_password = loadImageFromMemory(images[TITLE_PASSWORD].data, images[TITLE_PASSWORD].hdr.size);
		#endif
		while(1)
		{
			selectEnabled = 1;

			#ifdef DEBUG
			printf("\nPress START to accept.\nPress SELECT to change password.\nEnter password: "******"\nPassword OK.");
				#else
				int temp;
				blitImageToScreen(0, 0, images[BACKGROUND].hdr.w, images[BACKGROUND].hdr.h, background, images[BACKGROUND].hdr.x, images[BACKGROUND].hdr.y);
				blitAlphaImageToScreen(0, 0, images[FOOTER_PRESSSELECT].hdr.w, images[FOOTER_PRESSSELECT].hdr.h, footer_pressselect, images[FOOTER_PRESSSELECT].hdr.x, images[FOOTER_PRESSSELECT].hdr.y);
				blitAlphaImageToScreen(0, 0, images[TITLE_PASSWORD].hdr.w, images[TITLE_PASSWORD].hdr.h, title_password, images[TITLE_PASSWORD].hdr.x, images[TITLE_PASSWORD].hdr.y);
				msg_passwordok = loadImageFromMemory(images[MSG_PASSWORDOK].data, images[MSG_PASSWORDOK].hdr.size);
				blitAlphaImageToScreen(0, 0, images[MSG_PASSWORDOK].hdr.w, images[MSG_PASSWORDOK].hdr.h, msg_passwordok, images[MSG_PASSWORDOK].hdr.x, images[MSG_PASSWORDOK].hdr.y);
				freeImage(msg_passwordok);
				for(temp = 0; temp < len; temp++)
				{
					blitAlphaImageToScreen(0, 0, images[MASK].hdr.w, images[MASK].hdr.h, mask, images[MASK].hdr.x+(temp*images[MASK].hdr.w), images[MASK].hdr.y);
				}
				sceDisplayWaitVblankStart();
				flipScreen();
				#endif
				sceKernelDelayThread(1000*1000);
				break;
			}
			else
			{
				#ifdef DEBUG
				printf("\nIncorrect password.");
				#else
				int temp;
				blitImageToScreen(0, 0, images[BACKGROUND].hdr.w, images[BACKGROUND].hdr.h, background, images[BACKGROUND].hdr.x, images[BACKGROUND].hdr.y);
				blitAlphaImageToScreen(0, 0, images[FOOTER_PRESSSELECT].hdr.w, images[FOOTER_PRESSSELECT].hdr.h, footer_pressselect, images[FOOTER_PRESSSELECT].hdr.x, images[FOOTER_PRESSSELECT].hdr.y);
				blitAlphaImageToScreen(0, 0, images[TITLE_PASSWORD].hdr.w, images[TITLE_PASSWORD].hdr.h, title_password, images[TITLE_PASSWORD].hdr.x, images[TITLE_PASSWORD].hdr.y);
				msg_passwordincorrect = loadImageFromMemory(images[MSG_PASSWORDINCORRECT].data, images[MSG_PASSWORDINCORRECT].hdr.size);
				blitAlphaImageToScreen(0, 0, images[MSG_PASSWORDINCORRECT].hdr.w, images[MSG_PASSWORDINCORRECT].hdr.h, msg_passwordincorrect, images[MSG_PASSWORDINCORRECT].hdr.x, images[MSG_PASSWORDINCORRECT].hdr.y);
				freeImage(msg_passwordincorrect);
				for(temp = 0; temp < len; temp++)
				{
					blitAlphaImageToScreen(0, 0, images[MASK].hdr.w, images[MASK].hdr.h, mask, images[MASK].hdr.x+(temp*images[MASK].hdr.w), images[MASK].hdr.y);
				}
				sceDisplayWaitVblankStart();
				flipScreen();
				#endif
				sceKernelDelayThread(3000*1000);
			}
		}
		#ifndef DEBUG
		freeImage(footer_pressselect);
		freeImage(title_password);
		#endif

		if(len == -1)
		{
			#ifndef DEBUG
			footer_changemode = loadImageFromMemory(images[FOOTER_CHANGEMODE].data, images[FOOTER_CHANGEMODE].hdr.size);
			title_oldpassword = loadImageFromMemory(images[TITLE_OLDPASSWORD].data, images[TITLE_OLDPASSWORD].hdr.size);
			#endif
			while(1)
			{
				#ifdef DEBUG
				printf("\nChange password mode.\nEnter old password: "******"\nPassword OK.");
					#else
					int temp;
					blitImageToScreen(0, 0, images[BACKGROUND].hdr.w, images[BACKGROUND].hdr.h, background, images[BACKGROUND].hdr.x, images[BACKGROUND].hdr.y);
					blitAlphaImageToScreen(0, 0, images[FOOTER_CHANGEMODE].hdr.w, images[FOOTER_CHANGEMODE].hdr.h, footer_changemode, images[FOOTER_CHANGEMODE].hdr.x, images[FOOTER_CHANGEMODE].hdr.y);
					blitAlphaImageToScreen(0, 0, images[TITLE_OLDPASSWORD].hdr.w, images[TITLE_OLDPASSWORD].hdr.h, title_oldpassword, images[TITLE_OLDPASSWORD].hdr.x, images[TITLE_OLDPASSWORD].hdr.y);
					msg_passwordok = loadImageFromMemory(images[MSG_PASSWORDOK].data, images[MSG_PASSWORDOK].hdr.size);
					blitAlphaImageToScreen(0, 0, images[MSG_PASSWORDOK].hdr.w, images[MSG_PASSWORDOK].hdr.h, msg_passwordok, images[MSG_PASSWORDOK].hdr.x, images[MSG_PASSWORDOK].hdr.y);
					freeImage(msg_passwordok);
					for(temp = 0; temp < len; temp++)
					{
						blitAlphaImageToScreen(0, 0, images[MASK].hdr.w, images[MASK].hdr.h, mask, images[MASK].hdr.x+(temp*images[MASK].hdr.w), images[MASK].hdr.y);
					}
					sceDisplayWaitVblankStart();
					flipScreen();
					#endif
					sceKernelDelayThread(3000*1000);
					break;
				}
				else
				{
					#ifdef DEBUG
					printf("\nIncorrect password.");
					#else
					int temp;
					blitImageToScreen(0, 0, images[BACKGROUND].hdr.w, images[BACKGROUND].hdr.h, background, images[BACKGROUND].hdr.x, images[BACKGROUND].hdr.y);
					blitAlphaImageToScreen(0, 0, images[FOOTER_CHANGEMODE].hdr.w, images[FOOTER_CHANGEMODE].hdr.h, footer_changemode, images[FOOTER_CHANGEMODE].hdr.x, images[FOOTER_CHANGEMODE].hdr.y);
					blitAlphaImageToScreen(0, 0, images[TITLE_OLDPASSWORD].hdr.w, images[TITLE_OLDPASSWORD].hdr.h, title_oldpassword, images[TITLE_OLDPASSWORD].hdr.x, images[TITLE_OLDPASSWORD].hdr.y);
					msg_passwordincorrect = loadImageFromMemory(images[MSG_PASSWORDINCORRECT].data, images[MSG_PASSWORDINCORRECT].hdr.size);
					blitAlphaImageToScreen(0, 0, images[MSG_PASSWORDINCORRECT].hdr.w, images[MSG_PASSWORDINCORRECT].hdr.h, msg_passwordincorrect, images[MSG_PASSWORDINCORRECT].hdr.x, images[MSG_PASSWORDINCORRECT].hdr.y);
					freeImage(msg_passwordincorrect);
					for(temp = 0; temp < len; temp++)
					{
						blitAlphaImageToScreen(0, 0, images[MASK].hdr.w, images[MASK].hdr.h, mask, images[MASK].hdr.x+(temp*images[MASK].hdr.w), images[MASK].hdr.y);
					}
					sceDisplayWaitVblankStart();
					flipScreen();
					#endif
					sceKernelDelayThread(3000*1000);
				}
			}
			#ifndef DEBUG
			freeImage(footer_changemode);
			freeImage(title_oldpassword);
			#endif
			if(len == -1)
			{
				goto main_password;
			}
			selectEnabled = 0;
			setPassword();
		}
	}

	#ifndef DEBUG
	freeImage(background);
	freeImage(mask);
	sceGuTerm();
	int i;
	for (i = 0; i < NUMFILES; i++)
	{
		if (images[i].blockid != -1)
		{
			sceKernelFreePartitionMemory(images[i].blockid);
		}
	}
	#endif

	__psp_free_heap();
	#ifdef DEBUG
	printf("\n__psp_free_heap(): %u KB\n",sceKernelTotalFreeMemSize()/1024);
	sceKernelDelayThread(3000*1000);
	#endif

	#ifdef DEBUG
	printf("\nLoading loader.prx");
	#endif

	SceUID mod = sceKernelLoadModule("flash0:/loader.prx", 0, NULL);

	if (mod & 0x80000000)
	{
		#ifdef DEBUG
		printf("\nLoadModule failed 0x%x", mod);
		#endif
	}
	else
	{
		SceUID startmod;
		startmod = sceKernelStartModule(mod, args, argp, NULL, NULL);

		if (mod != startmod)
		{
			#ifdef DEBUG
			printf("\nStartModule failed 0x%x", startmod);
			#endif
		}
	}

	return sceKernelExitDeleteThread(0);
}
Esempio n. 26
0
/**
 * Friend Finder Thread (Receives Peer Information)
 * @param args Length of argp in Bytes (Unused)
 * @param argp Argument (Unused)
 * @return Unused Value - Return 0
 */
int _friendFinder(SceSize args, void * argp)
{
	// Receive Buffer
	int rxpos = 0;
	uint8_t rx[1024];
	
	// Chat Packet
	SceNetAdhocctlChatPacketC2S chat;
	chat.base.opcode = OPCODE_CHAT;
	
	// Last Ping Time
	uint64_t lastping = 0;
	
	// Last Time Reception got updated
	uint64_t lastreceptionupdate = 0;
	
	// Finder Loop
	while(_init == 1)
	{
		// Acquire Network Lock
		_acquireNetworkLock();
		
		// Ping Server
		if((sceKernelGetSystemTimeWide() - lastping) >= ADHOCCTL_PING_TIMEOUT)
		{
			// Update Ping Time
			lastping = sceKernelGetSystemTimeWide();
			
			// Prepare Packet
			uint8_t opcode = OPCODE_PING;
			
			// Send Ping to Server
			sceNetInetSend(_metasocket, &opcode, 1, INET_MSG_DONTWAIT);
		}
		
		// Send Chat Messages
		while(popFromOutbox(chat.message))
		{
			// Send Chat to Server
			sceNetInetSend(_metasocket, &chat, sizeof(chat), INET_MSG_DONTWAIT);
		}
		
		// Wait for Incoming Data
		int received = sceNetInetRecv(_metasocket, rx + rxpos, sizeof(rx) - rxpos, INET_MSG_DONTWAIT);
		
		// Free Network Lock
		_freeNetworkLock();
		
		// Received Data
		if(received > 0)
		{
			// Fix Position
			rxpos += received;
			
			// Log Incoming Traffic
			#ifdef DEBUG
			printk("Received %d Bytes of Data from Server\n", received);
			#endif
		}
		
		// Handle Packets
		if(rxpos > 0)
		{
			// BSSID Packet
			if(rx[0] == OPCODE_CONNECT_BSSID)
			{
				// Enough Data available
				if(rxpos >= sizeof(SceNetAdhocctlConnectBSSIDPacketS2C))
				{
					// Cast Packet
					SceNetAdhocctlConnectBSSIDPacketS2C * packet = (SceNetAdhocctlConnectBSSIDPacketS2C *)rx;
					
					// Update BSSID
					_parameter.bssid.mac_addr = packet->mac;
					
					// Change State
					_thread_status = ADHOCCTL_STATE_CONNECTED;
					
					// Notify Event Handlers
					int i = 0; for(; i < ADHOCCTL_MAX_HANDLER; i++)
					{
						// Active Handler
						if(_event_handler[i] != NULL) _event_handler[i](ADHOCCTL_EVENT_CONNECT, 0, _event_args[i]);
					}
					
					// Move RX Buffer
					memmove(rx, rx + sizeof(SceNetAdhocctlConnectBSSIDPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlConnectBSSIDPacketS2C));
					
					// Fix RX Buffer Length
					rxpos -= sizeof(SceNetAdhocctlConnectBSSIDPacketS2C);
				}
			}
			
			// Chat Packet
			else if(rx[0] == OPCODE_CHAT)
			{
				// Enough Data available
				if(rxpos >= sizeof(SceNetAdhocctlChatPacketS2C))
				{
					// Cast Packet
					SceNetAdhocctlChatPacketS2C * packet = (SceNetAdhocctlChatPacketS2C *)rx;
					
					// Fix for Idiots that try to troll the "ME" Nametag
					if(stricmp((char *)packet->name.data, "ME") == 0) strcpy((char *)packet->name.data, "NOT ME");
					
					// Add Incoming Chat to HUD
					addChatLog((char *)packet->name.data, packet->base.message);
					
					// Move RX Buffer
					memmove(rx, rx + sizeof(SceNetAdhocctlChatPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlChatPacketS2C));
					
					// Fix RX Buffer Length
					rxpos -= sizeof(SceNetAdhocctlChatPacketS2C);
				}
			}
			
			// Connect Packet
			else if(rx[0] == OPCODE_CONNECT)
			{
				// Enough Data available
				if(rxpos >= sizeof(SceNetAdhocctlConnectPacketS2C))
				{
					// Log Incoming Peer
					#ifdef DEBUG
					printk("Incoming Peer Data...\n");
					#endif
					
					// Cast Packet
					SceNetAdhocctlConnectPacketS2C * packet = (SceNetAdhocctlConnectPacketS2C *)rx;
					
					// Add User
					_addFriend(packet);
					
					// Update HUD User Count
					#ifdef LOCALHOST_AS_PEER
					setUserCount(_getActivePeerCount());
					#else
					setUserCount(_getActivePeerCount()+1);
					#endif
					
					// Move RX Buffer
					memmove(rx, rx + sizeof(SceNetAdhocctlConnectPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlConnectPacketS2C));
					
					// Fix RX Buffer Length
					rxpos -= sizeof(SceNetAdhocctlConnectPacketS2C);
				}
			}
			
			// Disconnect Packet
			else if(rx[0] == OPCODE_DISCONNECT)
			{
				// Enough Data available
				if(rxpos >= sizeof(SceNetAdhocctlDisconnectPacketS2C))
				{
					// Log Incoming Peer Delete Request
					#ifdef DEBUG
					printk("Incoming Peer Data Delete Request...\n");
					#endif
					
					// Cast Packet
					SceNetAdhocctlDisconnectPacketS2C * packet = (SceNetAdhocctlDisconnectPacketS2C *)rx;
					
					// Delete User by IP
					_deleteFriendByIP(packet->ip);
					
					// Update HUD User Count
					#ifdef LOCALHOST_AS_PEER
					setUserCount(_getActivePeerCount());
					#else
					setUserCount(_getActivePeerCount()+1);
					#endif
					
					// Move RX Buffer
					memmove(rx, rx + sizeof(SceNetAdhocctlDisconnectPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlDisconnectPacketS2C));
					
					// Fix RX Buffer Length
					rxpos -= sizeof(SceNetAdhocctlDisconnectPacketS2C);
				}
			}
			
			// Scan Packet
			else if(rx[0] == OPCODE_SCAN)
			{
				// Enough Data available
				if(rxpos >= sizeof(SceNetAdhocctlScanPacketS2C))
				{
					// Log Incoming Network Information
					#ifdef DEBUG
					printk("Incoming Group Information...\n");
					#endif
					
					// Cast Packet
					SceNetAdhocctlScanPacketS2C * packet = (SceNetAdhocctlScanPacketS2C *)rx;
					
					// Allocate Structure Data
					SceNetAdhocctlScanInfo * group = (SceNetAdhocctlScanInfo *)malloc(sizeof(SceNetAdhocctlScanInfo));
					
					// Allocated Structure Data
					if(group != NULL)
					{
						// Clear Memory
						memset(group, 0, sizeof(SceNetAdhocctlScanInfo));
						
						// Link to existing Groups
						group->next = _networks;
						
						// Copy Group Name
						group->group_name = packet->group;
						
						// Set Group Host
						group->bssid.mac_addr = packet->mac;
						
						// Link into Group List
						_networks = group;
					}
					
					// Move RX Buffer
					memmove(rx, rx + sizeof(SceNetAdhocctlScanPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlScanPacketS2C));
					
					// Fix RX Buffer Length
					rxpos -= sizeof(SceNetAdhocctlScanPacketS2C);
				}
			}
			
			// Scan Complete Packet
			else if(rx[0] == OPCODE_SCAN_COMPLETE)
			{
				// Log Scan Completion
				#ifdef DEBUG
				printk("Incoming Scan complete response...\n");
				#endif
				
				// Change State
				_thread_status = ADHOCCTL_STATE_DISCONNECTED;
				
				// Notify Event Handlers
				int i = 0; for(; i < ADHOCCTL_MAX_HANDLER; i++)
				{
					// Active Handler
					if(_event_handler[i] != NULL) _event_handler[i](ADHOCCTL_EVENT_SCAN, 0, _event_args[i]);
				}
				
				// Move RX Buffer
				memmove(rx, rx + 1, sizeof(rx) - 1);
				
				// Fix RX Buffer Length
				rxpos -= 1;
			}
		}
		
		// Reception Update required
		if((sceKernelGetSystemTimeWide() - lastreceptionupdate) > 5000000)
		{
			// Clone Time into Last Update Field
			lastreceptionupdate = sceKernelGetSystemTimeWide();
			
			// Update Reception Level
			union SceNetApctlInfo info;
			if(sceNetApctlGetInfo(PSP_NET_APCTL_INFO_STRENGTH, &info) >= 0) setReceptionPercentage((int)info.strength);
			else setReceptionPercentage(0);
		}
		
		//	Delay Thread (10ms)
		sceKernelDelayThread(10000);
	}
	
	// Set WLAN HUD Reception to 0% on Shutdown
	setReceptionPercentage(0);
	
	// Notify Caller of Shutdown
	_init = -1;
	
	// Log Shutdown
	printk("End of Friend Finder Thread\n");
	
	// Reset Thread Status
	_thread_status = ADHOCCTL_STATE_DISCONNECTED;
	
	// Kill Thread
	sceKernelExitDeleteThread(0);
	
	// Return Success
	return 0;
}
Esempio n. 27
0
/********************************************//**
 *  \brief Exiting point for loaded application
 *  
 *  This is hooked by the loaded application to 
 *  terminate the process early. The call is 
 *  not needed in normal operations.
 *  For this reason, you should not add any 
 *  cleanup code here.
 *  \returns Zero on success, otherwise error
 ***********************************************/
void
uvl_exit (int status)
{
    sceKernelExitDeleteThread (0);
}
Esempio n. 28
0
// Audio thread code
static int bgmThread(unsigned int args, void* arg){
	
	// Initializing audio port
	int ch = sceAudioOutOpenPort(SCE_AUDIO_OUT_PORT_TYPE_MAIN, NSAMPLES, 48000, SCE_AUDIO_OUT_MODE_STEREO);
	sceAudioOutSetConfig(ch, -1, -1, -1);
	old_vol = bgmvolume.value;
	int vol = 32767 * bgmvolume.value;
	int vol_stereo[] = {vol, vol};
	sceAudioOutSetVolume(ch, SCE_AUDIO_VOLUME_FLAG_L_CH | SCE_AUDIO_VOLUME_FLAG_R_CH, vol_stereo);
	
	DecodedMusic* mus;
	for (;;){
		
		// Waiting for an audio output request
		sceKernelWaitSema(Audio_Mutex, 1, NULL);
		
		// Fetching track
		mus = BGM;
		
		// Checking if a new track is available
		if (mus == NULL){
			
			//If we enter here, we probably are in the exiting procedure
			if (mustExit){
				sceAudioOutReleasePort(ch);
				mustExit = false;
				sceKernelExitDeleteThread(0);
			}
		
		}
		
		// Initializing audio decoder
		audio_decoder = AudioDecoder::Create(mus->handle, "Track");
		audio_decoder->Open(mus->handle);
		audio_decoder->SetLooping(mus->loop);
		audio_decoder->SetFormat(48000, AudioDecoder::Format::S16, 2);
		
		// Initializing audio buffers
		mus->audiobuf = (uint8_t*)malloc(BUFSIZE);
		mus->audiobuf2 = (uint8_t*)malloc(BUFSIZE);
		mus->cur_audiobuf = mus->audiobuf;
		
		// Audio playback loop
		for (;;){
		
			// Check if the music must be paused
			if (mus->pauseTrigger || mustExit){
			
				// Check if the music must be closed
				if (mus->closeTrigger){
					free(mus->audiobuf);
					free(mus->audiobuf2);
					audio_decoder.reset();
					free(mus);
					BGM = NULL;
					if (!mustExit){
						sceKernelSignalSema(Talk_Mutex, 1);
						break;
					}
				}
				
				// Check if the thread must be closed
				if (mustExit){
				
					// Check if the audio stream has already been closed
					if (mus != NULL){
						mus->closeTrigger = true;
						continue;
					}
					
					// Recursively closing all the threads
					sceAudioOutReleasePort(ch);
					mustExit = false;
					sceKernelExitThread(0);
					
				}
			
				mus->isPlaying = !mus->isPlaying;
				mus->pauseTrigger = false;
			}
			
			// Check if a volume change is required
			if (mus->changeVol){
				old_vol = bgmvolume.value;
				int vol = 32767 * bgmvolume.value;
				int vol_stereo[] = {vol, vol};
				sceAudioOutSetVolume(ch, SCE_AUDIO_VOLUME_FLAG_L_CH | SCE_AUDIO_VOLUME_FLAG_R_CH, vol_stereo);
				mus->changeVol = false;
			}
			
			if (mus->isPlaying){
				
				// Check if audio playback finished
				if ((!mus->loop) && audio_decoder->IsFinished()) mus->isPlaying = false;
				
				// Update audio output
				if (mus->cur_audiobuf == mus->audiobuf) mus->cur_audiobuf = mus->audiobuf2;
				else mus->cur_audiobuf = mus->audiobuf;
				audio_decoder->Decode(mus->cur_audiobuf, BUFSIZE);	
				sceAudioOutOutput(ch, mus->cur_audiobuf);
				
			}
			
		}
		
	}
	
}
Esempio n. 29
0
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;
}
Esempio n. 30
0
static int client_thread(SceSize args, void *argp)
{
	char cmd[16];
	cmd_dispatch_func dispatch_func;
	ClientInfo *client = (ClientInfo *)argp;

	DEBUG("Client thread %i started!\n", client->num);

	client_send_ctrl_msg(client, "220 FTPVita Server ready.\n");

	while (1) {

		memset(client->recv_buffer, 0, sizeof(client->recv_buffer));

		client->n_recv = sceNetRecv(client->ctrl_sockfd, client->recv_buffer, sizeof(client->recv_buffer), 0);
		if (client->n_recv > 0) {
			DEBUG("Received %i bytes from client number %i:\n",
				client->n_recv, client->num);

			INFO("\t%i> %s", client->num, client->recv_buffer);

			/* The command are the first chars until the first space */
			sscanf(client->recv_buffer, "%s", cmd);

			/* Wait 1 ms before sending any data */
			sceKernelDelayThread(1*1000);

			if ((dispatch_func = get_dispatch_func(cmd))) {
				dispatch_func(client);
			} else {
				client_send_ctrl_msg(client, "502 Sorry, command not implemented. :(\n");
			}

		} else if (client->n_recv == 0) {
			/* Value 0 means connection closed by the remote peer */
			INFO("Connection closed by the client %i.\n", client->num);
			/* Delete itself from the client list */
			client_list_delete(client);
			break;
		} else if (client->n_recv == PSP2_NET_ERROR_ECANCELED) {
			/* PSP2_NET_ERROR_ECANCELED means socket shutdown */
			DEBUG("Client %i socket shutdown\n", client->num);
			break;
		} else {
			/* Other errors */
			INFO("Socket error client %i.\n", client->num);
			client_list_delete(client);
			break;
		}
	}

	/* Close the client's socket */
	sceNetSocketClose(client->ctrl_sockfd);

	/* If there's an open data connection, close it */
	if (client->data_con_type != FTP_DATA_CONNECTION_NONE) {
		sceNetSocketClose(client->data_sockfd);
		if (client->data_con_type == FTP_DATA_CONNECTION_PASSIVE) {
			sceNetSocketClose(client->pasv_sockfd);
		}
	}

	DEBUG("Client thread %i exiting!\n", client->num);

	/* Temporary newlib thread malloc bug fix */
	// free(client);

	sceKernelExitDeleteThread(0);
	return 0;
}