Example #1
0
  /********************  Mass Storage interface ********************/
  0x09,   /* bLength: Interface Descriptor size */
  0x04,   /* bDescriptorType: */
  MSC_INTERFACE,   /* bInterfaceNumber: Number of Interface */
  0x00,   /* bAlternateSetting: Alternate setting */
  0x02,   /* bNumEndpoints*/
  0x08,   /* bInterfaceClass: MSC Class */
  0x06,   /* bInterfaceSubClass : SCSI transparent*/
  0x50,   /* nInterfaceProtocol */
  0x05,          /* iInterface: */
  /********************  Mass Storage Endpoints ********************/
  0x07,   /*Endpoint descriptor length = 7*/
  0x05,   /*Endpoint descriptor type */
  MSC_IN_EP,   /*Endpoint address (IN, address 1) */
  0x02,   /*Bulk endpoint type */
  LOBYTE(MSC_MAX_PACKET),
  HIBYTE(MSC_MAX_PACKET),
  0x00,   /*Polling interval in milliseconds */
  
  0x07,   /*Endpoint descriptor length = 7 */
  0x05,   /*Endpoint descriptor type */
  MSC_OUT_EP,   /*Endpoint address (OUT, address 1) */
  0x02,   /*Bulk endpoint type */
  LOBYTE(MSC_MAX_PACKET),
  HIBYTE(MSC_MAX_PACKET),
  0x00     /*Polling interval in milliseconds*/
} ;

/* Private function prototypes -----------------------------------------------*/

/*********************************************
Example #2
0
// Plug-in process
void CORE_Process(int iArg)
{
    try
    {
        char version[16];
        sprintf(version, "%u.%u", HIBYTE(MY_VERSION), LOBYTE(MY_VERSION));
        msg("\n>> WhatAPIs: v: %s, built: %s, By Sirmabus\n", version, __DATE__);
        if (!autoIsOk())
        {
            msg("** Must wait for IDA to finish processing before starting plug-in! **\n*** Aborted ***\n\n");
            return;
        }

        // Show UI
        refreshUI();
        int uiResult = AskUsingForm_c(mainDialog, version, doHyperlink);
        if (!uiResult)
        {
            msg(" - Canceled -\n");
            return;
        }

        WaitBox::show();
        TIMESTAMP startTime = getTimeStamp();

        // Build import segment bounds table
        {
            msg("Import segments:\n");
            refreshUI();
            SEGLIST segList;
            for (int i = 0; i < get_segm_qty(); i++)
            {
                if (segment_t *s = getnseg(i))
                {
                    if (s->type == SEG_XTRN)
                    {
                        char buffer[64] = { "unknown" }; buffer[SIZESTR(buffer)] = 0;
                        get_true_segm_name(s, buffer, SIZESTR(buffer));
                        msg(" [%d] \"%s\" "EAFORMAT" - "EAFORMAT"\n", segmentCount, buffer, s->startEA, s->endEA);
                        BOUNDS b = { s->startEA, s->endEA };
                        segList.push_back(b);
                        segmentCount++;
                    }
                }
            }
            refreshUI();

            // Flatten list into an array for speed
            if (segmentCount)
            {
                UINT size = (segmentCount * sizeof(BOUNDS));
                if (segmentPtr = (BOUNDS *)_aligned_malloc(size, 16))
                {
                    BOUNDS *b = segmentPtr;
                    for (SEGLIST::iterator i = segList.begin(); i != segList.end(); i++, b++)
                    {
                        b->startEA = i->startEA;
                        b->endEA   = i->endEA;
                    }
                }
                else
                {
                    msg("\n*** Allocation failure of %u bytes! ***\n", size);
                    refreshUI();
                }
            }
        }

        if (segmentCount)
        {
            // Make a list of all import names
            if (int moduleCount = get_import_module_qty())
            {
                for (int i = 0; i < moduleCount; i++)
                    enum_import_names(i, importNameCallback);

                char buffer[32];
                msg("Parsed %s module imports.\n", prettyNumberString(moduleCount, buffer));
                refreshUI();
            }

            // Iterate through all functions..
            BOOL aborted = FALSE;
            UINT functionCount = get_func_qty();
            char buffer[32];
            msg("Processing %s functions.\n", prettyNumberString(functionCount, buffer));
            refreshUI();

            for (UINT n = 0; n < functionCount; n++)
            {
                processFunction(getn_func(n));

                if (WaitBox::isUpdateTime())
                {
                    if (WaitBox::updateAndCancelCheck((int)(((float)n / (float)functionCount) * 100.0f)))
                    {
                        msg("* Aborted *\n");
                        break;
                    }
                }
            }

            refresh_idaview_anyway();
            WaitBox::hide();
            msg("\n");
            msg("Done. %s comments add/appended in %s.\n", prettyNumberString(commentCount, buffer), timeString(getTimeStamp() - startTime));
            msg("-------------------------------------------------------------\n");
        }
        else
            msg("\n*** No import segments! ***\n");

        if (segmentPtr)
        {
            _aligned_free(segmentPtr);
            segmentPtr = NULL;
        }
        apiMap.clear();
    }
    CATCH()
}
Example #3
0
RACE_DESC*
init_shofixti (void)
{
    RACE_DESC *RaceDescPtr;

    static RACE_DESC new_shofixti_desc;

    shofixti_desc.postprocess_func = shofixti_postprocess;
    shofixti_desc.init_weapon_func = initialize_standard_missile;
    shofixti_desc.cyborg_control.intelligence_func = shofixti_intelligence;

    new_shofixti_desc = shofixti_desc;
    if (LOBYTE (GLOBAL (CurrentActivity)) == IN_ENCOUNTER
            && !GET_GAME_STATE (SHOFIXTI_RECRUITED))
    {
        // Tanaka/Katana flies in a damaged ship.
#define NUM_LIMPETS 3
        COUNT i;

        new_shofixti_desc.ship_data.ship_rsc[0] = OLDSHOF_BIG_MASK_PMAP_ANIM;
        new_shofixti_desc.ship_data.ship_rsc[1] = OLDSHOF_MED_MASK_PMAP_ANIM;
        new_shofixti_desc.ship_data.ship_rsc[2] = OLDSHOF_SML_MASK_PMAP_ANIM;
        new_shofixti_desc.ship_data.special_rsc[0] = NULL_RESOURCE;
        new_shofixti_desc.ship_data.special_rsc[1] = NULL_RESOURCE;
        new_shofixti_desc.ship_data.special_rsc[2] = NULL_RESOURCE;
        new_shofixti_desc.ship_data.captain_control.captain_rsc =
            OLDSHOF_CAPTAIN_MASK_PMAP_ANIM;

        /* Weapon doesn't work as well */
        new_shofixti_desc.characteristics.weapon_wait = 10;

        /* Simulate VUX limpets */
        for (i = 0; i < NUM_LIMPETS; ++i)
        {
            if (++new_shofixti_desc.characteristics.turn_wait == 0)
                --new_shofixti_desc.characteristics.turn_wait;
            if (++new_shofixti_desc.characteristics.thrust_wait == 0)
                --new_shofixti_desc.characteristics.thrust_wait;
#define MIN_THRUST_INCREMENT DISPLAY_TO_WORLD (1)
            if (new_shofixti_desc.characteristics.thrust_increment <=
                    MIN_THRUST_INCREMENT)
            {
                new_shofixti_desc.characteristics.max_thrust =
                    new_shofixti_desc.characteristics.thrust_increment << 1;
            }
            else
            {
                COUNT num_thrusts;

                num_thrusts = new_shofixti_desc.characteristics.max_thrust /
                              new_shofixti_desc.characteristics.thrust_increment;
                --new_shofixti_desc.characteristics.thrust_increment;
                new_shofixti_desc.characteristics.max_thrust =
                    new_shofixti_desc.characteristics.thrust_increment *
                    num_thrusts;
            }
        }
    }

    RaceDescPtr = &new_shofixti_desc;

    return (RaceDescPtr);
}
Example #4
0
/*
 * set_tool_item_proc - ツールの項目を設定
 */
