Windows operating system Flashcards
What is Kernel mode stack?
Its of size 12 KB and is part of 2 GB kernel space. Though the stack is allocated in kernel (system) space, it is associated with the running thread and will be swapped out when thread relinquishes its control
What is system services dispatcher function? (KiSystemService)
The main function in a device driver is Driver entry. In kernel mode each request is treated as an IRP (Interrupt request packet) so for every read, write and any other operation separate IRP’s are generated. For example - IRP_MJ/MN_READ, IRP_MJ/MN_WRITE etc. In the dispatcher function, code is written to invoke an action to perform when a particular IRP occurs i.e. suppose for IRP_MJ_READ operation the control goes from driver entry to dispatcher function , in that IRP_MJ_READ is handled.
what are different calling conventions
Below are important calling conversions
- _cdecl(caller frees the stack, parameters are passed from RL).
- __stdcall(callee frees up the stack, RL), Also known as pascal calling convention.
- __fastcall(callee frees up the stack, first in register and then on stack) .
- thiscall(callee, RL, the this pointer is passed in ECX register).
In debug mode, VC++ compiler adds stack-check function to check stack overrun or underrun. What is that? How it is useful?
For threads total stack region reserved is 1 MB, out of which 2 pages are committed to physical storage. Other pages are committed as stack grows in size. The second page is protected with PAGE_GUARD attribute and when thread tries to write on it (as an effect of stack growing), exception is thrown and a new page is committed. Sometimes the functions requires quite big stack (which needs more than 2 pages) in such case the statements in function might access area below page_guard page, which will result in access violation. (say function has a big array: int i[10000]). To avoid this, c run-time stack check function finds out total requirement of stack memory and commits that much memory in advance.
How to call 32 bit function from 16 bit code?
Using universal thunking. Universal thunking enables you to call a 32-bit function from 16-bit code. Universal thunking is supported by Windows NT and Windows 95/98 both.
What does .pdb file contains?
PDB (Program Database) is a symbol table file. Compiler switch \PDB:SEPT keeps type info in VC60.PDB file and symbol table in .PDB file. \PDB:CON puts both information in one .pdb file. These PDB files are very useful while debugging. If these files are not there then developer has to understand each and every assembly language instruction while debugging. PDB files makes debuggers life easy. If these files are available, debugger application can load these files while debugging and so user can see symbol names instead of hexadecimal values.
How will you post a message to a thread and not to any window created by that thread?
PostMessage(msg, NULL);
What is windows subclassing?
Subclassing is a procedure that allows an application to intercept and process messages sent or posted to a particular window before the window has a chance to process them. By subclassing a window an application can augment, modify or monitor the behavior of the window.
Hint: Change the address of wndproc using SetWindowLong() function
What is window superclassing
Superclassing is a technique that allows a application to create a new window class having basic functionality of the existing class plus enhancements provided by the application.
User mode synchronization objects means what? Does thread never goes in the kernel mode?
User mode synchronization objects don’t put thread in wait state and so executes in user mode only. Spin lock is the only true user mode synchronization object. Critical section tries to spin for certain number of time and then transitions to the kernel mode (during wait state). It internally uses event kernel object.
What is semaphore. Where it is used?
Semaphore is used where access to n number of resources need to controlled.
Semaphore uses two counters, max_resource_count specifies maximum number of resources that can be controlled and cur_resource_count specifies number of resources available for processing at present.
Semaphore is signaled if cur_resouce_count > 0.
CreateSemaphor() API creates a semaphore object. ReleaseSemaphor() is called when resource is available for other threads to use. Successful wait on the semaphor (WaitForSingleObject() is returning) decrements current resource count by 1 since one of the waiting thread has started using available resource.
What are the ways to debug ‘release’ mode application?
- Put debug info into release build as well.
2. Using MAP file and PDB file.
How to find crash location?
Use map file to find the crash address. The simple formula to find the line number and source file name is
what is structure of MAP file?
MAP file is the textual representation of your programs global symbols and source file and line number information. These files are very useful to find a crash location just by an address. The format of .map file is as follows. It has 5 different sections.
- States binary’s preferred base address location.
- Puts info about different sections (PE)
- lists all public ‘c’ functions with RVA+base address info.
- source file and line number info.
- exported functions.
The simple formula to find the line number and source file name is (Crash address - pref load address - 0x1000). To get the function name where crash occurred search for the function having RVA+base value greater than crash address. The preceding function is where the crash occurred.
How memory is partitioned?
On windows 2000, there are 4 main partitions -
- NULL pointer assignment
- user mode
- 64 KB off limits
- kernel mode.
Two additional partitions on win98 are
- 16 bit dos/windows application compatibility
- shared MMF.
What is the concept of 3GB user mode space?
The total process address space is divided as 2 GB user mode space and 2 GB kernel mode space. This 2 GB user mode space is not sufficient for some applications. So on Windows 2000 advance server, we can have setting such that 3 GB addess space is given to user mode application and kernel fits in only 1 GB. Applications must be compiled with /LARGEADRESSSPACE option to behave properly in 3 GB address space.
What is the advantage of having multiple paging files configured on a system, on different hard drives.
OS can write on multiple drives simulteniously. This will improve the performance.
What’s OS default behaviour for thread stack? How does it grows for OS 98/2000?
Each thread has 1 MB of stack region reserved for it. Out of which, initially only 2 pages are committed. Stack pointer points to the first page and second page has PAGE_GAURD protection attribute. So when stack grows to second page, exception is thrown and system commits one more page, and moves PAGE_GUARD attribute to this new page. This way stack grows. When stack reaches to end of third-last page of stack region, second last page is committed and here PAGE_GUARD attribute is not applied to new page i.e. last page. The system next throws STACK_OVERFLOW exception. The last page is never committed and if stack grows to this page, access violation exception is thrown.
Same happens in win98 with some exceptions, win98 protects for both stack overflow and underflow, PAGE_NOACCESS attribute is applied instead of PAGE_GUARD.
What is the use of ‘stack check’ function defined n c- run time library
This function checks the memory required for the function to execute is committed or not. If not committed, commits the required amount of memory. This is very useful if function has a very big stack.
What is hardware exception and software exception?
Exceptions raised by CPU are called as hardware exceptions (e.g. invalid memory access, divide by 0).
Exceptions raised by operating system or applications is called software exception (raiseexception() API).
What is heap?
Heaps are used to allocate small blocks of memory. It ignores allocation granularity boundary and page size. Internally it is a region of reserved address space. The pages are committed to this address space as and when required. System’s paging file backs these pages. Access to all heaps is serialized by default. One can opt for un-serialized heap using options flag parameter of function CreateHeap().
Design a single threaded application doing both background processing & UI handling
Hint: use fibre and peekmessage.
Write an edit control that takes only numeric input?
Use Subclassing in this case. The procedure should return an error message if the input is other than numeric value.
Hint: WM_CHAR massage
Why do we need to dispatch message? Why it is not processed when received in GetMassage() loop
Message loop is per thread. One thread may create two or more windows having different winproc to process messages corresponding to it. DispatchMessage() API dispatches messages to appropriate winproc for processing.
What is the difference bet GetMessage() and PeekMessage() API
- GetMessage() removes message from thread message queue whereas PeekMessage() function reads the message from thread message queue without removing it from there.
- GetMessage() functions waits if no message is present in the thread message queue whereas PeekMessage() returns if no message is present.
What is the difference between SendMessage() and PostMessage()
PostMessage() posts a message to thread message queue and returns immediately. SendMessage() sends a message to window procedure and does not return until the message is processed.
Windows first generates virtual key messages which are then converted to character messages using function TraslateMessage(). why?
Keyboard messaging - Each keyboard has a device driver associated with it. When a key is pressed, the device driver reads scan code and maps it to a virtual key code which are device independent. A message is then posted to system message queue with this virtual scan code. Then system posts these messages to appropriate thread’s message queue which is retrieved by GetMessage() API. TranslateMessage() API converts these messages to character messages.
How TranslateAccelarator( ) function works?
TranslateAccelarator() processes accelerator keys for menu items. It translates WM_KEYDOWN or WM_SYSKEYDOWN message to a WM_COMMAND or WM_SYSCOMMAND message and sends the message directly to a window procedure. TranslateAccelerator() does not return until the window procedure has processed the message.
What is the use of window subclassing?
By subclassing a window an application can augment, modify or moniter the behavior of the window.
3 threads are manipulating a linked list.
- read,
- modify if not present add
- delete.
What synchronization technique will you use? Synchronization should be efficient.
The ideal synchronization technique to use here is multiple read single write lock. This will be the most efficient technique.
What are jobs? Its usage
Job is a container of processes. One or many processes can be contained in a job object. Job objects lets programmer assign some restrictions on the processes which he normally cannot apply on individual processes like maximum allowed CPU time, maximum and minimum working set, preventing client application from shutting down machine, limit processes accessing security info.
If a process in a job spawns a child process then child automatically becomes part of a job.
Closing a job object doesn’t terminate any of processes, it just marks the job object for deletion and deletes it when the allocated CPU time is elapsed.
Job object is non-signaled when processes in the job has not used allocated CPU time. It becomes signaled when allocated CPU time lapses and then windows forcibly kills all the processes in the job and signals job object
C++ resources are not cleaned up calling ExitThread. (T/F)?
TRUE.
C++ resources used by thread are not cleaned up properly if ExitThread() function is called. This is because when ExitThread() is called, the thread terminates in the called function immediately and so it does not get any chance to call any other function like destructor of a c++ class object.
What are thread psuedo handler? Its usage
GetThreadHandle() function returns a pseudo handle.
Pseudo handle always represents current thread. Call GetThreadHandle() in one thread and pass this handle to second thread. When handle reaches in second thread it represents second thread and not the first which called GetThreadHandle() function.
What does a thread context contains?
Thread context contains all the thread registers like IP, SP etc. These registers contains values when thread was last executing. Thread context data structure is part of thread kernel object. A thread has two contexts, user mode and kernel mode. GetThreadContext() API returns user-mode context.
What is the difference between sleep(0) and SwitchToThread() function?
Both makes a thread to relinquish its remainder of time slice and gives another thread opportunity to become schedulable. Sleep(0) schedules only same or higher priority thread. SwitchToThread() gives opportunity to lower priority thead to become schedulable.
Difference between manual reset and auto reset events
When manual reset event is signaled, all threads waiting on it becomes schedulable. For auto reset event, only one thread becomes schedulable and all other remains in wait state.
Whats use PulseEvent function?
PulseEvent function calls SetEvent() and ResetEvent() internally. There is no other specific use of this API
Mutex object keeps track of which thread owns it? Why?
Mutex keeps track of the thread id which owns it. This unique design of mutex makes it possible to call WaitForSingleObject(mutex) multiple times on single thread. Mutex internally check which thread is calling wait, if same thread is calling then it increments recursion counter. Also if a owning thread dies without releasing a mutex then other Waitforsingleobject() functions returns with code WAIT_ABONDONDED.
When a wait function returns WAIT_ABONDONED?
A thread is owning a mutex and if it dies without releasing it, then other theads which are waiting on this mutex returns (i.e. waitforsingleobject()) with a code WAIT_ABONDONED.
Difference between waitable time and user timer
Waitable time is a kernel object. In case of manual reset waitable time all threads waiting on it becomes schedulable. Since this is a kernel object, it can be shared across processes. Once timer if off, the thread becomes schedulable and so will execute the remaining functionality.
User time posts WM_TIMER messages to the calling thread’s message queue. Only one thread is notified when timer goes off. User timer needs lots of user interface infrastructure. Also WM_TIMER is a low priority message so it is not guaranteed that the thread is scheduled as soon as the timer goes off.
MMF is kernel mode object? (T/F)
True, that’s why it can be used in IPC
What are dynamic and static TLS? What is the use of static TLS?
Dynamic TLS uses four API’s TlsAlloc(), TlsFree(), TlsGetValue(), TlsSetValue(). TLS is managed using these four functions.
Static TLS is created by using special compiler directive __declspec(thread) followed by a global or static variable. All these TLS variables are put in a section called .tls. When application is loaded it creates a memory block large enough to hold all variables in .tls section. Such block is created for each and every thread in the application.
Dynamic TLs is better than static for following reasons
- TlsAlloc() makes index to point to 0 in each thread.
- Static TLS has overload of accessing particular memory location, so puts more code while compilation and linking.
What is local unwind?
Termination handler is called irrespective of how control leaves try block. Premature termination of try block (return, goto, setjump etc..) causes local unwind in which control is passed to termination handler and then again returns to the try block from where it left. Compiler adds this code to jump to the termination handler and jump back to the try block once finally block execution is complete.
__leave keyword suppresses local unwind and moves control to the termination handler smoothly.
How will you debug a multithreaded application?
The best way to debug a multithreaded application is
- Keep the thread functions small.
- Synchronize at lowest level.
- Use logging information
How copy-on-write mechanism works?
Copy-on-write is used where pages are shared among multiple processes. The page has protection attribute COPY_ONWRITE. If any of the process attempts to write anything of these shared pages, the process gets his own copy of the page for processing. This way a lot of memory is saved.
If a DLL is shared among multiple processes and has global variable. If one process changes global variable then does second process gets affected? How this thing works>
No, Global variables are not shared among processes. Each process has its own global variable. If you want to share a global variable among processes, put it under a shared section and then use it. A global variable in a process is shared by all the threads in process and so may need some synchronization.
implement spin lock - aquirespinlock() and releasespinlock() functions
Hint: interlocked family of functions and sleep(0)
Difference between virtual memory and MMF
Virtual memory and MMF are two different concepts.
Virtual memory is total address space available to a user. In win32 its 4 GB. But user can access around 2 GB of virtual memory. This memory need to be backed by physical memory i.e. RAM or paging file.
MMF can have physical storage backed by a paging file or a different physical file altogether.