⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 kernel.h

📁 可用于嵌入式编程学习
💻 H
📖 第 1 页 / 共 3 页
字号:
#define SET_STACKFAULT(T)	((T)->wInfo |= (1<<STACKFAULT_SHIFT))
#define CLEAR_STACKFAULT(T)	((T)->wInfo &= ~(1<<STACKFAULT_SHIFT))
#define SET_DEAD(T)			((T)->wInfo |= (1<<DEAD_SHIFT))
#define SET_TIMEUSER(T)		((T)->wInfo &= ~(1<<TIMEMODE_SHIFT))
#define SET_TIMEKERN(T)		((T)->wInfo |= (1<<TIMEMODE_SHIFT))
#define SET_NEEDDBG(T)		((T)->wInfo |= (1<<NEEDDBG_SHIFT))
#define CLEAR_NEEDDBG(T)	((T)->wInfo &= ~(1<<NEEDDBG_SHIFT))
#define SET_PROFILE(T)		((T)->wInfo |= (1<<PROFILE_SHIFT))
#define CLEAR_PROFILE(T)	((T)->wInfo &= ~(1<<PROFILE_SHIFT))
#define SET_NOPRIOCALC(T)	((T)->wInfo |= (1<<NOPRIOCALC_SHIFT))
#define CLEAR_NOPRIOCALC(T)	((T)->wInfo &= ~(1<<NOPRIOCALC_SHIFT))
#define SET_DEBUGWAIT(T)	((T)->wInfo |= (1<<DEBUGWAIT_SHIFT))
#define CLEAR_DEBUGWAIT(T)	((T)->wInfo &= ~(1<<DEBUGWAIT_SHIFT))
#define SET_USERBLOCK(T)	((T)->wInfo |= (1<<USERBLOCK_SHIFT))
#define CLEAR_USERBLOCK(T)	((T)->wInfo &= ~(1<<USERBLOCK_SHIFT))

struct Thread {
	WORD      	wInfo;  	/* 00: various info about thread, see above */
	BYTE		bSuspendCnt;/* 02: thread suspend count */
    BYTE		bWaitState;	/* 03: state of waiting loop */
    LPPROXY		pProxList;	/* 04: list of proxies to threads blocked on this thread */
	PTHREAD		pNextInProc;/* 08: next thread in this process */	
    PPROCESS	pProc;		/* 0C: pointer to current process */
    PPROCESS	pOwnerProc;	/* 10: pointer to owner process */
    ACCESSKEY   aky;        /* 14: keys used by thread to access memory & handles */
    PCALLSTACK  pcstkTop;   /* 18: current api call info */
	DWORD       dwStackBase;/* 1C: stack base */
    DWORD		dwStackBound;/* 20: lower bound of commited stack space */
	LPDWORD     tlsPtr;     /* 24: tls pointer */
	DWORD		dwSleepCnt; /* 28: sleep count, also pending sleepcnt on waitmult */
    DWORD		dwKernTime;	/* 2C: elapsed kernel time */
    DWORD		dwUserTime;	/* 30: elapsed user time */
	LPPROXY		lpProxy;	/* 34: first proxy this thread is blocked on */
	DWORD       dwLastError;/* 38: last error */
    HANDLE		hTh;		/* 3C: Handle to this thread, needed by NextThread */
    BYTE		bBPrio;		/* 40: base priority */
    BYTE		bCPrio;		/* 41: curr priority */
	WORD		wCount;		/* 42: nonce for blocking lists */
	PTHREAD		pPrevInProc;/* 44: previous thread in this process */
	LPTHRDDBG	pThrdDbg;	/* 48: pointer to thread debug structure, if any */
	LPBYTE		pSwapStack;	/* 4c */
    FILETIME	ftCreate;	/* 50: time thread is created */
    CLEANEVENT *lpce;		/* 58: cleanevent for unqueueing blocking lists */
    CPUCONTEXT  ctx;        /* 5c: thread's cpu context information */
	PTHREAD		pNextSleepRun; /* ??: next sleeping thread, if sleeping, else next on runq if runnable */
	PTHREAD		pPrevSleepRun; /* ??: back pointer if sleeping or runnable */
	PTHREAD		pUpRun;		/* ??: up run pointer */
	PTHREAD		pDownRun;	/* ??: down run pointer */
	LPCRIT		pOwnedList; /* ??: list of crits and mutexes for priority inversion */
	LPCRIT		pOwnedHash[PRIORITY_LEVELS_HASHSIZE];
    DWORD		dwQuantum;	/* ??: thread quantum */
    DWORD		dwQuantLeft;/* ??: quantum left */
    LPPROXY		lpCritProxy;/* ??: proxy from last critical section block, in case stolen back */
	LPPROXY		lpPendProxy;/* ??: pending proxies for queueing */
	DWORD		dwPendTime;	/* ??: pending timeout delay */
	DWORD		dwPendReturn;/* ??: return value from pended wait */
	DWORD		dwPendStart;/* ??: time at which pendoperation started */
	PTHREAD 	pCrabPth;
	DWORD		dwCrabRem;
	HANDLE		hLastCrit;	/* ??: Last crit taken, cleared by nextthread */
	DWORD		dwCrabTime;
	DWORD		dwCrabCount;
	CALLSTACK	IntrStk;
   DWORD       dwStartAddr; /* thread PC at creation, used to get thread name */
};  /* Thread */