static BOOL CALLBACK set_tool_item_proc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	TOOL_INFO *ti;
	TCHAR buf[BUF_SIZE];
	int i;

	switch (uMsg) {
	case WM_INITDIALOG:
		if (lParam == 0) {
			// 新規追加
			SendMessage(hDlg, WM_COMMAND, IDC_CHECK_MENU, 0);
			SetWindowLong(hDlg, GWL_USERDATA, 0);
			break;
		}
		ti = (TOOL_INFO *)lParam;

		SendDlgItemMessage(hDlg, IDC_EDIT_TITLE, WM_SETTEXT, 0, (LPARAM)ti->title);
		SendDlgItemMessage(hDlg, IDC_EDIT_LIB_PATH, WM_SETTEXT, 0, (LPARAM)ti->lib_file_path);
		SendDlgItemMessage(hDlg, IDC_EDIT_HEADER, WM_SETTEXT, 0, (LPARAM)ti->func_name);
		SendDlgItemMessage(hDlg, IDC_EDIT_CMD_LINE, WM_SETTEXT, 0, (LPARAM)ti->cmd_line);

		set_call_type(hDlg, ti->call_type);
		CheckDlgButton(hDlg, IDC_CHECK_COPY_PATE, ti->copy_paste);
		CheckDlgButton(hDlg, IDC_CHECK_OLD, ti->old);

		i = 0;
		if (ti->modifiers & MOD_SHIFT) {
			i |= HOTKEYF_SHIFT;
		}
		if (ti->modifiers & MOD_CONTROL) {
			i |= HOTKEYF_CONTROL;
		}
		if (ti->modifiers & MOD_ALT) {
			i |= HOTKEYF_ALT;
		}
		if (ti->modifiers & MOD_WIN) {
			i |= HOTKEYF_WIN;
		}
		if (ti->virtkey != 0) {
			SendDlgItemMessage(hDlg, IDC_HOTKEY_TOOL, HKM_SETHOTKEY,
				(WPARAM)MAKEWORD(ti->virtkey, i), 0);
		}
		SendMessage(hDlg, WM_COMMAND, IDC_CHECK_MENU, 0);

		SetWindowLong(hDlg, GWL_USERDATA, lParam);
		break;

	case WM_CLOSE:
		EndDialog(hDlg, FALSE);
		break;

	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case IDC_CHECK_MENU:
			EnableWindow(GetDlgItem(hDlg, IDC_CHECK_COPY_PATE), IsDlgButtonChecked(hDlg, IDC_CHECK_MENU));
			EnableWindow(GetDlgItem(hDlg, IDC_HOTKEY_TOOL), IsDlgButtonChecked(hDlg, IDC_CHECK_MENU));
			break;

		case IDC_BUTTON_FILE_SELECT:
			// ファイル選択
			SetFocus(GetDlgItem(hDlg, IDC_EDIT_LIB_PATH));
			if (file_select(hDlg, TEXT("*.dll\0*.dll\0*.*\0*.*\0\0"), 1, buf) == -1) {
				break;
			}
			SendDlgItemMessage(hDlg, IDC_EDIT_LIB_PATH, WM_SETTEXT, 0, (LPARAM)buf);
			SendDlgItemMessage(hDlg, IDC_EDIT_HEADER, WM_SETTEXT, 0, (LPARAM)TEXT(""));

		case IDC_BUTTON_FUNC_SELECT:
			// ツール選択
			*buf = TEXT('\0');
			SendDlgItemMessage(hDlg, IDC_EDIT_LIB_PATH, WM_GETTEXT, BUF_SIZE - 1, (LPARAM)buf);
			if (DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_DIALOG_SELECT_FUNC), hDlg, select_tool_proc, (LPARAM)buf) == TRUE) {
				SendMessage(hDlg, WM_COMMAND, IDC_CHECK_MENU, 0);
			}
			break;

		case IDOK:
			*buf = TEXT('\0');
			SendDlgItemMessage(hDlg, IDC_EDIT_TITLE, WM_GETTEXT, BUF_SIZE - 1, (LPARAM)buf);
			if (*buf == TEXT('\0')) {
				MessageBox(hDlg, message_get_res(IDS_TOOL_ERR_TITLE), WINDOW_TITLE, MB_ICONEXCLAMATION);
				SetFocus(GetDlgItem(hDlg, IDC_EDIT_TITLE));
				break;
			}

			if ((ti = (TOOL_INFO *)GetWindowLong(hDlg, GWL_USERDATA)) == NULL) {
				ti = mem_calloc(sizeof(TOOL_INFO));
			}
			if (ti != NULL) {
				// 設定取得
				alloc_get_text(GetDlgItem(hDlg, IDC_EDIT_TITLE), &ti->title);
				alloc_get_text(GetDlgItem(hDlg, IDC_EDIT_LIB_PATH), &ti->lib_file_path);
				alloc_get_text(GetDlgItem(hDlg, IDC_EDIT_HEADER), &ti->func_name);
				alloc_get_text(GetDlgItem(hDlg, IDC_EDIT_CMD_LINE), &ti->cmd_line);
				
				ti->call_type = 0;
				ti->call_type |= (IsDlgButtonChecked(hDlg, IDC_CHECK_MENU) * CALLTYPE_MENU);
				ti->call_type |= (IsDlgButtonChecked(hDlg, IDC_CHECK_VIEWER) * CALLTYPE_VIEWER);
				ti->call_type |= (IsDlgButtonChecked(hDlg, IDC_CHECK_VIEWER_OPEN) * CALLTYPE_VIEWER_OPEN);
				ti->call_type |= (IsDlgButtonChecked(hDlg, IDC_CHECK_VIEWER_CLOSE) * CALLTYPE_VIEWER_CLOSE);
				ti->call_type |= (IsDlgButtonChecked(hDlg, IDC_CHECK_HISTORY) * CALLTYPE_ADD_HISTORY);
				ti->call_type |= (IsDlgButtonChecked(hDlg, IDC_CHECK_CLIPBOARD) * CALLTYPE_ITEM_TO_CLIPBOARD);
				ti->call_type |= (IsDlgButtonChecked(hDlg, IDC_CHECK_START) * CALLTYPE_START);
				ti->call_type |= (IsDlgButtonChecked(hDlg, IDC_CHECK_END) * CALLTYPE_END);

				ti->copy_paste = IsDlgButtonChecked(hDlg, IDC_CHECK_COPY_PATE);
				ti->old = IsDlgButtonChecked(hDlg, IDC_CHECK_OLD);

				i = SendDlgItemMessage(hDlg, IDC_HOTKEY_TOOL, HKM_GETHOTKEY, 0, 0);
				ti->virtkey = LOBYTE(i);
				i = HIBYTE(i);
				ti->modifiers = ((i & HOTKEYF_SHIFT) ? MOD_SHIFT : 0) |
					((i & HOTKEYF_CONTROL) ? MOD_CONTROL : 0) |
					((i & HOTKEYF_ALT) ? MOD_ALT : 0) |
					((i & HOTKEYF_WIN) ? MOD_WIN : 0);
			}

			if (GetWindowLong(hDlg, GWL_USERDATA) == 0) {
				// 新規
				HWND pWnd = PropSheet_GetCurrentPageHwnd(GetParent(hDlg));
				listview_set_tool(GetDlgItem(pWnd, IDC_LIST_TOOL), ti, FALSE);
			}
			EndDialog(hDlg, TRUE);
			break;

		case IDCANCEL:
			EndDialog(hDlg, FALSE);
			break;
		}
		break;

	default:
		return FALSE;
	}
	return TRUE;
}
Example #5
0
//-------------------------------------------------------------------------------------------------
//  Public Functions
//-------------------------------------------------------------------------------------------------
static ST_EEPROM_PARA getEepeomParameter(ST_EEPROM_ID EepromType,MS_U16 offset)
{
    ST_EEPROM_PARA stEtype;
    u16 u16Tmp = 0;
   
    switch(EepromType.type)
    {
        case EEPROM_24C01:    
        case EEPROM_24C02:
            stEtype.u16SlaveIDAddr=EepromType.u16DeviceAddr;
            stEtype.u8AddrCnt=1;
            stEtype.pu8Offset[0]=LOBYTE(offset);
            stEtype.u8PageSize=8;
            break;
        case EEPROM_24C04:
            u16Tmp=((HIBYTE(offset)&0x1)<<1);          
            stEtype.u16SlaveIDAddr=(EepromType.u16DeviceAddr|u16Tmp);
            stEtype.u8AddrCnt=1;
            stEtype.pu8Offset[0]=LOBYTE(offset);
            stEtype.u8PageSize=16;            
            break;
        case EEPROM_24C08:
            u16Tmp=((HIBYTE(offset)&0x3)<<1);          
            stEtype.u16SlaveIDAddr=(EepromType.u16DeviceAddr|u16Tmp);
            stEtype.u8AddrCnt=1;
            stEtype.pu8Offset[0]=LOBYTE(offset);
            stEtype.u8PageSize=16;                        
            break;
        case EEPROM_24C16:
            u16Tmp=((HIBYTE(offset)&0x7)<<1);          
            stEtype.u16SlaveIDAddr=(EepromType.u16DeviceAddr|u16Tmp);
            stEtype.u8AddrCnt=1;
            stEtype.pu8Offset[0]=LOBYTE(offset);
            stEtype.u8PageSize=16;              
            break;            
        case EEPROM_24C32:            
        case EEPROM_24C64:            
            stEtype.u8PageSize=32;              
            stEtype.u16SlaveIDAddr=EepromType.u16DeviceAddr;
            stEtype.u8AddrCnt=2;
            stEtype.pu8Offset[0]=HIBYTE(offset);
            stEtype.pu8Offset[1]=LOBYTE(offset);            
            break;
        case EEPROM_24C128:
        case EEPROM_24C256:
            stEtype.u8PageSize=64;              
            stEtype.u16SlaveIDAddr=EepromType.u16DeviceAddr;
            stEtype.u8AddrCnt=2;
            stEtype.pu8Offset[0]=HIBYTE(offset);
            stEtype.pu8Offset[1]=LOBYTE(offset);                
            break;
        case EEPROM_24C512:
            stEtype.u8PageSize=128;              
            stEtype.u16SlaveIDAddr=EepromType.u16DeviceAddr;
            stEtype.u8AddrCnt=2;
            stEtype.pu8Offset[0]=HIBYTE(offset);
            stEtype.pu8Offset[1]=LOBYTE(offset);                
        case EEPROM_24C1024:            
            stEtype.u8PageSize=256;              
            stEtype.u16SlaveIDAddr=EepromType.u16DeviceAddr;
            stEtype.u8AddrCnt=2;
            stEtype.pu8Offset[0]=HIBYTE(offset);
            stEtype.pu8Offset[1]=LOBYTE(offset);                
            break;
        default:
            UBOOT_ERROR("Wrong Eeprom Type!!\n");
            break;
    }
    return stEtype;
}
Example #6
0
LRESULT WINAPI ImmEscapeW(
    HKL    hKL,
    HIMC   hImc,
    UINT   uSubFunc,
    LPVOID lpData)
{
    PIMEDPI pImeDpi;
    LRESULT lRet = 0;

    pImeDpi = FindOrLoadImeDpi(hKL);
    if (pImeDpi == NULL) {
        RIPMSG0(RIP_WARNING, "ImmEscapeW: no pImeDpi entry.");
        return lRet;
    }

    if ((pImeDpi->ImeInfo.fdwProperty & IME_PROP_UNICODE) || lpData == NULL) {
        /*
         * Doesn't need W/A conversion. Calls directly to IME to
         * bring up the configuration dialogbox.
         */
        lRet = (*pImeDpi->pfn.ImeEscape)(hImc, uSubFunc, lpData);
        ImmUnlockImeDpi(pImeDpi);
        return lRet;
    }

    /*
     * Unicode caller, ANSI IME. Needs W/A conversion depending on
     * uSubFunc.
     */
    switch (uSubFunc) {
    case IME_ESC_GET_EUDC_DICTIONARY:
    case IME_ESC_IME_NAME:
        {
            CHAR szData[IME_T_EUDC_DIC_SIZE];
            INT  i;

            lRet = ImmEscapeA(hKL, hImc, uSubFunc, (LPVOID)szData);

            if (lRet != 0) {

                try {
                    i = MultiByteToWideChar(CP_ACP,
                                            (DWORD)MB_PRECOMPOSED,
                                            (LPSTR)szData,          // src
                                            (INT)strlen(szData),
                                            (LPWSTR)lpData,         // dest
                                            (INT)IME_T_EUDC_DIC_SIZE);
                    ((LPWSTR)lpData)[i] = L'\0';
                }
                except (EXCEPTION_EXECUTE_HANDLER) {
                    lRet = 0;
                }
            }

            break;
        }

    case IME_ESC_SET_EUDC_DICTIONARY:
    case IME_ESC_HANJA_MODE:
        {
            CHAR szData[IME_T_EUDC_DIC_SIZE];
            BOOL bUDC;
            INT  i;

            i = WideCharToMultiByte( CP_ACP,
                                    (DWORD)0,
                                    (LPWSTR)lpData,          // src
                                    (INT)wcslen(lpData),
                                    (LPSTR)szData,          // dest
                                    (INT)sizeof(szData),
                                    (LPSTR)NULL,
                                    (LPBOOL)&bUDC);
            szData[i] = '\0';

            lRet = ImmEscapeA(hKL, hImc, uSubFunc, (LPVOID)szData);

            break;
        }

    case IME_ESC_SEQUENCE_TO_INTERNAL:
        {
            CHAR    szData[4];
            WCHAR   wszData[4];
            INT     i = 0;

            lRet = ImmEscapeA(hKL, hImc, uSubFunc, lpData);

            if (HIBYTE(LOWORD(lRet)))
                szData[i++] = HIBYTE(LOWORD(lRet));

            if (LOBYTE(LOWORD(lRet)))
                szData[i++] = LOBYTE(LOWORD(lRet));

            i = MultiByteToWideChar(CP_ACP,
                                    (DWORD)MB_PRECOMPOSED,
                                    (LPSTR)szData,            // src
                                    i,
                                    (LPWSTR)wszData,          // dest
                                    (INT)sizeof(wszData)/sizeof(WCHAR));

            switch (i) {
            case 1:
                lRet = MAKELONG(wszData[0], 0);
                break;

            case 2:
                lRet = MAKELONG(wszData[1], wszData[0]);
                break;

            default:
                lRet = 0;
                break;
            }

            break;
        }

    default:
        lRet = ImmEscapeA(hKL, hImc, uSubFunc, lpData);
        break;
    }

    ImmUnlockImeDpi(pImeDpi);

    return lRet;
}
Example #7
0
static int
PackCommRqtEx(unsigned char* pAppBuf, int nAppBufLen, PBYTE pSA, PBYTE pDA, BOOL bNeedRsp, unsigned char nSeq, unsigned char* pFrm)
{
	int				nFrmLen	= 0;
	int				nLenPos	= OFFSET_COM_LY_PACKAGE_LEN;
//	unsigned int	nSeq	= GetNextRqtSeq();
	unsigned short  usChk = 0;
	int i = 0;
	// STX
	*(pFrm + nFrmLen + 1) = BACP_COM_LY_STX_B0;
	*(pFrm + nFrmLen + 0) = BACP_COM_LY_STX_B1;

	nFrmLen += LEN_COM_STX;
	// VER
	*(pFrm + nFrmLen) = CURRENT_COM_NET_LAY_VER;
	nFrmLen += LEN_COM_VER;

	// LEN
	nFrmLen += LEN_COM_LEN;

	// SEQ

	*(pFrm + nFrmLen + 0) = nSeq;
			
	nFrmLen += LEN_COM_SEQ;


	// OPT
	if (bNeedRsp)
	{
		*(pFrm + nFrmLen) = COM_LY_OPT_REQ_ON ;
	}
	else
	{
		*(pFrm + nFrmLen) = COM_LY_OPT_REQ_OFF ;
	}
	nFrmLen += LEN_COM_OPT; 

	memcpy(pFrm + nFrmLen, pDA, 3);
	nFrmLen += LEN_COM_DA;

	memcpy(pFrm + nFrmLen, pSA, 3);
	nFrmLen += LEN_COM_SA;
	// APP
	memcpy((pFrm + nFrmLen), pAppBuf, nAppBufLen);
	nFrmLen += nAppBufLen;
	
	// check num
	nFrmLen += 2;

	// ETX
	*(pFrm + nFrmLen + 1) = BACP_COM_LY_ETX_B0;
	*(pFrm + nFrmLen + 0) = BACP_COM_LY_ETX_B1;

	nFrmLen += LEN_COM_ETX;

	// Fill LEN 
	*(pFrm + nLenPos + 1) = LOBYTE(nFrmLen);
	*(pFrm + nLenPos + 0) = HIBYTE(nFrmLen);


	usChk = 0;
	for (i = LEN_COM_STX; i < nFrmLen - 4; i++)
	{
		usChk += *(pFrm + i);
	}

	*(pFrm + nFrmLen - 3) = LOBYTE(usChk);
	*(pFrm + nFrmLen - 4) = HIBYTE(usChk);

	return nFrmLen;
}
Example #8
0
/**************************************************************************
 * 			modData					[internal]
 */
static DWORD modData(WORD wDevID, DWORD dwParam)
{
    BYTE	evt = LOBYTE(LOWORD(dwParam));
    BYTE	d1  = HIBYTE(LOWORD(dwParam));
    BYTE	d2  = LOBYTE(HIWORD(dwParam));
    
    TRACE("(%04X, %08lX);\n", wDevID, dwParam);

    if (wDevID >= MODM_NumDevs) return MMSYSERR_BADDEVICEID;
    if (!MidiOutDev[wDevID].bEnabled) return MIDIERR_NODEVICE;

    if (midiSeq == NULL) {
	WARN("can't play !\n");
	return MIDIERR_NODEVICE;
    }
    switch (MidiOutDev[wDevID].caps.wTechnology) {
    case MOD_SYNTH:
    case MOD_MIDIPORT:
	{
	    int handled = 1; /* Assume event is handled */
            snd_seq_event_t event;
            snd_seq_ev_clear(&event);
            snd_seq_ev_set_direct(&event);
            snd_seq_ev_set_source(&event, port_out);
            snd_seq_ev_set_dest(&event, MidiOutDev[wDevID].addr.client, MidiOutDev[wDevID].addr.port);
	    
	    switch (evt & 0xF0) {
	    case MIDI_CMD_NOTE_OFF:
		snd_seq_ev_set_noteoff(&event, evt&0x0F, d1, d2);
		break;
	    case MIDI_CMD_NOTE_ON:
		snd_seq_ev_set_noteon(&event, evt&0x0F, d1, d2);
		break;
	    case MIDI_CMD_NOTE_PRESSURE:
		snd_seq_ev_set_keypress(&event, evt&0x0F, d1, d2);
		break;
	    case MIDI_CMD_CONTROL:
		snd_seq_ev_set_controller(&event, evt&0x0F, d1, d2);
		break;
	    case MIDI_CMD_BENDER:
		snd_seq_ev_set_pitchbend(&event, evt&0x0F, ((WORD)d2 << 7 | (WORD)d1) - 0x2000);
		break;
	    case MIDI_CMD_PGM_CHANGE:
		snd_seq_ev_set_pgmchange(&event, evt&0x0F, d1);
		break;
	    case MIDI_CMD_CHANNEL_PRESSURE:
		snd_seq_ev_set_chanpress(&event, evt&0x0F, d1);
		break;
	    case MIDI_CMD_COMMON_SYSEX:
		switch (evt & 0x0F) {
		case 0x00:	/* System Exclusive, don't do it on modData,
				 * should require modLongData*/
		case 0x01:	/* Undefined */
		case 0x04:	/* Undefined. */
		case 0x05:	/* Undefined. */
		case 0x07:	/* End of Exclusive. */
		case 0x09:	/* Undefined. */
		case 0x0D:	/* Undefined. */
		    handled = 0;
		    break;
		case 0x06:	/* Tune Request */
		case 0x08:	/* Timing Clock. */
		case 0x0A:	/* Start. */
		case 0x0B:	/* Continue */
		case 0x0C:	/* Stop */
		case 0x0E: 	/* Active Sensing. */
		    /* FIXME: Is this function suitable for these purposes
		       (and also Song Select and Song Position Pointer) */
	            snd_seq_ev_set_sysex(&event, 1, &evt);
		    break;
		case 0x0F: 	/* Reset */
				/* snd_seq_ev_set_sysex(&event, 1, &evt);
				   this other way may be better */
		    {
			BYTE reset_sysex_seq[] = {MIDI_CMD_COMMON_SYSEX, 0x7e, 0x7f, 0x09, 0x01, 0xf7};
			snd_seq_ev_set_sysex(&event, sizeof(reset_sysex_seq), reset_sysex_seq);
		    }
		    break;
		case 0x03:	/* Song Select. */
		    {
			BYTE buf[2];
			buf[0] = evt;
			buf[1] = d1;
			snd_seq_ev_set_sysex(&event, sizeof(buf), buf);
	            }
	            break;
		case 0x02:	/* Song Position Pointer. */
		    {
			BYTE buf[3];
			buf[0] = evt;
			buf[1] = d1;
			buf[2] = d2;
			snd_seq_ev_set_sysex(&event, sizeof(buf), buf);
	            }
		    break;
		}
		break;
	    }
	    if (handled)
                snd_seq_event_output_direct(midiSeq, &event);
	}
	break;
    default:
	WARN("Technology not supported (yet) %d !\n",
	     MidiOutDev[wDevID].caps.wTechnology);
	return MMSYSERR_NOTENABLED;
    }

    return MMSYSERR_NOERROR;
}
Example #9
0
/**
 * main
 * 
 * executable entry point
 */