#define THREAD_CONTEXT_OFFSET   0x5c

ERRFALSE(THREAD_CONTEXT_OFFSET == offsetof(THREAD, ctx));

#define KSetLastError(pth, err) (pth->dwLastError = err)
#define KGetLastError(pth) (pth->dwLastError)

// Any time this structure is redefined, we need to recalculate
// the offset used in the SHx profiler ISR located at
// %_WINCEROOT%\platform\ODO\kernel\profiler\shx\profisr.src
struct Process {
    BYTE        procnum;    /* 00: ID of this process [ie: it's slot number] */
    BYTE		DbgActive;	/* 01: ID of process currently DebugActiveProcess'ing this process */
    BYTE		bChainDebug;/* 02: Did the creator want to debug child processes? */
    BYTE		bTrustLevel;/* 03: level of trust of this exe */
	LPPROXY		pProxList;	/* 04: list of proxies to threads blocked on this process */
    HANDLE		hProc;		/* 08: handle for this process, needed only for SC_GetProcFromPtr */
    DWORD       dwVMBase;   /* 0C: base of process's memory section, or 0 if not in use */
    PTHREAD     pTh;        /* 10: first thread in this process */
    ACCESSKEY   aky;        /* 14: default address space key for process's threads */
	LPVOID      BasePtr;    /* 18: Base pointer of exe load */
	HANDLE		hDbgrThrd;	/* 1C: handle of thread debugging this process, if any */
	LPWSTR      lpszProcName;/* 20: name of process */
	DWORD       tlsLowUsed; /* 24: TLS in use bitmask (first 32 slots) */
	DWORD       tlsHighUsed;/* 28: TLS in use bitmask (second 32 slots) */
	PEXCEPTION_ROUTINE pfnEH;/*2C: process exception handler */
	LPDBGPARAM  ZonePtr;    /* 30: Debug zone pointer */
	PTHREAD		pMainTh;	/* 34  primary thread in this process*/
	PMODULE		pmodResource;	/* 38: module that contains the resources */
	LPName		pStdNames[3]; /* 3C: Pointer to names for stdio */
	LPCWSTR		pcmdline;	/* 48: Pointer to command line */
	DWORD		dwDyingThreads;	/* 4C: number of pending dying threads */
	openexe_t   oe;			/* 50: Pointer to executable file handle */
	e32_lite    e32;        /* ??: structure containing exe header */
	o32_lite    *o32_ptr;   /* ??: o32 array pointer for exe */
	LPVOID		pExtPdata;
};  /* Process */

#define ProcStarted(P) (((P)->dwVMBase >> VA_SECTION) == ((DWORD)((P)->lpszProcName)>>VA_SECTION))

#define MIN_STACK_SIZE PAGE_SIZE
#define CNP_STACK_SIZE (64*1024) // the size of the stack when bootstrapping a new process
#define KRN_STACK_SIZE (64*1024) // the size of kernel thread stacks
// MIN_STACK_RESERVE is the minimum amount of stack space for the debugger and/or SEH code to run.
// When there is less than this amount of stack left and another stack page is committed,
// a stack overflow exception will be raised.
#if (PAGE_SIZE == 1024)
#define MIN_STACK_RESERVE 4096
#else
#define MIN_STACK_RESERVE 8192
#endif
#define MAX_STACK_RESERVE (1024*1024)

#define MapPtr(P) (!(P) || ((DWORD)(P)>>VA_SECTION) ? (LPVOID)(P) : \
		(LPVOID)((DWORD)(P)|(DWORD)pCurProc->dwVMBase))

#define MapPtrProc(Ptr, Proc) (!(Ptr) || ((DWORD)(Ptr)>>VA_SECTION) ? (LPVOID)(Ptr) : \
		(LPVOID)((DWORD)(Ptr)|(DWORD)(Proc)->dwVMBase))

extern PROCESS ProcArray[MAX_PROCESSES]; // in schedule.c

// dwFlags for MODULES
// #define DONT_RESOLVE_DLL_REFERENCES     0x00000001	// defined in winbase.h
// #define LOAD_LIBRARY_AS_DATAFILE        0x00000002	// defined in winbase.h
// #define LOAD_WITH_ALTERED_SEARCH_PATH   0x00000008	// defined in winbase.h

ERRFALSE(!(DONT_RESOLVE_DLL_REFERENCES & 0xffff0000));
ERRFALSE(!(LOAD_LIBRARY_AS_DATAFILE & 0xffff0000));
ERRFALSE(!(LOAD_WITH_ALTERED_SEARCH_PATH & 0xffff0000));

typedef struct Module {
	LPVOID lpSelf;					/* Self pointer for validation */
	PMODULE pMod;                   /* Next module in chain */
	LPWSTR lpszModName;              /* Module name */
	DWORD inuse;                    /* Bit vector of use */
	DWORD calledfunc;				/* Called entry but not exit */
	WORD refcnt[MAX_PROCESSES];/* Reference count per process*/
	LPVOID BasePtr;                 /* Base pointer of dll load (not 0 based) */
	DWORD DbgFlags;                 /* Debug flags */
	LPDBGPARAM ZonePtr;             /* Debug zone pointer */
	ulong startip;                  /* 0 based entrypoint */
	openexe_t oe;					/* Pointer to executable file handle */
	e32_lite e32;                   /* E32 header */
	o32_lite *o32_ptr;              /* O32 chain ptr */
	DWORD breadcrumb;
	DWORD dwNoNotify;				/* 1 bit per process, set if notifications disabled */
	WORD wFlags;
	BYTE bTrustLevel;
	BYTE bPadding;
	PMODULE pmodResource;			/* module that contains the resources */
} Module;

// List of all modules
#define pModList ((PMODULE)KInfoTable[KINX_MODULES])

#define HasModRefProcPtr(pMod,pProc) ((pMod)->refcnt[(pProc)->procnum] != 0)
#define HasModRefProcIndex(pMod,iProc) ((pMod)->refcnt[(iProc)] != 0)
#define AllowThreadMessage(pMod,pProc) (!((pMod)->dwNoNotify & (1 << (pProc)->procnum)))


typedef struct FSMAP *LPFSMAP;

typedef struct FSMAP {
	HANDLE hNext;		/* Next map in list */
	HANDLE hFile;		/* File, or INVALID_HANDLE_VALUE for just vm */
	LPBYTE pBase;		/* pointer to start of kernel mapped region */
	LPBYTE pDirty;		/* non-null if r/w real file, points to dirty bitmap */
	DWORD length;		/* length of mapped region */
	DWORD filelen;		/* length of file if hFile != INVALID_HANDLE_VALUE */
	DWORD reslen;		/* length of reservation */
	Name *name;			/* points to name of event */
	CLEANEVENT *lpmlist;/* List of mappings */
	DWORD dwDirty;		/* Count of dirty pages */
	BYTE bRestart;		/* Has been flushed */
	BYTE bNoAutoFlush;	/* Disallow automatic flushing */
	WORD wPad;
} FSMAP;

// Lowest DLL load address
#define DllLoadBase KInfoTable[KINX_DLL_LOW]

#define DBG_IS_DEBUGGER    0x00000001
#define DBG_SYMBOLS_LOADED 0x80000000

#define PAGEALIGN_UP(X) (((X)+(PAGE_SIZE-1))&~(PAGE_SIZE-1))
#define PAGEALIGN_DOWN(X) ((X)&~(PAGE_SIZE-1))

// LOG_MAGIC, mem_t, fslogentry_t, and fslog_t MUST be kept in sync with filesys.h version

#define LOG_MAGIC 0x4d494b45

typedef struct mem_t {
	DWORD startptr;
	DWORD length;
	DWORD extension;
} mem_t;

typedef struct fslogentry_t {
	DWORD type;
	DWORD d1, d2, d3;
} fslogentry_t;

typedef struct fshash_t {
	DWORD hashdata[4];
} fshash_t;

#define CURRENT_FSLOG_VERSION 1

// MUST be kept in sync with data structure in coreos\filesys\filesys.h