INT __cdecl main( INT argc, CHAR **argv ) 
{
    /* local variables */
    int err;
    int i,j;
    WORD wVersionRequested;
    WSADATA wsaData;
    DWORD dwSocketError;

    SOCKET sock = INVALID_SOCKET;


    /* PAL initialization */
    if( (PAL_Initialize(argc, argv)) != 0 )
    {
        return( FAIL );
    }

    /* try to cleanup the winsock library -- should fail */
    /* since we haven't initialized it yet */
    err = WSACleanup();
    if( err == 0 )
    {
        Fail(   "WSACleanup call succeeded before call to WSAStartup\n" );
    }
    
    /* check the socket-specific error code */    
    dwSocketError = GetLastError();
    if( dwSocketError != WSANOTINITIALISED )
    {
        Fail(   "WSACleanup call does not return WSANOTINITIALISED "
                "before successful call to WSAStartup\n" );
    }


    /* initialize winsock version 2.2 */
    wVersionRequested = MAKEWORD( 2, 2 );
    
    for(i=0;i<5;i++)
    {
        err = WSAStartup( wVersionRequested, &wsaData );
        if( err != 0 )
        {            
            for(j=0;j<i;j++)
            {
                err = WSACleanup();
                if( err != 0 )
                {
                    /* check the socket-specific error code */    
                    dwSocketError = GetLastError();
                    Trace(   "WSACleanup call fails with error code %d\n",
                            dwSocketError ); 
                }
            }
            Fail( "Unexpected WSAStartup call failed with error code %d\n", 
                err ); 
        }

        /* Confirm that the WinSock DLL supports the specified version. */
        if( LOBYTE( wsaData.wVersion ) != 2 ||
            HIBYTE( wsaData.wVersion ) != 2 )
        {
            /* Tell the user that we could not find a usable winsock DLL. */
            Trace( "Requested winsock version unsupported, "
                    "returned version %d.%d\n",
                    LOBYTE( wsaData.wVersion ),
                    HIBYTE( wsaData.wVersion ) ); 

            for(j=0;j<=i;j++)
            {
                err = WSACleanup();
                if( err != 0 )
                {
                    /* check the socket-specific error code */    
                    dwSocketError = GetLastError();
                    Trace(   "WSACleanup call fails with error code %d\n",
                            dwSocketError ); 
                }
            }
            
            return( FAIL );
        }
    }

    for(i=0;i<4;i++)
    {
        /* try to cleanup the winsock library -- should succeed now */
        err = WSACleanup();
        if( err != 0 )
        {
            /* check the socket-specific error code */    
            dwSocketError = GetLastError();
            Fail(   "WSACleanup call fails with error code %d\n",
                    dwSocketError ); 
        }

        /* make a socket call before calling WSAStartup -- it should fail */                        
        sock = WSASocketA(  AF_INET,
                            SOCK_STREAM,
                            IPPROTO_TCP,
                            NULL,
                            0,
                            WSA_FLAG_OVERLAPPED
                        );

        if( sock == INVALID_SOCKET )
        {
            Trace("Unexpected failure: WSASocketA returned error\n");
            for(j=i;j<5;j++)
            {
                /* try to cleanup the winsock library -- should succeed now */
                err = WSACleanup();
                if( err != 0 )
                {
                    /* check the socket-specific error code */    
                    dwSocketError = GetLastError();
                    Trace(   "WSACleanup call fails with error code %d\n",
                            dwSocketError ); 
                }
            }
            Fail("");
        }
        if(closesocket( sock )==SOCKET_ERROR)
        {
            Trace("Unexpected failure: CloseSocket returned error\n");            
            for(j=i;j<5;j++)
            {
                /* try to cleanup the winsock library -- should succeed now */
                err = WSACleanup();
                if( err != 0 )
                {
                    /* check the socket-specific error code */    
                    dwSocketError = GetLastError();
                    Trace(   "WSACleanup call fails with error code %d\n",
                            dwSocketError ); 
                }
            }
            Fail("");
        }


    }

    /* try to cleanup the winsock library -- should succeed now */
    err = WSACleanup(); /* handle the last wsastartup */
    if( err != 0 )
    {
        /* check the socket-specific error code */    
        dwSocketError = GetLastError();
        Fail(   "WSACleanup call fails with error code %d\n",
                dwSocketError ); 
    }

    /* try a socket call to make sure the library's no longer initialized */
    /* make a socket call before calling WSAStartup -- it should fail */                        
    sock = WSASocketA(  AF_INET,
                        SOCK_STREAM,
                        IPPROTO_TCP,
                        NULL,
                        0,
                        WSA_FLAG_OVERLAPPED
                    );

    if( sock != INVALID_SOCKET )
    {
        closesocket( sock );
        Fail(   "Arbitrary socket call works after a successful "
                "call to WSACleanup\n" ); 
    }
    else
    {
        /* check the socket-specific error code */    
        dwSocketError = GetLastError();
        if( dwSocketError != WSANOTINITIALISED )
        {
            Fail(   "Arbitrary socket call does not return WSANOTINITIALISED "
                    "after successful call to WSACleanup\n" ); 
        }
    }
    

    /* PAL termination */
    PAL_Terminate();
    return PASS; 
}
Example #10
0
/**
* @brief  USBD_StdEPReq
*         Handle standard usb endpoint requests
* @param  pdev: USB OTG device instance
* @param  req: usb request
* @retval status
*/
USBD_Status  USBD_StdEPReq (USB_OTG_CORE_HANDLE  *pdev, USB_SETUP_REQ  *req)
{

  uint8_t   ep_addr;
  USBD_Status ret = USBD_OK;

  ep_addr  = LOBYTE(req->wIndex);

  switch (req->bRequest)
  {

  case USB_REQ_SET_FEATURE :

    switch (pdev->dev.device_status)
    {
    case USB_OTG_ADDRESSED:
      if ((ep_addr != 0x00) && (ep_addr != 0x80))
      {
        DCD_EP_Stall(pdev , ep_addr);
      }
      break;

    case USB_OTG_CONFIGURED:
      if (req->wValue == USB_FEATURE_EP_HALT)
      {
        if ((ep_addr != 0x00) && (ep_addr != 0x80))
        {
          DCD_EP_Stall(pdev , ep_addr);

        }
      }
      pdev->dev.class_cb->Setup (pdev, req);
      USBD_CtlSendStatus(pdev);

      break;

    default:
      USBD_CtlError(pdev , req);
      break;
    }
    break;

  case USB_REQ_CLEAR_FEATURE :

    switch (pdev->dev.device_status)
    {
    case USB_OTG_ADDRESSED:
      if ((ep_addr != 0x00) && (ep_addr != 0x80))
      {
        DCD_EP_Stall(pdev , ep_addr);
      }
      break;

    case USB_OTG_CONFIGURED:
      if (req->wValue == USB_FEATURE_EP_HALT)
      {
        if ((ep_addr != 0x00) && (ep_addr != 0x80))
        {
          DCD_EP_ClrStall(pdev , ep_addr);
          pdev->dev.class_cb->Setup (pdev, req);
        }
        USBD_CtlSendStatus(pdev);
      }
      break;

    default:
       USBD_CtlError(pdev , req);
      break;
    }
    break;

  case USB_REQ_GET_STATUS:
    switch (pdev->dev.device_status)
    {
    case USB_OTG_ADDRESSED:
      if ((ep_addr != 0x00) && (ep_addr != 0x80))
      {
        DCD_EP_Stall(pdev , ep_addr);
      }
      break;

    case USB_OTG_CONFIGURED:


      if ((ep_addr & 0x80)== 0x80)
      {
        if(pdev->dev.in_ep[ep_addr & 0x7F].is_stall)
        {
          USBD_ep_status = 0x0001;
        }
        else
        {
          USBD_ep_status = 0x0000;
        }
      }
      else if ((ep_addr & 0x80)== 0x00)
      {
        if(pdev->dev.out_ep[ep_addr].is_stall)
        {
          USBD_ep_status = 0x0001;
        }

        else
        {
          USBD_ep_status = 0x0000;
        }
      }
      USBD_CtlSendData (pdev,
                        (uint8_t *)&USBD_ep_status,
                        2);
      break;

    default:
       USBD_CtlError(pdev , req);
      break;
    }
    break;

  default:
    break;
  }
  return ret;
}
Example #11
0
static void
TestSuite_PrintJsonHeader (TestSuite *suite, /* IN */
                           FILE *stream)     /* IN */
{
#ifdef _WIN32
#  define INFO_BUFFER_SIZE 32767

   SYSTEM_INFO si;
   DWORD version = 0;
   DWORD major_version = 0;
   DWORD minor_version = 0;
   DWORD build = 0;

   GetSystemInfo(&si);
   version = GetVersion();

   major_version = (DWORD)(LOBYTE(LOWORD(version)));
   minor_version = (DWORD)(HIBYTE(LOWORD(version)));

   if (version < 0x80000000) {
      build = (DWORD)(HIWORD(version));
   }

   fprintf (stream,
            "{\n"
            "  \"host\": {\n"
            "    \"sysname\": \"Windows\",\n"
            "    \"release\": \"%ld.%ld (%ld)\",\n"
            "    \"machine\": \"%ld\",\n"
            "    \"memory\": {\n"
            "      \"pagesize\": %ld,\n"
            "      \"npages\": %d\n"
            "    }\n"
            "  },\n"
            "  \"options\": {\n"
            "    \"parallel\": \"%s\",\n"
            "    \"fork\": \"%s\"\n"
            "  },\n"
            "  \"tests\": [\n",
            major_version, minor_version, build,
            si.dwProcessorType,
            si.dwPageSize,
            0,
            (suite->flags & TEST_NOTHREADS) ? "false" : "true",
            (suite->flags & TEST_NOFORK) ? "false" : "true");
#else
   struct utsname u;
   uint64_t pagesize;
   uint64_t npages = 0;

   ASSERT (suite);

   if (uname (&u) == -1) {
      perror ("uname()");
      return;
   }

   pagesize = sysconf (_SC_PAGE_SIZE);

#  if defined(_SC_PHYS_PAGES)
   npages = sysconf (_SC_PHYS_PAGES);
#  endif

   fprintf (stream,
            "{\n"
            "  \"host\": {\n"
            "    \"sysname\": \"%s\",\n"
            "    \"release\": \"%s\",\n"
            "    \"machine\": \"%s\",\n"
            "    \"memory\": {\n"
            "      \"pagesize\": %"PRIu64",\n"
            "      \"npages\": %"PRIu64"\n"
            "    }\n"
            "  },\n"
            "  \"options\": {\n"
            "    \"parallel\": \"%s\",\n"
            "    \"fork\": \"%s\"\n"
            "  },\n"
            "  \"tests\": [\n",
            u.sysname,
            u.release,
            u.machine,
            pagesize,
            npages,
            (suite->flags & TEST_NOTHREADS) ? "false" : "true",
            (suite->flags & TEST_NOFORK) ? "false" : "true");
#endif

   fflush (stream);
}
Example #12
0
static JSValueRef keyDownCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
    if (argumentCount < 1)
        return JSValueMakeUndefined(context);

    static const JSStringRef lengthProperty = JSStringCreateWithUTF8CString("length");

    COMPtr<IWebFramePrivate> framePrivate;
    if (SUCCEEDED(frame->QueryInterface(&framePrivate)))
        framePrivate->layout();
    
    JSStringRef character = JSValueToStringCopy(context, arguments[0], exception);
    ASSERT(!*exception);
    int virtualKeyCode;
    int charCode = 0;
    int keyData = 1;
    bool needsShiftKeyModifier = false;
    if (JSStringIsEqualToUTF8CString(character, "leftArrow")) {
        virtualKeyCode = VK_LEFT;
        keyData += KF_EXTENDED << 16; // In this case, extended means "not keypad".
    } else if (JSStringIsEqualToUTF8CString(character, "rightArrow")) {
        virtualKeyCode = VK_RIGHT;
        keyData += KF_EXTENDED << 16;
    } else if (JSStringIsEqualToUTF8CString(character, "upArrow")) {
        virtualKeyCode = VK_UP;
        keyData += KF_EXTENDED << 16;
    } else if (JSStringIsEqualToUTF8CString(character, "downArrow")) {
        virtualKeyCode = VK_DOWN;
        keyData += KF_EXTENDED << 16;
    } else if (JSStringIsEqualToUTF8CString(character, "pageUp"))
        virtualKeyCode = VK_PRIOR;
    else if (JSStringIsEqualToUTF8CString(character, "pageDown"))
        virtualKeyCode = VK_NEXT;
    else if (JSStringIsEqualToUTF8CString(character, "home"))
        virtualKeyCode = VK_HOME;
    else if (JSStringIsEqualToUTF8CString(character, "end"))
        virtualKeyCode = VK_END;
    else if (JSStringIsEqualToUTF8CString(character, "insert"))
        virtualKeyCode = VK_INSERT;
    else if (JSStringIsEqualToUTF8CString(character, "delete"))
        virtualKeyCode = VK_DELETE;
    else if (JSStringIsEqualToUTF8CString(character, "printScreen"))
        virtualKeyCode = VK_SNAPSHOT;
    else if (JSStringIsEqualToUTF8CString(character, "menu"))
        virtualKeyCode = VK_APPS;
    else if (JSStringIsEqualToUTF8CString(character, "leftControl"))
        virtualKeyCode = VK_LCONTROL;
    else if (JSStringIsEqualToUTF8CString(character, "leftShift"))
        virtualKeyCode = VK_LSHIFT;
    else if (JSStringIsEqualToUTF8CString(character, "leftAlt"))
        virtualKeyCode = VK_LMENU;
    else if (JSStringIsEqualToUTF8CString(character, "rightControl"))
        virtualKeyCode = VK_RCONTROL;
    else if (JSStringIsEqualToUTF8CString(character, "rightShift"))
        virtualKeyCode = VK_RSHIFT;
    else if (JSStringIsEqualToUTF8CString(character, "rightAlt"))
        virtualKeyCode = VK_RMENU;
    else {
        charCode = JSStringGetCharactersPtr(character)[0];
        virtualKeyCode = LOBYTE(VkKeyScan(charCode));
        if (WTF::isASCIIUpper(charCode))
            needsShiftKeyModifier = true;
    }
    JSStringRelease(character);

    BYTE keyState[256];
    if (argumentCount > 1 || needsShiftKeyModifier) {
        ::GetKeyboardState(keyState);

        BYTE newKeyState[256];
        memcpy(newKeyState, keyState, sizeof(keyState));

        if (needsShiftKeyModifier)
            newKeyState[VK_SHIFT] = 0x80;

        if (argumentCount > 1) {
            JSObjectRef modifiersArray = JSValueToObject(context, arguments[1], 0);
            if (modifiersArray) {
                int modifiersCount = JSValueToNumber(context, JSObjectGetProperty(context, modifiersArray, lengthProperty, 0), 0);
                for (int i = 0; i < modifiersCount; ++i) {
                    JSValueRef value = JSObjectGetPropertyAtIndex(context, modifiersArray, i, 0);
                    JSStringRef string = JSValueToStringCopy(context, value, 0);
                    if (JSStringIsEqualToUTF8CString(string, "ctrlKey") || JSStringIsEqualToUTF8CString(string, "addSelectionKey"))
                        newKeyState[VK_CONTROL] = 0x80;
                    else if (JSStringIsEqualToUTF8CString(string, "shiftKey") || JSStringIsEqualToUTF8CString(string, "rangeSelectionKey"))
                        newKeyState[VK_SHIFT] = 0x80;
                    else if (JSStringIsEqualToUTF8CString(string, "altKey"))
                        newKeyState[VK_MENU] = 0x80;

                    JSStringRelease(string);
                }
            }
        }

        ::SetKeyboardState(newKeyState);
    }

    MSG msg = makeMsg(webViewWindow, (::GetKeyState(VK_MENU) & 0x8000) ? WM_SYSKEYDOWN : WM_KEYDOWN, virtualKeyCode, keyData);
    if (virtualKeyCode != 255)
        dispatchMessage(&msg);
    else {
        // For characters that do not exist in the active keyboard layout,
        // ::Translate will not work, so we post an WM_CHAR event ourselves.
        ::PostMessage(webViewWindow, WM_CHAR, charCode, 0);
    }

    // Tests expect that all messages are processed by the time keyDown() returns.
    if (::PeekMessage(&msg, webViewWindow, WM_CHAR, WM_CHAR, PM_REMOVE) || ::PeekMessage(&msg, webViewWindow, WM_SYSCHAR, WM_SYSCHAR, PM_REMOVE))
        ::DispatchMessage(&msg);

    MSG msgUp = makeMsg(webViewWindow, (::GetKeyState(VK_MENU) & 0x8000) ? WM_SYSKEYUP : WM_KEYUP, virtualKeyCode, keyData);
    ::DispatchMessage(&msgUp);

    if (argumentCount > 1 || needsShiftKeyModifier)
        ::SetKeyboardState(keyState);

    return JSValueMakeUndefined(context);
}
Example #13
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2,2);
    WSADATA WsaData;
    int err;
    int socketID;
    struct sockaddr_in mySockaddr;

    /*set the backlog number*/
    const int BacklogNumber = 10;

    /*Initialize the PAL environment*/
    err = PAL_Initialize(argc, argv);
    if(0 != err)
    {
        return FAIL;
    }

    /*initialize to use winsock2.dll*/
    err = WSAStartup(VersionRequested,&WsaData);
    if(err != 0)
    {
        Fail("\nFailed to find a usable WinSock DLL!\n");
    }

    /*Confirm that the WinSock DLL supports 2.2.*/
    if(LOBYTE( WsaData.wVersion ) != 2 ||
            HIBYTE( WsaData.wVersion ) != 2)
    {
        Trace("\nFailed to find a usable WinSock DLL!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    /*create a datagram socket in AF_INET domain*/
    socketID = socket(AF_INET,SOCK_DGRAM,0);
    if(INVALID_SOCKET == socketID)
    {
        Trace("\nFailed to call socket API to create a stream socket!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    /*prepare the sockaddr structure*/
    mySockaddr.sin_family = AF_INET;
    mySockaddr.sin_port = 0;
    mySockaddr.sin_addr.S_un.S_addr = INADDR_ANY;
    memset( &(mySockaddr.sin_zero), 0, 8);

    /*bind local address to a socket*/
    err = bind(socketID,(struct sockaddr *)&mySockaddr,sizeof(struct sockaddr));
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call bind API to bind a socket with "
                "local address!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    /*to setup the backlog number for a datagram socket*/
    err = listen(socketID,BacklogNumber);
    if(WSAEOPNOTSUPP != GetLastError() || SOCKET_ERROR != err)
    {
        Trace("\nFailed to call listen API for a negative test, "
                "setup backlog number for a datagram socket!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    err = closesocket(socketID);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call closesocket API!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    err = WSACleanup();
    if(SOCKET_ERROR == err)
    {
        Fail("\nFailed to call WSACleanup API!\n");
    }

    PAL_Terminate();
    return PASS;
}
CCherryNotificationDialog::CCherryNotificationDialog()
:
m_bWinXPOrLater(IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0))
{
	Initialize();
}
Example #15
0
// Listen to incoming TCP requests. Supply the port you want the server to listen on
int listen_tcp(int host_port) {

	// adapted from: http://www.tidytutorials.com/2009/12/c-winsock-example-using-client-server.html

	int err = 0;

    // Initialize socket support WINDOWS ONLY!
    unsigned short wVersionRequested;
    WSADATA wsaData;
    wVersionRequested = MAKEWORD(2, 2);
    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0 || (LOBYTE(wsaData.wVersion) != 2 ||
            HIBYTE(wsaData.wVersion) != 2)) {
        fprintf(stderr, "Could not find useable sock dll %d\n", WSAGetLastError());
        goto FINISH;
    }

    // Initialize sockets and set any options
    int hsock;
    int* p_int ;
    hsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (hsock == -1) {
        printf("Error initializing socket %d\n", WSAGetLastError());
        goto FINISH;
    }
    
    p_int = (int*)malloc(sizeof(int));
    *p_int = 1;
    if ((setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1)||
        (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1)) {
        printf("Error setting options %d\n", WSAGetLastError());
        free(p_int);
        goto FINISH;
    }
    free(p_int);

    // Bind and listen
    struct sockaddr_in my_addr;

    my_addr.sin_family = AF_INET ;
    my_addr.sin_port = htons(host_port);
    
    memset(&(my_addr.sin_zero), 0, 8);
    my_addr.sin_addr.s_addr = INADDR_ANY ;
    
    if (bind(hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) != 0) {
        fprintf(stderr,"Error binding to socket, make sure nothing else is listening on port %d\n", WSAGetLastError());
        goto FINISH;
    }
    if (listen(hsock, 10) != 0) {
        fprintf(stderr, "Error listening %d\n", WSAGetLastError());
        goto FINISH;
    }
    
	// wait for connections

    int* csock;
    sockaddr_in sadr;
    int addr_size = sizeof(SOCKADDR);
    
    while (true) {
        printf("Listening for a TCP connection on port %d\n", host_port);
        csock = (int*)malloc(sizeof(int));
        
        if ((*csock = accept(hsock, (SOCKADDR*)&sadr, &addr_size)) != INVALID_SOCKET) {
            printf("Connection attempt from %s\n", inet_ntoa(sadr.sin_addr));

            err = HandleTCPConnection(csock);
			
			fprintf(stderr, "Result: %d\n", err);
        }
        else{
            fprintf(stderr, "Error accepting %d\n",WSAGetLastError());
        }
	}

FINISH:
	return err;
}
Example #16
0
/* =========================== */
int main(int argc,char *argv[])
{
   unsigned short       port;
   int                  result;
   int                  err;
   SOCKET               masterSock;
   SOCKET               clientSock;
   em_workspace_t       *wrk;
   struct sockaddr_in   servAddr;
   int                  i;
   WORD                 wVersionRequested;
   WSADATA              wsaData;
   int                  clientAddrLen;
   struct sockaddr      clientAddr;

   fprintf(stdout,"Embedded Web Server - Windows 95 : %s\n",__TIMESTAMP__);
   fprintf(stdout,"Copyright (c) 1995-1996 David M. Howard\n");

   port = w95t_server_port;

   /* initialize printf */
   printf_init();

   /* =============================================== */
   /* initialize winsock library                      */
   /* =============================================== */

   wVersionRequested = MAKEWORD(1, 1);

   err = WSAStartup(wVersionRequested, &wsaData);
   if (err != 0) {
      fprintf(stderr,"Can't initialize winsock lib\n");
      exit(1);
   }

   /* Confirm that the Windows Sockets DLL supports 1.1.*/
   /* Note that if the DLL supports versions greater */
   /* than 1.1 in addition to 1.1, it will still return */
   /* 1.1 in wVersion since that is the version we */
   /* requested. */

   if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) {
      /* Tell the user that we couldn't find a useable */
      /* winsock.dll. */
      WSACleanup();
      fprintf(stderr,"Winsock doesn't support version 1.1\n");
      exit(1);
   }

   ews_printf("Winsock Initialized OK\n");

   /* =============================================== */
   /* The Windows Sockets DLL is acceptable. Proceed. */
   /* =============================================== */

   /* Create a socket and bind address, listen for incoming connections */
   masterSock = socket( PF_INET, SOCK_STREAM, 0 );
   if ( masterSock == INVALID_SOCKET ) {
      ews_printf("socket(..) failed\n");
      exit(1);
   }

   /*lint -e740 unusual pointer cast */
   memset((char *) &servAddr, 0, sizeof servAddr );
   servAddr.sin_family      = AF_INET;
   servAddr.sin_addr.s_addr = htonl( INADDR_ANY );
   servAddr.sin_port        = htons( port );
   result = bind( masterSock, ( struct sockaddr * ) &servAddr, sizeof servAddr );
   if ( result == -1 ) {
      ews_printf("bind(..) failed\n");
      exit(1);
   }

   /*lint _e740 */

   result = listen( masterSock, 3 );
   if ( result == -1 ) {
      ews_printf("listen(..) failed\n");
      exit(1);
   }

   ews_printf("masterSock listening on port %hu\n",port);

   /* ================================== */
   /* create the client connection queue */
   /* ================================== */
   thread_sockq = socket_qinit(NUMBER_OF_SERVER_TASKS);

   /* for each vrtx connection thread */
   for(i=0;i<NUMBER_OF_SERVER_TASKS;i++) {
      /* initialize a workspace  */
      wrk = &w95t_workspace[i];

      /* clear it to all 0's to start */
      memset(wrk,0,sizeof(em_workspace_t));

      /* SOCKET IO FUNCTIONS */
      wrk->system.p           = &w95t_dresp[i];
      wrk->system.read        = w95t_Read;
      wrk->system.write       = w95t_Write;
      wrk->system.open        = w95t_Open;
      wrk->system.close       = w95t_Close;
      wrk->system.exit        = w95t_Exit;
      wrk->system.gmt         = w95t_GMT;
      wrk->system.pagebin     = app_binurl;

      /* spawn the thread and pass it the workspace pointer */
      _beginthread(w95t_server_thread,0,wrk);
   }

   /* all threads are spawned */
   /* loop, waiting for connections */
   /* when a connection is received, enqueue it for the server threads */
   for(;;) {
      /* specify the max length of the address structure and accept the
      next connection.  clientAddrLen is passed as a pointer as it is
      updated by the accept call.
      retry accept until it works
      */
      ews_printf("Accept : masterSock = %ld\n",masterSock);

      clientAddrLen = sizeof (clientAddr);
      clientSock = accept( masterSock, &clientAddr, &clientAddrLen );


      /* if accept call fails */
      if ( clientSock == INVALID_SOCKET ) {
         /* get winsock error */
         err = WSAGetLastError();

         /* print it to error output */
         ews_printf("Accept failed : %d\n",err);

         /* quit */
         break;
      }

      ews_printf("Connect : clientSock = %ld\n",clientSock);

      /* client socket is accepted  */
      /* enqueue it for the servers */
      /* return (long)clientSock;   */
      socket_qsend(thread_sockq,clientSock);
   }

   return 0;
}
DWORD WINAPI RetranmitRequest(LPVOID lpParameter){
	/*
	winsock³õʼ»¯
	*/
	WORD wVersionRequested; 
	WSADATA wsaData; 
	int err; 
	wVersionRequested = MAKEWORD(1,1); 
	err = WSAStartup(wVersionRequested,&wsaData); 
	if ( err != 0 ) { 
		return -1; 
	} 

	if ( LOBYTE( wsaData.wVersion ) != 1 || 
		HIBYTE( wsaData.wVersion ) != 1) { 
			WSACleanup( ); 
			return -1; 
	}

	SOCKADDR_IN server_retran_addr;
	SOCKET retrans_socket;    
	retrans_socket=socket(AF_INET, SOCK_DGRAM,0);
	server_retran_addr.sin_family = AF_INET;
	server_retran_addr.sin_port = htons(retranport); 
	server_retran_addr.sin_addr.s_addr = inet_addr(ServIP);

	while(g_retran_ruuning){
		std::vector<RetransUnit> RequestVector = g_retrans_treator.getReTransList(RTT);
		//printf("out get size:%d\n",RequestVector.size());
		char requestcommand[1500];

		int counter = 0;
		int packet_pos = 0;
		int packetsize = 0;

		memcpy(requestcommand+packetsize,&userRandomId,sizeof(userRandomId));
		packetsize = packetsize+sizeof(userRandomId);


		while (true){
			if (isStop)
			{
				threadStop[3] = 1;
				return 0;
			}
			if(packet_pos==RequestVector.size())break;

			long id = RequestVector[packet_pos].top_id;
			memcpy(requestcommand+packetsize,&id,sizeof(long));
			packetsize = packetsize+sizeof(id);

			int sqnum=RequestVector[packet_pos].self_sqnum;
			memcpy(requestcommand+packetsize,&sqnum,sizeof(sqnum));
			packetsize=packetsize+sizeof(sqnum);

			int timestmp=RequestVector[packet_pos].self_timestmp;
			memcpy(requestcommand+packetsize,&timestmp,sizeof(timestmp));
			packetsize=packetsize+sizeof(timestmp);

			packet_pos++;
			counter++;
			if(counter == requestsize){

				int re = sendto(retrans_socket,requestcommand,packetsize,0,(SOCKADDR*)&server_retran_addr,sizeof(SOCKADDR));
				//printf("send retrans request %d %d\n",sqnum,re);
				packetsize = 0;
				counter = 0;
				memcpy(requestcommand+packetsize,&userRandomId,sizeof(userRandomId));
				packetsize = packetsize+sizeof(userRandomId);
				if(packet_pos==RequestVector.size()){
					break;
				}
			}
			if(packet_pos==RequestVector.size()){
				if(counter>0){
					//	printf("send retrans request %d size:%d\n ",sqnum,RequestVector.size());
					sendto(retrans_socket,requestcommand,packetsize,0,(SOCKADDR*)&server_retran_addr,sizeof(SOCKADDR));
					packetsize = 0;
					counter = 0;
				}
				break;
			}
		}
		Sleep(10);
	}

	return 0;

}
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2, 2);
    WSADATA WsaData;
    SOCKET aSocket;
    u_long argp = 1;/*set the non-blocking enable flag*/
    int err;
    int socketID;
    struct sockaddr_in mySockaddr;
    struct sockaddr mySocketaddrConnect;
    int nSocketaddrLength;
    int nBacklogNumber = 1;
    struct timeval waitTime;
    fd_set readFds;
    int socketFds;


    /*Initialize the PAL environment*/
    err = PAL_Initialize(argc, argv);
    if(0 != err)
    {
        return FAIL;
    }

    /*initialize to use winsock2.dll*/
    err = WSAStartup(VersionRequested,&WsaData);
    if(err != 0)
    {
        Fail("\nFailed to find a usable WinSock DLL!\n");
    }

    /* Confirm that the WinSock DLL supports 2.2.*/
    if(LOBYTE( WsaData.wVersion ) != 2 ||
            HIBYTE( WsaData.wVersion ) != 2)
    {
        Trace("\nFailed to find a usable WinSock DLL!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }
 
    /*create a stream socket in AF_INET domain*/
    socketID = socket(AF_INET, SOCK_STREAM, 0);
    if(INVALID_SOCKET == socketID)
    {
        Trace("\nFailed to call socket API to create a stream socket!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    // Wait for 5 seconds for the client to connect.
    waitTime.tv_sec = 5L;
    waitTime.tv_usec = 0L;

    /*initialize the readable socket set*/
    FD_ZERO(&readFds);

    /*set the socket as non-blocking */
    err = ioctlsocket(socketID,FIONBIO,&argp);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call ioctlsocket API to set up a "
                "non-block socket!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }


    /*prepare the sockaddr_in structure*/
    mySockaddr.sin_family = AF_INET;
    mySockaddr.sin_port = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    memset( &(mySockaddr.sin_zero), 0, 8);

    /*bind the local address to the created socket*/
    err = bind(socketID,(struct sockaddr *)&mySockaddr,
        sizeof(struct sockaddr));
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call bind API to bind socket with local address!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }


    /*to setup the backlog number for a created socket*/
    err = listen(socketID,nBacklogNumber);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call listen API to setup backlog number!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    /*add socket to readable socket set*/
    FD_SET(socketID, &readFds);
    /*mornitor the readable socket set*/
    socketFds = select(0, &readFds, NULL, NULL, &waitTime);

    if(SOCKET_ERROR == socketFds)
    {
        Trace("\nFailed to call select API to monitor socket set!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Fail("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }
    if(0 == socketFds)
    {
        Trace("\nSelect waiting time is out!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail(""); 
    }


    nSocketaddrLength = sizeof(mySocketaddrConnect);
    /*accept a request from client*/
    aSocket = accept(socketID,(struct sockaddr*)&mySocketaddrConnect,
            &nSocketaddrLength);
    if(INVALID_SOCKET == aSocket)
    {
        Trace("\nFailed to call accept API!\n");
        err = closesocket(socketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API!\n");
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }
        
    err = closesocket(aSocket);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call closesocket API!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    err = closesocket(socketID);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call closesocket API!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    err = WSACleanup();
    if(SOCKET_ERROR == err)
    {
        Fail("\nFailed to call WSACleanup API!\n");
    }

    PAL_Terminate();
    return PASS;
}
Example #19
0
BOOLEAN
PauseGame (void)
{
	RECT r;
	STAMP s;
	BOOLEAN ClockActive;
	CONTEXT OldContext;
	FRAME F;
	HOT_SPOT OldHot;

	if (ActivityFrame == 0
			|| (GLOBAL (CurrentActivity) & (CHECK_ABORT | CHECK_PAUSE))
			|| (LastActivity & (CHECK_LOAD | CHECK_RESTART)))
		return (FALSE);
		
	GLOBAL (CurrentActivity) |= CHECK_PAUSE;

	ClockActive = (BOOLEAN)(
			LOBYTE (GLOBAL (CurrentActivity)) != SUPER_MELEE
			&& GameClockRunning ()
			);
	if (ClockActive)
		SuspendGameClock ();
	else if (CommData.ConversationPhrases && PlayingTrack ())
		PauseTrack ();

	SetSemaphore (GraphicsSem);
	OldContext = SetContext (ScreenContext);
	OldHot = SetFrameHot (Screen, MAKE_HOT_SPOT (0, 0));

	GetFrameRect (ActivityFrame, &r);
	r.corner.x = (SCREEN_WIDTH - r.extent.width) >> 1;
	r.corner.y = (SCREEN_HEIGHT - r.extent.height) >> 1;
	s.origin = r.corner;
	s.frame = ActivityFrame;
	F = CaptureDrawable (LoadDisplayPixmap (&r, (FRAME)0));
	DrawStamp (&s);

	FlushGraphics ();

	{
		BYTE scan;

		scan = KBDToUNICODE (SK_F1);
		while (KeyDown (scan))
			TaskSwitch ();
	}

	FlushInput ();
	while (KeyHit () != SK_F1)
		TaskSwitch ();

	s.frame = F;
	DrawStamp (&s);
	DestroyDrawable (ReleaseDrawable (s.frame));

	SetFrameHot (Screen, OldHot);
	SetContext (OldContext);

	WaitForNoInput (ONE_SECOND / 4);
	FlushInput ();
	ClearSemaphore (GraphicsSem);

	if (ClockActive)
		ResumeGameClock ();
	else if (CommData.ConversationPhrases && PlayingTrack ())
		ResumeTrack ();

	TaskSwitch ();
	GLOBAL (CurrentActivity) &= ~CHECK_PAUSE;
	return (TRUE);
}
Example #20
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2, 2);
    WSADATA WsaData;
    int err;
    int SocketID;
    int size;
    BOOL bValue;

    /*Initialize the PAL environment*/
    err = PAL_Initialize(argc, argv);
    if(0 != err)
    {
        return FAIL;
    }

    /*initialize to use winsock2.dll*/
    err = WSAStartup(VersionRequested, &WsaData);
    if(err != 0)
    {
        Fail("\nFailed to find a usable WinSock DLL!\n");
    }

    /*Confirm that the WinSock DLL supports 2.2.*/
    if(LOBYTE( WsaData.wVersion ) != 2 ||
            HIBYTE( WsaData.wVersion ) != 2)
    {
        Trace("\nFailed to find a usable WinSock DLL!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API, error code=%d!\n",
                GetLastError());
        }
        Fail("");
    }

    /*create a stream socket in AF_INET domain*/
    SocketID = socket(AF_INET, SOCK_STREAM, 0);
    if(INVALID_SOCKET == SocketID)
    {
        Trace("\nFailed to create the stream socket!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API, error code=%d!\n",
                GetLastError());
        }
        Fail("");
    }

    size =sizeof(BOOL);
    bValue = TRUE;
    
    /*pass an invalid socket option to generate an error*/
    err = setsockopt(SocketID, SOL_SOCKET, 0x1020,
                (char *)&bValue, size);

    if(WSAENOPROTOOPT != GetLastError() || SOCKET_ERROR != err)
    {  
        Trace("\nFailed to call Setsockopt API for negative test, "
                "call setsockopt by passing a not supported socket option, "
                "an error WSAENOPROTOOPT is expected, but no error or no "
                "expected error is detected , "
                "error code = %u\n", GetLastError());

        err = closesocket(SocketID);
        if(SOCKET_ERROR == err)
        {    
            Trace("\nFailed to call closesocket API, error code=%d!\n",
                GetLastError());
        }
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API, error code=%d!\n",
                GetLastError());
        }
        Fail("");
    }

    err = closesocket(SocketID);
    if(SOCKET_ERROR == err)
    {
        Trace("\nFailed to call closesocket API, error code=%d!\n",
                GetLastError());
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API, error code=%d!\n",
                GetLastError());
        }
        Fail("");
    }
    err = WSACleanup();
    if(SOCKET_ERROR == err)
    {
        Fail("\nFailed to call WSACleanup API, error code=%d!\n",
                GetLastError());
    }

    PAL_Terminate();
    return PASS;
}
Example #21
0
void CTuConfigTUDlg::UpdateGrid(void)
{
	CString str;
	CStringArray aOptions;
	m_Grid.DeleteNonFixedRows();
	
	for(int i = 0; i < m_TuArray.GetSize(); i++)
	{
		int nIndex = m_Grid.InsertRow(NULL);
		int col=0;

		str.Format("%d",i+1);
		m_Grid.SetItemText(nIndex,col++,str);

		m_Grid.SetItemText(nIndex,col++,m_TuArray[i].strCOMMENT);
				
		if(m_nProcType != PROT_SPA)
		{
			switch(m_nProcType )
			{
				case PROT_MODBUS:
					{
						aOptions.Add("Внешнее устройство ТУ");
						aOptions.Add("Модули МКСУ");	
						aOptions.Add("ИПЦ");	
						aOptions.Add("ТУ одна комманда");	
						aOptions.Add("ТУ Овен");	
						break;
					}
				case PROT_IEC101: 
				case PROT_IEC104: 
					{
						aOptions.Add("Одноступенчатое ТУ(IEC101)");
						aOptions.Add("Двуступенчатое ТУ(IEC101)");	
						break;
					}
				case PROT_IEC103: 
					{
						aOptions.Add("Одноступенчатое ТУ(IEC101)");						
						break;
					}
				case PROT_MODBUSTCP: 
			{
						aOptions.Add("Одноступенчатое ТУ");	
						aOptions.Add("Модули МКСУ");
						aOptions.Add("ИПЦ");
						aOptions.Add("резерв");
						aOptions.Add("ТУ Овен");
						break;
					}
			}
			/*if(m_nProcType == PROT_MODBUS)
			{
				aOptions.Add("Внутр.модули ТУ(MODBUS)");
				aOptions.Add("Внешнее устройство ТУ");			
			}
			if((m_nProcType == PROT_IEC101)||(m_nProcType == PROT_IEC104))
			{
				aOptions.Add("Одноступенчатое ТУ(IEC101)");
				aOptions.Add("Двуступенчатое ТУ(IEC101)");			
			}
			if(m_nProcType == PROT_IEC103)
				aOptions.Add("Одноступенчатое ТУ(IEC103)");*/
			m_Grid.SetCellType(nIndex,col, RUNTIME_CLASS(CGridCellCombo));
			CGridCellCombo *pCell = (CGridCellCombo*) m_Grid.GetCell(nIndex,col);		
			pCell->SetOptions(aOptions);		
			pCell->SetStyle(CBS_DROPDOWN); //CBS_DROPDOWN, CBS_DROPDOWNLIST, CBS_SIMPLE			
			str.Format("%d",m_TuArray[i].TYPE_PRIBOR);

			if((m_TuArray[i].TYPE_PRIBOR < 0)||(m_TuArray[i].TYPE_PRIBOR >4))
				m_Grid.SetItemText(nIndex,col++, str);
			else
			{
				switch(m_nProcType )
				{
					case PROT_MODBUS:
					case PROT_MODBUSTCP: 
						{
							pCell->SetCurSel(m_TuArray[i].TYPE_PRIBOR);
							break;
						}
					case PROT_IEC101: 
					case PROT_IEC104: 					
					case PROT_IEC103: 
						{
							pCell->SetCurSel(m_TuArray[i].TYPE_PRIBOR-2);				
							break;
						}
				}
				col++;
			}
			aOptions.RemoveAll();
			/*if(m_TuArray[i].TYPE_PRIBOR == 1)
				m_Grid.SetItemText(nIndex,col++, aOptions[0]);
			if(m_TuArray[i].TYPE_PRIBOR == 2)
			{
				if(m_nProcType == PROT_MODBUS)
					m_Grid.SetItemText(nIndex,col++, aOptions[1]);
				else
					m_Grid.SetItemText(nIndex,col++, aOptions[0]);
			}					
			if(m_TuArray[i].TYPE_PRIBOR == 3)
				m_Grid.SetItemText(nIndex,col++, aOptions[1]);	*/							
		}
		else
			col++;

		str.Format("%d",m_TuArray[i].ADRESS);
		m_Grid.SetItemText(nIndex,col,str);
		m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

		if(m_nProcType == PROT_MODBUS)
		{
			aOptions.Add("Force Single Coil(5)");
			aOptions.Add("Preset Single Reg(6)");
		}
		if((m_nProcType == PROT_IEC101)||(m_nProcType == PROT_IEC104))
		{
			aOptions.Add("C_SC_NA(45)");
			aOptions.Add("C_DC_NA(46)");
		}
		if(m_nProcType == PROT_IEC103)
		{
			aOptions.Add("DCO(20)");
		}
		if(m_nProcType == PROT_SPA)
		{
			aOptions.Add("1-I-input data");
			aOptions.Add("2-O-output data");	
			aOptions.Add("3-S-setting value");
			aOptions.Add("4-V-variable");
			aOptions.Add("5-M-memory data");
			aOptions.Add("6-C-condition of slave status");
			aOptions.Add("7-F-slave identification");//0		
			aOptions.Add("8-T-time");
			aOptions.Add("9-D-date and time");
			aOptions.Add("10-last events");
			aOptions.Add("11-B-backup events");
			aOptions.Add("12-A-alarms valid");
		}
		m_Grid.SetCellType(nIndex,col, RUNTIME_CLASS(CGridCellCombo));
		CGridCellCombo* pCell = (CGridCellCombo*) m_Grid.GetCell(nIndex,col);		
		pCell->SetOptions(aOptions);
		pCell->SetStyle(CBS_DROPDOWN); //CBS_DROPDOWN, CBS_DROPDOWNLIST, CBS_SIMPLE			
		str.Format("%d",m_TuArray[i].FUNCTION);
		m_Grid.SetItemText(nIndex,col, str);
		if(m_nProcType != PROT_SPA)
		{
			if(m_TuArray[i].FUNCTION == 5)
				m_Grid.SetItemText(nIndex,col++, aOptions[0]);
			if(m_TuArray[i].FUNCTION == 6)
				m_Grid.SetItemText(nIndex,col++, aOptions[1]);
			if(m_TuArray[i].FUNCTION == 45)
				m_Grid.SetItemText(nIndex,col++, aOptions[0]);
			if(m_TuArray[i].FUNCTION == 46)
				m_Grid.SetItemText(nIndex,col++, aOptions[1]);
			if(m_TuArray[i].FUNCTION == 20)
				m_Grid.SetItemText(nIndex,col++, aOptions[0]);
			if((m_TuArray[i].FUNCTION != 45)&&(m_TuArray[i].FUNCTION != 46)
				&&(m_TuArray[i].FUNCTION != 20)&&(m_TuArray[i].FUNCTION != 5)
				&&(m_TuArray[i].FUNCTION != 6))
				m_Grid.SetItemText(nIndex,col++, str);		
		}
		else//PROT_SPA
		{
			pCell->SetCurSel(m_TuArray[i].FUNCTION-1);
			col++;
		}
		aOptions.RemoveAll();

		if(m_nProcType == PROT_SPA)
		{
			str.Format("%d",m_TuArray[i].REGTU_ON);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].REGTU_OFF);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].DATATU_ON);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].DATATU_OFF);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].IEC_ASDU);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));
		}
		if(m_nProcType == PROT_MODBUS)
		{
			str.Format("%d",m_TuArray[i].REGTU_ON);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].REGTU_OFF);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].DATATU_ON);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].DATATU_OFF);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].TU_CLOSER);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].WAIT_RESP_TU);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].TIMER_SEL_EXEC);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));
		}
		if((m_nProcType == PROT_IEC101)||(m_nProcType == PROT_IEC104))
		{
			str.Format("%d",m_TuArray[i].REGTU_ON);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].REGTU_OFF);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].DATATU_ON);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].DATATU_OFF);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].TU_CLOSER);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].WAIT_RESP_TU);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].ADDRESS_TS);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].TS_ON);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].TS_OFF);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].ADDRESS_DAMAGE_TU);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].MASKA_DAMAGE_TU);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].IEC_ASDU);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			m_Grid.SetCellType(nIndex,col,RUNTIME_CLASS(CGridCellCheck));
			CGridCellCheck *pCell2 = (CGridCellCheck*) m_Grid.GetCell(nIndex, col++);									
			pCell2->SetStrings("Да","Нет");		
			if(m_TuArray[i].TU_ACT_TRM_ENABLE == 0)
				pCell2->SetCheck(FALSE);
			else
				pCell2->SetCheck(TRUE);

			str.Format("%d",m_TuArray[i].TIMER_SEL_EXEC);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].TIMER_ACT_TRM);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

		}
		if(m_nProcType == PROT_IEC103)
		{
			str.Format("%d",HIBYTE(m_TuArray[i].REGTU_ON));
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",LOBYTE(m_TuArray[i].REGTU_ON));
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",HIBYTE(m_TuArray[i].REGTU_OFF));
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",LOBYTE(m_TuArray[i].REGTU_OFF));
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].DATATU_ON);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].DATATU_OFF);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].TU_CLOSER);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].WAIT_RESP_TU);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].ADDRESS_TS);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].TS_ON);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].TS_OFF);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].ADDRESS_DAMAGE_TU);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].MASKA_DAMAGE_TU);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].IEC_ASDU);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));

			str.Format("%d",m_TuArray[i].TIMER_SEL_EXEC);
			m_Grid.SetItemText(nIndex,col,str);
			m_Grid.SetCellType(nIndex,col++,RUNTIME_CLASS(CGridCellNumeric));
		}		
	}
	//m_GridData.Auto
	m_Grid.AutoSizeRows();
	//m_GridData.AutoSizeColumn(0);
	m_Grid.Refresh();
}
/**
* @brief  USBD_StdEPReq
*         Handle standard usb endpoint requests
* @param  pdev: device instance
* @param  req: usb request
* @retval status
*/
USBD_StatusTypeDef  USBD_StdEPReq (USBD_HandleTypeDef *pdev , USBD_SetupReqTypedef  *req)
{
  
  uint8_t   ep_addr;
  USBD_StatusTypeDef ret = USBD_OK; 
  USBD_EndpointTypeDef   *pep;
  ep_addr  = LOBYTE(req->wIndex);   
  
  switch (req->bRequest) 
  {
    
  case USB_REQ_SET_FEATURE :
    
    switch (pdev->dev_state) 
    {
    case USBD_STATE_ADDRESSED:          
      if ((ep_addr != 0x00) && (ep_addr != 0x80)) 
      {
        USBD_LL_StallEP(pdev , ep_addr);
      }
      break;	
      
    case USBD_STATE_CONFIGURED:   
      if (req->wValue == USB_FEATURE_EP_HALT)
      {
        if ((ep_addr != 0x00) && (ep_addr != 0x80)) 
        { 
          USBD_LL_StallEP(pdev , ep_addr);
          
        }
      }
      pdev->pClass->Setup (pdev, req);   
      USBD_CtlSendStatus(pdev);
      
      break;
      
    default:                         
      USBD_CtlError(pdev , req);
      break;    
    }
    break;
    
  case USB_REQ_CLEAR_FEATURE :
    
    switch (pdev->dev_state) 
    {
    case USBD_STATE_ADDRESSED:          
      if ((ep_addr != 0x00) && (ep_addr != 0x80)) 
      {
        USBD_LL_StallEP(pdev , ep_addr);
      }
      break;	
      
    case USBD_STATE_CONFIGURED:   
      if (req->wValue == USB_FEATURE_EP_HALT)
      {
        if ((ep_addr & 0x7F) != 0x00) 
        {        
          USBD_LL_ClearStallEP(pdev , ep_addr);
          pdev->pClass->Setup (pdev, req);
        }
        USBD_CtlSendStatus(pdev);
      }
      break;
      
    default:                         
      USBD_CtlError(pdev , req);
      break;    
    }
    break;
    
  case USB_REQ_GET_STATUS:                  
    switch (pdev->dev_state) 
    {
    case USBD_STATE_ADDRESSED:          
      if ((ep_addr & 0x7F) != 0x00) 
      {
        USBD_LL_StallEP(pdev , ep_addr);
      }
      break;	
      
    case USBD_STATE_CONFIGURED:
      pep = ((ep_addr & 0x80) == 0x80) ? &pdev->ep_in[ep_addr & 0x7F]:\
                                         &pdev->ep_out[ep_addr & 0x7F];
      if(USBD_LL_IsStallEP(pdev, ep_addr))
      {
        pep->status = 0x0001;     
      }
      else
      {
        pep->status = 0x0000;  
      }
      
      USBD_CtlSendData (pdev,
                        (uint8_t *)&pep->status,
                        2);
      break;
      
    default:                         
      USBD_CtlError(pdev , req);
      break;
    }
    break;
    
  default:
    break;
  }
  return ret;
}
Example #23
0
/* create the volatile hardware registry keys */
static void create_hardware_registry_keys(void)
{
    static const WCHAR SystemW[] = {'H','a','r','d','w','a','r','e','\\',
                                    'D','e','s','c','r','i','p','t','i','o','n','\\',
                                    'S','y','s','t','e','m',0};
    static const WCHAR fpuW[] = {'F','l','o','a','t','i','n','g','P','o','i','n','t','P','r','o','c','e','s','s','o','r',0};
    static const WCHAR cpuW[] = {'C','e','n','t','r','a','l','P','r','o','c','e','s','s','o','r',0};
    static const WCHAR FeatureSetW[] = {'F','e','a','t','u','r','e','S','e','t',0};
    static const WCHAR IdentifierW[] = {'I','d','e','n','t','i','f','i','e','r',0};
    static const WCHAR ProcessorNameStringW[] = {'P','r','o','c','e','s','s','o','r','N','a','m','e','S','t','r','i','n','g',0};
    static const WCHAR SysidW[] = {'A','T',' ','c','o','m','p','a','t','i','b','l','e',0};
    static const WCHAR mhzKeyW[] = {'~','M','H','z',0};
    static const WCHAR VendorIdentifierW[] = {'V','e','n','d','o','r','I','d','e','n','t','i','f','i','e','r',0};
    static const WCHAR VenidIntelW[] = {'G','e','n','u','i','n','e','I','n','t','e','l',0};
    /* static const WCHAR VenidAMDW[] = {'A','u','t','h','e','n','t','i','c','A','M','D',0}; */
    static const WCHAR PercentDW[] = {'%','d',0};
    static const WCHAR IntelCpuDescrW[] = {'x','8','6',' ','F','a','m','i','l','y',' ','%','d',' ','M','o','d','e','l',' ','%','d',
                                           ' ','S','t','e','p','p','i','n','g',' ','%','d',0};
    static const WCHAR IntelCpuStringW[] = {'I','n','t','e','l','(','R',')',' ','P','e','n','t','i','u','m','(','R',')',' ','4',' ',
                                            'C','P','U',' ','2','.','4','0','G','H','z',0};
    unsigned int i;
    HKEY hkey, system_key, cpu_key, fpu_key;
    SYSTEM_CPU_INFORMATION sci;
    PROCESSOR_POWER_INFORMATION power_info;
    WCHAR idW[60];

    NtQuerySystemInformation( SystemCpuInformation, &sci, sizeof(sci), NULL );
    if (NtPowerInformation(ProcessorInformation, NULL, 0, &power_info, sizeof(power_info)))
        power_info.MaxMhz = 0;

    /*TODO: report 64bit processors properly*/
    sprintfW( idW, IntelCpuDescrW, sci.Level, HIBYTE(sci.Revision), LOBYTE(sci.Revision) );

    if (RegCreateKeyExW( HKEY_LOCAL_MACHINE, SystemW, 0, NULL, REG_OPTION_VOLATILE,
                         KEY_ALL_ACCESS, NULL, &system_key, NULL ))
        return;

    set_reg_value( system_key, IdentifierW, SysidW );

    if (RegCreateKeyExW( system_key, fpuW, 0, NULL, REG_OPTION_VOLATILE,
                         KEY_ALL_ACCESS, NULL, &fpu_key, NULL ))
        fpu_key = 0;
    if (RegCreateKeyExW( system_key, cpuW, 0, NULL, REG_OPTION_VOLATILE,
                         KEY_ALL_ACCESS, NULL, &cpu_key, NULL ))
        cpu_key = 0;

    for (i = 0; i < NtCurrentTeb()->Peb->NumberOfProcessors; i++)
    {
        WCHAR numW[10];

        sprintfW( numW, PercentDW, i );
        if (!RegCreateKeyExW( cpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
                              KEY_ALL_ACCESS, NULL, &hkey, NULL ))
        {
            RegSetValueExW( hkey, FeatureSetW, 0, REG_DWORD, (BYTE *)&sci.FeatureSet, sizeof(DWORD) );
            set_reg_value( hkey, IdentifierW, idW );
            /*TODO; report amd's properly*/
            set_reg_value( hkey, ProcessorNameStringW, IntelCpuStringW );
            set_reg_value( hkey, VendorIdentifierW, VenidIntelW );
            RegSetValueExW( hkey, mhzKeyW, 0, REG_DWORD, (BYTE *)&power_info.MaxMhz, sizeof(DWORD) );
            RegCloseKey( hkey );
        }
        if (!RegCreateKeyExW( fpu_key, numW, 0, NULL, REG_OPTION_VOLATILE,
                              KEY_ALL_ACCESS, NULL, &hkey, NULL ))
        {
            set_reg_value( hkey, IdentifierW, idW );
            RegCloseKey( hkey );
        }
    }
    RegCloseKey( fpu_key );
    RegCloseKey( cpu_key );
    RegCloseKey( system_key );
}
Example #24
0
void main(void)
{
	SOCKET sock;
	
	//1.启动SOCKET库,版本为2.0
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;	
	wVersionRequested = MAKEWORD( 2, 0 );	
	err = WSAStartup( wVersionRequested, &wsaData );
	if (0 != err) 
	{
		cout<<"Socket2.0初始化失败,Exit!";
		return;
	}	
	if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 0 ) 
	{
		WSACleanup();
		return; 
	}
	
	//2.创建套接字
	sock = socket(AF_INET,SOCK_DGRAM,0);
	if (INVALID_SOCKET == sock) 
	{
		cout<<"Socket 创建失败,Exit!";
		return;
	}

	//3.设置该套接字为广播类型,
	bool opt=true;
	setsockopt(sock,SOL_SOCKET,	SO_BROADCAST,(char FAR *)&opt,sizeof(opt));
	
	//4.创建地址
	sockaddr_in from;
	memset(&from,0,sizeof(from));
	from.sin_family=AF_INET;
	//如果绑定地址不是本机地址或者ADDR_ANY,则recvfrom函数不会正确接收,而是立刻返回
	// from.sin_addr.s_addr = ADDR_ANY;  
	from.sin_addr.s_addr = inet_addr("192.168.0.7");
	//端口号必须和客户发往的端口号一致
	from.sin_port=htons(7861);
	
	//5.绑定接收地址
 	bind(sock,(sockaddr*)&from,sizeof(from));
	
	memset(&from,0,sizeof(from));
	int fromlength = sizeof(SOCKADDR);
	char buf[256];	
	memset(buf,0,sizeof(buf));
	long number = 0;
	while(true){
		number++;
	// 	recvfrom(sock,buf,256,0,(struct sockaddr FAR *)&from,(int FAR *)&fromlength);
 		recv(sock,buf,256,0);
	 	Sleep(1000);
		cout<<number<<":"<<buf<<endl;
		memset(buf,0,sizeof(buf));
	}
	
	if (!closesocket(sock)) {
		WSAGetLastError();
		return;
	}
	if (!WSACleanup()) {
		WSAGetLastError();
		return;
	}
}
Example #25
0
static BOOLEAN
StripShip (COUNT fuel_required)
{
	BYTE i, which_module;
	SBYTE crew_pods;

	SET_GAME_STATE (MELNORME_RESCUE_REFUSED, 0);

	crew_pods = -(SBYTE)(
			(GLOBAL_SIS (CrewEnlisted) + CREW_POD_CAPACITY - 1)
			/ CREW_POD_CAPACITY
			);
	if (fuel_required == 0)
	{
		GlobData.SIS_state = SIS_copy;
		LockMutex (GraphicsLock);
		DeltaSISGauges (UNDEFINED_DELTA, rescue_fuel, UNDEFINED_DELTA);
		UnlockMutex (GraphicsLock);
	}
	else if (fuel_required == (COUNT)~0)
	{
		GLOBAL_SIS (NumLanders) = 0;
		for (i = 0; i < NUM_DRIVE_SLOTS; ++i)
			GLOBAL_SIS (DriveSlots[i]) = EMPTY_SLOT + 0;
		for (i = 0; i < NUM_JET_SLOTS; ++i)
			GLOBAL_SIS (JetSlots[i]) = EMPTY_SLOT + 1;
		if (GLOBAL_SIS (FuelOnBoard) > FUEL_RESERVE)
			GLOBAL_SIS (FuelOnBoard) = FUEL_RESERVE;
		GLOBAL_SIS (TotalBioMass) = 0;
		GLOBAL_SIS (TotalElementMass) = 0;
		for (i = 0; i < NUM_ELEMENT_CATEGORIES; ++i)
			GLOBAL_SIS (ElementAmounts[i]) = 0;
		for (i = 0; i < NUM_MODULE_SLOTS; ++i)
		{
			which_module = GLOBAL_SIS (ModuleSlots[i]);
			if (which_module < BOMB_MODULE_0
					&& (which_module != CREW_POD
					|| ++crew_pods > 0))
				GLOBAL_SIS (ModuleSlots[i]) = EMPTY_SLOT + 2;
		}

		LockMutex (GraphicsLock);
		DeltaSISGauges (UNDEFINED_DELTA, UNDEFINED_DELTA, UNDEFINED_DELTA);
		UnlockMutex (GraphicsLock);
	}
	else if (fuel_required)
	{
		SBYTE bays;
		BYTE num_searches, beg_mod, end_mod;
		COUNT worth, total;
		BYTE module_count[BOMB_MODULE_0];
		BYTE slot;
		DWORD capacity;

		SIS_copy = GlobData.SIS_state;
		for (i = PLANET_LANDER; i < BOMB_MODULE_0; ++i)
			module_count[i] = 0;

		capacity = FUEL_RESERVE;
		slot = NUM_MODULE_SLOTS - 1;
		do
		{
			if (SIS_copy.ModuleSlots[slot] == FUEL_TANK
					|| SIS_copy.ModuleSlots[slot] == HIGHEFF_FUELSYS)
			{
				COUNT volume;

				volume = SIS_copy.ModuleSlots[slot] == FUEL_TANK
						? FUEL_TANK_CAPACITY : HEFUEL_TANK_CAPACITY;
				capacity += volume;
			}
		} while (slot--);
		if (fuel_required > capacity)
			fuel_required = capacity;

		bays = -(SBYTE)(
				(SIS_copy.TotalElementMass + STORAGE_BAY_CAPACITY - 1)
				/ STORAGE_BAY_CAPACITY
				);
		for (i = 0; i < NUM_MODULE_SLOTS; ++i)
		{
			which_module = SIS_copy.ModuleSlots[i];
			if (which_module == CREW_POD)
				++crew_pods;
			else if (which_module == STORAGE_BAY)
				++bays;
		}

		worth = fuel_required / FUEL_TANK_SCALE;
		total = 0;
		num_searches = 0;
		beg_mod = end_mod = (BYTE)~0;
		while (total < worth && ShipWorth () && ++num_searches)
		{
			DWORD rand_val;

			rand_val = TFB_Random ();
			switch (which_module = LOBYTE (LOWORD (rand_val)) % (CREW_POD + 1))
			{
				case PLANET_LANDER:
					if (SIS_copy.NumLanders == 0)
						continue;
					--SIS_copy.NumLanders;
					break;
				case FUSION_THRUSTER:
					for (i = 0; i < NUM_DRIVE_SLOTS; ++i)
					{
						if (SIS_copy.DriveSlots[i] < EMPTY_SLOT)
							break;
					}
					if (i == NUM_DRIVE_SLOTS)
						continue;
					SIS_copy.DriveSlots[i] = EMPTY_SLOT + 0;
					break;
				case TURNING_JETS:
					for (i = 0; i < NUM_JET_SLOTS; ++i)
					{
						if (SIS_copy.JetSlots[i] < EMPTY_SLOT)
							break;
					}
					if (i == NUM_JET_SLOTS)
						continue;
					SIS_copy.JetSlots[i] = EMPTY_SLOT + 1;
					break;
				case CREW_POD:
					i = HIBYTE (LOWORD (rand_val)) % NUM_MODULE_SLOTS;
					which_module = SIS_copy.ModuleSlots[i];
					if (which_module >= BOMB_MODULE_0
							|| which_module == FUEL_TANK
							|| which_module == HIGHEFF_FUELSYS
							|| (which_module == STORAGE_BAY
							&& module_count[STORAGE_BAY] >= bays)
							|| (which_module == CREW_POD
							&& module_count[CREW_POD] >= crew_pods))
						continue;
					SIS_copy.ModuleSlots[i] = EMPTY_SLOT + 2;
					break;
			}

			if (beg_mod == (BYTE)~0)
				beg_mod = end_mod = which_module;
			else if (which_module > end_mod)
				end_mod = which_module;
			++module_count[which_module];
			total += GLOBAL (ModuleCost[which_module]);
		}

		if (total == 0)
		{
			NPCPhrase (CHARITY);
			LockMutex (GraphicsLock);
			DeltaSISGauges (0, fuel_required, 0);
			UnlockMutex (GraphicsLock);
			return (FALSE);
		}
		else
		{
			NPCPhrase (RESCUE_OFFER);
			rescue_fuel = fuel_required;
			if (rescue_fuel == capacity)
				NPCPhrase (RESCUE_TANKS);
			else
				NPCPhrase (RESCUE_HOME);
			for (i = PLANET_LANDER; i < BOMB_MODULE_0; ++i)
			{
				if (module_count[i])
				{
					RESPONSE_REF pStr;

					switch (i)
					{
						case PLANET_LANDER:
							pStr = LANDERS;
							break;
						case FUSION_THRUSTER:
							pStr = THRUSTERS;
							break;
						case TURNING_JETS:
							pStr = JETS;
							break;
						case CREW_POD:
							pStr = PODS;
							break;
						case STORAGE_BAY:
							pStr = BAYS;
							break;
						case DYNAMO_UNIT:
							pStr = DYNAMOS;
							break;
						case SHIVA_FURNACE:
							pStr = FURNACES;
							break;
						case GUN_WEAPON:
							pStr = GUNS;
							break;
						case BLASTER_WEAPON:
							pStr = BLASTERS;
							break;
						case CANNON_WEAPON:
							pStr = CANNONS;
							break;
						case TRACKING_SYSTEM:
							pStr = TRACKERS;
							break;
						case ANTIMISSILE_DEFENSE:
							pStr = DEFENSES;
							break;
					}

					if (i == end_mod && i != beg_mod)
						NPCPhrase (END_LIST_WITH_AND);
					NPCPhrase (ENUMERATE_ONE + (module_count[i] - 1));
					NPCPhrase (pStr);
				}
			}
		}
	}

	return (TRUE);
}
Example #26
0
BOOL
GdiSelectBrush(HDC32 hDC32, LPBRUSHINFO lpBrushInfo)
{
    UINT uiCompatibility;
    BOOL bDither;
    COLORREF crColor,crTemp;
    LPIMAGEINFO lpImageInfo;
    HBITMAP hBitmap;
    int nDepth = 0;
    WORD wBrushType;
    int i;

    if (lpBrushInfo->lpBrush.lbColor & PALETTE_MASK)
	crColor = TWIN_PaletteRGB(hDC32, lpBrushInfo->lpBrush.lbColor);
    else
	crColor = lpBrushInfo->lpBrush.lbColor;

    if (lpBrushInfo->lpBrush.lbStyle == BS_SOLID) {
	wBrushType = LOWORD(lpBrushInfo->dwFlags);
	if (!(lpBrushInfo->dwFlags & DCX_DISPLAY_DC))
	    /* we have to re-realize solid brush, dither if needed */
	    wBrushType = BFP_UNASSIGNED;
	if (hDC32->hBitmap) {
	    /* if the brush is realized, but its depth is different */
	    /* from the currently selected bitmap, it has to be re- */
	    /* realized */
	    lpImageInfo = GETBITMAPINFO(hDC32->hBitmap);
	    nDepth = lpImageInfo->BitsPixel;
	    if (nDepth != (int)LOBYTE(HIWORD(lpBrushInfo->dwFlags)))
		wBrushType = BFP_UNASSIGNED;
	    RELEASEBITMAPINFO(lpImageInfo);
	}

	if (wBrushType == BFP_UNASSIGNED) {
	    /* solid brush needs to be realized;		*/
	    /* gets resolved to either BFP_PIXEL (solid color)	*/
	    /* or BFP_PIXMAP (dithered pattern)		  	*/
	    if (nDepth == 1) {
		if ((crColor == RGB(0,0,0)) || crColor == RGB(255,255,255))
		    bDither = FALSE;
		else
		    bDither = TRUE;
	    }
	    else {
		uiCompatibility = GetCompatibilityFlags(0);
		if (!(uiCompatibility & WD_NODITHERPURE)) {
		    for (i = 0, bDither = TRUE; bDither && i < 16; i ++) 
			if (RGB(VGAColors[i].rgbRed,
				VGAColors[i].rgbGreen,
				VGAColors[i].rgbBlue) == crColor)
			    bDither = FALSE;
		}
		else {
		    crTemp = GetNearestColor(GETHDC16(hDC32),crColor);
		    if (lpBrushInfo->lpBrush.lbColor & PALETTE_RGB) {
			bDither = FALSE;
			crColor = crTemp;
		    }
		    else 
			bDither = (crColor != crTemp);
		}
	    }
	    if (!bDither) {
		wBrushType = BFP_PIXEL;
		lpBrushInfo->lpPrivate = (LPVOID)DRVCALL_COLORS
				(PLH_MAKEPIXEL,
				 crColor,
				 0L,0L);
	    }
	    else {
		hBitmap = GdiDitherColor
			(GETHDC16(hDC32),crColor,nDepth);
		lpBrushInfo->lpBrush.lbHatch = (int)hBitmap;
		wBrushType = BFP_PIXMAP;
		lpImageInfo = GETBITMAPINFO(hBitmap);
		if (!lpImageInfo) {
		    return FALSE;
		}
		lpBrushInfo->lpPrivate = (LPVOID)DRVCALL_IMAGES
				(PIH_CREATEBRUSH,
				BFP_PIXMAP,0L,
				lpImageInfo->lpDrvData);
		RELEASEBITMAPINFO(lpImageInfo);
	    }
	    lpBrushInfo->dwFlags = DCX_DISPLAY_DC | wBrushType;
	    lpBrushInfo->dwFlags |= (BYTE)nDepth << 16;
	}
    }
    if (!lpBrushInfo->fIsRealized) {
	LSDS_PARAMS argptr;
	argptr.lsde_validate.dwInvalidMask = 0;
	argptr.lsde.point = hDC32->ptBrushOrg;
	DRVCALL_GRAPHICS(PGH_SETBRUSHORG,
				(DWORD)hDC32->lpDrvData,0L, &argptr);
	lpBrushInfo->fIsRealized = TRUE;
    }
    return TRUE;
}
Example #27
0
/*
 * AccLoadProg - create a new process for debugging
 */
trap_retval ReqProg_load( void )
{
    char            *parm;
    char            *src;
    char            *dst;
    char            *endsrc;
    char            exe_name[PATH_MAX];
    char            ch;
    BOOL            rc;
    int             len;
    MYCONTEXT       con;
    thread_info     *ti;
    HANDLE          handle;
    prog_load_req   *acc;
    prog_load_ret   *ret;
    header_info     hi;
    WORD            stack;
    WORD            version;
    DWORD           pid;
    DWORD           pid_started;
    DWORD           cr_flags;
    char            *buff = NULL;
    size_t          nBuffRequired = 0;
    char            *dll_name;
    char            *service_name;
    char            *dll_destination;
    char            *service_parm;

    acc = GetInPtr( 0 );
    ret = GetOutPtr( 0 );
    parm = GetInPtr( sizeof( *acc ) );

    /*
     * reset status variables
     */
    LastExceptionCode = -1;
    DebugString = NULL;
    DebugeeEnded = FALSE;
    RemoveAllThreads();
    FreeLibList();
    DidWaitForDebugEvent = FALSE;
    DebugeePid = 0;
    DebugeeTid = 0;
    SupportingExactBreakpoints = 0;

    /*
     * check if pid is specified
     */
    ParseServiceStuff( parm, &dll_name, &service_name, &dll_destination, &service_parm );
    pid = 0;
    src = parm;

    /*
    //  Just to be really safe!
    */
    nBuffRequired = GetTotalSize() + PATH_MAX + 16;
    if( NULL == ( buff = malloc( nBuffRequired ) ) ) {
        ret->err = ERROR_NOT_ENOUGH_MEMORY;
        return( sizeof( *ret ) );
    }

    if( *src == '#' ) {
        src++;
        pid = strtoul( src, &endsrc, 16 );
        if( pid == 0 ) {
            pid = -1;
        }
        strcpy( buff, endsrc );
    } else {
        while( isdigit( *src ) ) {
            src++;
        }
        if( *src == 0 && src != parm ) {
            pid = atoi( parm );
        }
    }

    /*
     * get program to debug.  If the user has specified a pid, then
     * skip directly to doing a DebugActiveProcess
     */
    IsWOW = FALSE;
#if !defined( MD_x64 )
    IsDOS = FALSE;
#endif
    if( pid == 0 ) {
        if( FindFilePath( parm, exe_name, ExtensionList ) != 0 ) {
            ret->err = ERROR_FILE_NOT_FOUND;
            goto error_exit;
        }

        /*
         * Get type of application
         */
        handle = CreateFile( (LPTSTR)exe_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
        if( handle == INVALID_HANDLE_VALUE ) {
            ret->err = GetLastError();
            goto error_exit;
        }
        GetFullPathName( exe_name, MAX_PATH, CurrEXEName, NULL );

        /*
         * get the parm list
         */
        if( strchr( CurrEXEName, ' ' ) != NULL ) {
            strcpy( buff, "\"" );
            strcat( buff, CurrEXEName );
            strcat( buff, "\"" );
        } else {
            strcpy( buff, CurrEXEName );
        }
        dst = &buff[strlen( buff )];
        src = parm;
        while( *src != 0 ) {
            ++src;
        }
        // parm layout
        // <--parameters-->0<--program_name-->0<--arguments-->0
        //
        for( len = GetTotalSize() - sizeof( *acc ) - (src - parm) - 1; len > 0; --len ) {
            ch = *src;
            if( ch == 0 ) {
                ch = ' ';
            }
            *dst = ch;
            ++dst;
            ++src;
        }
        *dst = 0;

        cr_flags = DEBUG_ONLY_THIS_PROCESS;

        if( !GetEXEHeader( handle, &hi, &stack ) ) {
            ret->err = GetLastError();
            CloseHandle( handle );
            goto error_exit;
        }
        if( hi.sig == EXE_PE ) {
            if( IS_PE64( hi.u.peh ) ) {
                DebugeeSubsystem = PE64( hi.u.peh ).subsystem;
            } else {
                DebugeeSubsystem = PE32( hi.u.peh ).subsystem;
#if defined( MD_x64 )
                IsWOW = TRUE;
#endif
            }
            if( DebugeeSubsystem == SS_WINDOWS_CHAR ) {
                cr_flags |= CREATE_NEW_CONSOLE;
            }
#if !defined( MD_x64 )
        } else if( hi.sig == EXE_NE ) {
            IsWOW = TRUE;
            /*
             * find out the pid of WOW, if it is already running.
             */
            pVDMEnumProcessWOW( EnumWOWProcessFunc, (LPARAM)&pid );
            if( pid != 0 ) {
                version = LOWORD( GetVersion() );
                if( LOBYTE( version ) == 3 && HIBYTE( version ) < 50 ) {
                    int kill = MessageBox( NULL, TRP_NT_wow_warning, TRP_The_WATCOM_Debugger, MB_APPLMODAL + MB_YESNO );
                    if( kill == IDYES ) {
                        DWORD axs = PROCESS_TERMINATE+STANDARD_RIGHTS_REQUIRED;
                        HANDLE hprocess = OpenProcess( axs, FALSE, pid );

                        if( hprocess != 0 && TerminateProcess( hprocess, 0 ) ) {
                            CloseHandle( hprocess );
                            pid = 0;
                        }
                    }
                } else {
                    cr_flags |= CREATE_SEPARATE_WOW_VDM;
                    pid = 0; // always start a new VDM.
                }
            }
            if( pid != 0 ) {
                ret->err = GetLastError();
                CloseHandle( handle );
                goto error_exit;
            }
        } else {
            IsDOS = TRUE;
#endif
        }
        CloseHandle( handle );
    }

    /*
     * start the debugee
     */
    pid_started = pid;
    if( *dll_name ) {
        strcat( buff, LOAD_PROG_STR_DELIM );
        strcat( buff, LOAD_PROG_STR_DLLNAME );
        strcat( buff, dll_name );
    }
    if( *service_name ) {
        strcat( buff, LOAD_PROG_STR_DELIM );
        strcat( buff, LOAD_PROG_STR_SERVICE );
        strcat( buff, service_name );
    }
    if( *dll_destination ) {
        strcat( buff, LOAD_PROG_STR_DELIM );
        strcat( buff, LOAD_PROG_STR_COPYDIR );
        strcat( buff, dll_destination );
    }
    if( *service_parm ) {
        strcat( buff, LOAD_PROG_STR_DELIM );
        strcat( buff, LOAD_PROG_STR_SERVICEPARM );
        strcat( buff, service_parm );
    }
    ret->err = StartControlThread( buff, &pid_started, cr_flags );
    if( ret->err != 0 ) {
        goto error_exit;
    }
    /*
     * CREATE_PROCESS_DEBUG_EVENT will always be the first debug event.
     * If it is not, then something is horribly wrong.
     */
    rc = MyWaitForDebugEvent();
    if( !rc || ( DebugEvent.dwDebugEventCode != CREATE_PROCESS_DEBUG_EVENT ) || ( DebugEvent.dwProcessId != pid_started ) ) {
        ret->err = GetLastError();
        goto error_exit;
    }
    ProcessInfo.pid = DebugEvent.dwProcessId;
    ProcessInfo.process_handle = DebugEvent.u.CreateProcessInfo.hProcess;
    ProcessInfo.base_addr = DebugEvent.u.CreateProcessInfo.lpBaseOfImage;
    AddProcess( &hi );
    AddThread( DebugEvent.dwThreadId, DebugEvent.u.CreateProcessInfo.hThread, DebugEvent.u.CreateProcessInfo.lpStartAddress );
    DebugeePid = DebugEvent.dwProcessId;
    DebugeeTid = DebugEvent.dwThreadId;
    LastDebugEventTid = DebugEvent.dwThreadId;

#if defined( MD_x86 )
#ifdef WOW
    if( IsWOW ) {
        ret->flags = LD_FLAG_IS_PROT;
        ret->err = 0;
        ret->task_id = DebugeePid;
        /*
         * we use our own CS and DS as the Flat CS and DS, for lack
         * of anything better
         */
        FlatDS = GetDS();
        FlatCS = GetCS();
        if( !executeUntilVDMStart() ) {
            ret->err = GetLastError();
            goto error_exit;
        }
        if( pid ) {
            addAllWOWModules();
        } else {
            addKERNEL();
        }
        /*
         * we save the starting CS:IP of the WOW app, since we will use
         * it to force execution of code later
         */
        ti = FindThread( DebugeeTid );
        MyGetThreadContext( ti, &con );
        WOWAppInfo.segment = ( WORD ) con.SegCs;
        WOWAppInfo.offset = ( WORD ) con.Eip;
        con.SegSs = con.SegDs; // Wow lies about the stack segment.  Reset it
        con.Esp = stack;
        MySetThreadContext( ti, &con );
    } else if( IsDOS ) {
        // TODO! Clean up this code
        ret->flags = 0; //LD_FLAG_IS_PROT;
        ret->err = 0;
        ret->task_id = DebugeePid;
        /*
         * we use our own CS and DS as the Flat CS and DS, for lack
         * of anything better
         */
        FlatDS = GetDS();
        FlatCS = GetCS();
        if( !executeUntilVDMStart() ) {
            ret->err = GetLastError();
            goto error_exit;
        }
#if 0
        if( pid ) {
            addAllWOWModules();
        } else {
            addKERNEL();
        }
#endif
        /*
         * we save the starting CS:IP of the WOW app, since we will use
         * it to force execution of code later
         */
        ti = FindThread( DebugeeTid );
        MyGetThreadContext( ti, &con );
        WOWAppInfo.segment = ( WORD )con.SegCs;
        WOWAppInfo.offset = ( WORD )con.Eip;
        con.SegSs = con.SegDs; // Wow lies about the stack segment.  Reset it
        con.Esp = stack;
        MySetThreadContext( ti, &con );
    } else {
#else
    {
#endif
#else
    {
#endif
        LPVOID base;

        if( pid == 0 ) {
            base = (LPVOID)DebugEvent.u.CreateProcessInfo.lpStartAddress;
        } else {
            base = 0;
        }

        ret->flags = LD_FLAG_IS_PROT;
        ret->err = 0;
        ret->task_id = DebugeePid;
        if( executeUntilStart( pid != 0 ) ) {
            LPVOID old;
            /*
             * make the application load our DLL, so that we can have it
             * run code out of it.  One small note: this will not work right
             * if the app does not load our DLL at the same address the
             * debugger loaded it at!!!
             */

            ti = FindThread( DebugeeTid );
            MyGetThreadContext( ti, &con );
            old = (LPVOID)AdjustIP( &con, 0 );
            if( base != 0 ) {
                SetIP( &con, base );
            }
            MySetThreadContext( ti, &con );
            SetIP( &con, old );
            MySetThreadContext( ti, &con );
        }
        ti = FindThread( DebugeeTid );
        MyGetThreadContext( ti, &con );
#if defined( MD_x86 )
        FlatCS = con.SegCs;
        FlatDS = con.SegDs;
#endif
        ret->flags |= LD_FLAG_IS_BIG;
    }
    ret->flags |= LD_FLAG_HAVE_RUNTIME_DLLS;
    if( pid != 0 ) {
        ret->flags |= LD_FLAG_IS_STARTED;
    }
    ret->mod_handle = 0;

error_exit:
    if( buff ) {
        free( buff );
        buff = NULL;
    }
    return( sizeof( *ret ) );

}

trap_retval ReqProg_kill( void )
{
    prog_kill_ret   *ret;

    ret = GetOutPtr( 0 );
    ret->err = 0;
    DelProcess( TRUE );
    StopControlThread();
    return( sizeof( *ret ) );
}
Example #28
0
 0x02,   /* bDescriptorSubtype: Abstract Control Management desc */
 0x02,   /* bmCapabilities */
 
 /*Union Functional Descriptor*/
 0x05,   /* bFunctionLength */
 0x24,   /* bDescriptorType: CS_INTERFACE */
 0x06,   /* bDescriptorSubtype: Union func desc */
 0,   /* bMasterInterface: Communication class interface */
 1,   /* bSlaveInterface0: Data Class Interface */
 
 /*Endpoint 2 Descriptor*/
 0x07,                           /* bLength: Endpoint Descriptor size */
 USB_DESC_TYPE_ENDPOINT,   /* bDescriptorType: Endpoint */
 CDC_CMD_EP,                     /* bEndpointAddress */
 0x03,                           /* bmAttributes: Interrupt */
 LOBYTE(CDC_CMD_PACKET_SIZE),     /* wMaxPacketSize: */
 HIBYTE(CDC_CMD_PACKET_SIZE),
 0x10,                           /* bInterval: */ 
 /*---------------------------------------------------------------------------*/
 
 /*Data class interface descriptor*/
 0x09,   /* bLength: Endpoint Descriptor size */
 USB_DESC_TYPE_INTERFACE,  /* bDescriptorType: */
 1,   /* bInterfaceNumber: Number of Interface */
 0x00,   /* bAlternateSetting: Alternate setting */
 0x02,   /* bNumEndpoints: Two endpoints used */
 0x0A,   /* bInterfaceClass: CDC */
 0x00,   /* bInterfaceSubClass: */
 0x00,   /* bInterfaceProtocol: */
 0x00,   /* iInterface: */
 
Example #29
0
  #if defined ( __ICCARM__ ) /*!< IAR Compiler */
    #pragma data_alignment=4   
  #endif
#endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */
/* USB Standard Device Descriptor */
__ALIGN_BEGIN uint8_t USBD_DeviceDesc[USB_SIZ_DEVICE_DESC] __ALIGN_END =
  {
    0x12,                       /*bLength */
    USB_DEVICE_DESCRIPTOR_TYPE, /*bDescriptorType*/
    0x00,                       /*bcdUSB */
    0x02,
    0x00,                       /*bDeviceClass*/
    0x00,                       /*bDeviceSubClass*/
    0x00,                       /*bDeviceProtocol*/
    USB_OTG_MAX_EP0_SIZE,      /*bMaxPacketSize*/
    LOBYTE(USBD_VID),           /*idVendor*/
    HIBYTE(USBD_VID),           /*idVendor*/
    LOBYTE(USBD_PID),           /*idVendor*/
    HIBYTE(USBD_PID),           /*idVendor*/
    0x00,                       /*bcdDevice rel. 2.00*/
    0x02,
    USBD_IDX_MFC_STR,           /*Index of manufacturer  string*/
    USBD_IDX_PRODUCT_STR,       /*Index of product string*/
    USBD_IDX_SERIAL_STR,        /*Index of serial number string*/
    USBD_CFG_MAX_NUM            /*bNumConfigurations*/
  } ; /* USB_DeviceDescriptor */

#ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED
  #if defined ( __ICCARM__ ) /*!< IAR Compiler */
    #pragma data_alignment=4   
  #endif
Example #30
0
/*
 * @implemented
 */
INT
WINAPI
WSAStartup(IN WORD wVersionRequested,
           OUT LPWSADATA lpWSAData)
{
    WORD VersionReturned = 0;
    DWORD ErrorCode = ERROR_SUCCESS;
    PWSPROCESS CurrentProcess;
    DPRINT("WSAStartup: %wx\n", wVersionRequested);

    /* Make sure that we went through DLL Init */
    if (!WsDllHandle) return WSASYSNOTREADY;

    /* Check which version is being requested */
    switch (LOBYTE(wVersionRequested))
    {
        case 0:

            /* We don't support this unknown version */
            ErrorCode = WSAVERNOTSUPPORTED;
            break;

        case 1:
            /* We support only 1.0 and 1.1 */
            if (HIBYTE(wVersionRequested) == 0)
            {
                /* Caller wants 1.0, return it */
                VersionReturned = wVersionRequested;
            }
            else
            {
                /* The only other version we support is 1.1 */
                VersionReturned = MAKEWORD(1, 1);
            }
            break;

        case 2:
            /* We support only 2.0, 2.1 and 2.2 */
            if (HIBYTE(wVersionRequested) <= 2)
            {
                /* Caller wants 2.0-2.2, return it */
                VersionReturned = MAKEWORD(2, HIBYTE(wVersionRequested));
            }
            else
            {
                /* The highest version we support is 2.2 */
                VersionReturned = MAKEWORD(2, 2);
            }
            break;

        default:

            /* Return 2.2 */
            VersionReturned = MAKEWORD(2, 2);;
            break;
    }

    /* Return the Version Requested, unless error */
    lpWSAData->wVersion = VersionReturned;

    /* We support Winsock 2.2 */
    lpWSAData->wHighVersion = MAKEWORD(2,2);
    lstrcpy(lpWSAData->szDescription, "WinSock 2.0");
    lstrcpy(lpWSAData->szSystemStatus, "Running");

    /* 
     * On Winsock 1, the following values are returned.
     * Taken straight from a Winsock Test app on Windows.
     */
    if (LOBYTE(wVersionRequested) == 1)
    {
        lpWSAData->iMaxSockets = 32767;
        lpWSAData->iMaxUdpDg = 65467;
    } 
    else
    {
        lpWSAData->iMaxSockets = 0;
        lpWSAData->iMaxUdpDg = 0;
    }

    /* Enter the startup synchronization lock */
    WsStartupLock();

    /* Now setup all our objects */
    while (TRUE)
    {
        /* Make sure we don't already have a process */
        CurrentProcess = WsGetProcess();
        if (CurrentProcess) break;

        /* Setup the process object support */
        ErrorCode = WsProcStartup();
        if (ErrorCode != ERROR_SUCCESS) break;

        /* Setup the process object support */
        ErrorCode = WsSockStartup();
        if (ErrorCode != ERROR_SUCCESS) break;

        /* Setup the process object support */
        ErrorCode = WsThreadStartup();
        if (ErrorCode != ERROR_SUCCESS) break;

        /* Try getting the process now */
        CurrentProcess = WsGetProcess();
        if (!CurrentProcess)
        {
            /* Something is weird... */
            ErrorCode = WSASYSNOTREADY;
            break;
        }
    }

    /* Check if all worked */
    if (ErrorCode == ERROR_SUCCESS)
    {
        /* Set the requested version */
        WsProcSetVersion(CurrentProcess, wVersionRequested);

        /* Increase the reference count */
        InterlockedIncrement(&CurrentProcess->RefCount);
    }

    /* Leave the startup lock */
    WsStartupUnlock();

    /* Return any Error */
    return ErrorCode;
}