#pragma warning(disable:4200) // nonstandard extensions warning

typedef struct fslog_t {
	DWORD version;		// version of this structure, must stay as first DWORD
	DWORD magic1;		// LOG_MAGIC if memory tables valid
	DWORD magic2;		// LOG_MAGIC if heap initialized
	union {
		struct {
			mem_t fsmemblk[2]; 	// Memory blocks to use for file system
			LPBYTE pFSList;
			LPBYTE pKList;
		};
		struct {
			CEGUID guid;
			DWORD dwRestoreFlags;
			DWORD dwRestoreStart;
			DWORD dwRestoreSize;
		};
	};	
	DWORD virtbase;		// VirtBase when last booted
	DWORD entries;		// number of entries in recovery log
	DWORD hDbaseRoot;   // handle to first dbase, else 0
	DWORD hReg;		// Handle to registry header
	DWORD dwReplMask;	// replication mask
	DWORD flags;		// file system flags
	fshash_t pwhash;	// hashed password
	fslogentry_t log[];	// log entries
} fslog_t;

#pragma warning(default:4200) // nonstandard extensions warning

LPVOID AllocMem(ulong poolnum);
VOID FreeMem(LPVOID pMem, ulong poolnum);
LPName AllocName(DWORD dwLen);
#define FreeName(lpn) FreeMem(lpn,lpn->wPool);
PHYSICAL_ADDRESS GetHeldPage(void);
PHYSICAL_ADDRESS GetReservedPage(void);
BOOL HoldPages(int cpNeed, BOOL bForce);
void DupPhysPage(PHYSICAL_ADDRESS paPFN);
void FreePhysPage(PHYSICAL_ADDRESS paPFN);
LPVOID InitNKSection(void);
BOOL AutoCommit(ulong addr);
BOOL DemandCommit(DWORD);
void GuardCommit(ulong addr);
BOOL ProcessPageFault(BOOL bWrite, ulong addr);
void FreeSection(PSECTION pscn);
PSECTION GetSection(void);
LPVOID GetHelperStack(void);
void FreeHelperStack(LPVOID);
BOOL CreateMapperSection(DWORD dwBase);
void DeleteMapperSection(DWORD dwBase);
void CloseMappedFileHandles();
void FreeIntrFromEvent(LPEVENT lpe);
void EnterPhysCS(void);
BOOL ScavengeStacks(int cNeed);
void CreateNewProc(ulong nextfunc, ulong param);
void KernelInit2(void);
void AlarmThread(LPVOID param);
void RunApps(ulong param);
#if x86
void InitNPXHPHandler(LPVOID);
void InitializeEmx87(void);
void InitializeFPU(void);
extern DWORD dwFPType;
#endif

/** Return values from AutoCommit(...): */
#define AUTO_COMMIT_RESCHED 0
#define AUTO_COMMIT_HANDLED 1
#define AUTO_COMMIT_FAULT   2

void SetCPUASID(PTHREAD pth);
#ifdef SHx
void SetCPUGlobals(void);
#endif

LPVOID VerifyAccess(LPVOID pvAddr, DWORD dwFlags, ACCESSKEY aky);
BOOL IsAccessOK(void *addr, ACCESSKEY aky);

void KUnicodeToAscii(LPCHAR, LPCWSTR, int);
void KAsciiToUnicode(LPWSTR wchptr, LPBYTE chptr, int maxlen);

LPVOID GetOneProcAddress(HANDLE, LPCVOID, BOOL);
HANDLE LoadOneLibraryW(LPCWSTR,BOOL,WORD);
PMODULE LoadOneLibraryPart2(LPWSTR lpszFileName, BOOL bAllowPaging, WORD dwFlags);
VOID FreeAllProcLibraries(PPROCESS);
PVOID PDataFromPC(ULONG pc, PPROCESS pProc, PULONG pSize);
LPVOID SC_GetProcAddressW(HANDLE hInst, LPWSTR lpszProc);
LPVOID SC_GetProcAddressA(HANDLE hInst, LPCSTR lpszProc);
BOOL SC_DisableThreadLibraryCalls(PMODULE hLibModule);

LPWSTR SC_GetCommandLineW(VOID);
PFNVOID DBG_CallCheck(PTHREAD pth, DWORD dwJumpAddress);
#define DBG_ReturnCheck(pth) ((pth)->pcstkTop ? (pth)->pcstkTop->retAddr : 0)
BOOL UserDbgTrap(EXCEPTION_RECORD *er, PCONTEXT pctx, BOOL bFirst);
void SurrenderCritSecs(void);
BOOL SetThreadBasePrio(HANDLE hth, DWORD nPriority);
HANDLE EventModIntr(LPEVENT lpe, DWORD type);
VOID MakeRunIfNeeded(HANDLE hth);

extern void (*TBFf)(LPVOID, ulong);
extern void (*MTBFf)(LPVOID, ulong, ulong, ulong, ulong);
extern void (*CTBFf)(LPVOID, ulong, ulong, ulong, ulong);
extern BOOL (*KSystemTimeToFileTime)(LPSYSTEMTIME, LPFILETIME);
extern LONG (*KCompareFileTime)(LPFILETIME, LPFILETIME);
extern BOOL (*KFileTimeToSystemTime)(const FILETIME *, LPSYSTEMTIME);
extern BOOL (*KLocalFileTimeToFileTime)(const FILETIME *, LPFILETIME);
extern void (*pPSLNotify)(DWORD, DWORD, DWORD);
extern BOOL (*pGetHeapSnapshot)(THSNAP *pSnap, BOOL bMainOnly, LPVOID *pDataPtr);
extern HANDLE (*pGetProcessHeap)(void);

#ifdef IN_KERNEL
extern ROMHDR * const volatile pTOC;
#endif

void KernelRelocate(ROMHDR *const pTOC);
void KernelFindMemory(void);

extern ROMChain_t *ROMChain;

DWORD CECompress(LPBYTE  lpbSrc, DWORD cbSrc, LPBYTE lpbDest, DWORD cbDest, WORD wStep, DWORD dwPagesize);
DWORD CEDecompress(LPBYTE  lpbSrc, DWORD cbSrc, LPBYTE  lpbDest, DWORD cbDest, DWORD dwSkip, WORD wStep, DWORD dwPagesize);

typedef struct LSInfo_t {
	PTHREAD pHelper;// must be first
	HTHREAD hth;	// hthread to start
	DWORD startip;	// starting ip after switch
	DWORD flags;	// creation flags
	LPVOID lpStack;	// pointer to new stack
	LPVOID lpOldStack; // pointer to old stack
	DWORD cbStack;	// bytes in stack
	DWORD cmdlen;	// length of command line
	DWORD namelen;	// length of process name
	HANDLE hEvent;	// event to signal
} LSInfo_t;

extern HANDLE hAlarmThreadWakeup;
DWORD ThreadSuspend(PTHREAD hTh);
void BlockWithHelper(FARPROC pFunc, FARPROC pHelpFunc, LPVOID param);
void BlockWithHelperAlloc(FARPROC pFunc, FARPROC pHelpFunc, LPVOID param);

int ropen(WCHAR *name, int mode);
int rread(int fd, char *buf, int cnt);
int rreadseek(int fd, char *buf, int cnt, int off);
int rlseek(int fd, int off, int mode);
int rclose(int fd);
int rwrite(int fd, char *buf, int cnt);

void kstrcpyW(LPWSTR p1, LPCWSTR p2);
unsigned int strlenW(LPCWSTR str);
unsigned int strlen(const char *str);
int kstrcmpi(LPWSTR str1, LPWSTR str2);
int strcmpW(LPCWSTR lpu1, LPCWSTR lpu2);
int strcmp(const char *lpc1, const char *lpc2);

LPVOID memset(LPVOID dest, int c, unsigned int count);
LPVOID memcpy(LPVOID dest, const void *src, unsigned int count);

#ifdef x86
void InvalidateRange(PVOID, ULONG);
#else
void FlushTLB(void);
#define InvalidateRange(x, y) FlushTLB()
#endif

#if defined(WIN32_CALL) && !defined(KEEP_SYSCALLS)
#undef InputDebugCharW
int WINAPI InputDebugCharW(void);
#undef OutputDebugStringW
VOID WINAPI OutputDebugStringW(LPCWSTR str);
#undef NKvDbgPrintfW
VOID NKvDbgPrintfW(LPCWSTR lpszFmt, CONST VOID * lpParms);
#endif

#if defined(SH3)
void FlushCache(void);
void FlushCacheNoDiscard(void);
#elif defined(x86)
void FlushCache(void);
#else
void FlushICache(void);
void FlushDCache(void);
#endif

void DumpStringToSerial(LPCWSTR);
HANDLE DoCreateThread(LPVOID lpStack, DWORD cbStack, LPVOID lpStart, LPVOID param, DWORD flags, LPDWORD lpthid, ulong mode, WORD prio);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -