Windows operating system Flashcards

1
Q

What is Kernel mode stack?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is system services dispatcher function? (KiSystemService)

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what are different calling conventions

A

Below are important calling conversions

  1. _cdecl(caller frees the stack, parameters are passed from RL).
  2. __stdcall(callee frees up the stack, RL), Also known as pascal calling convention.
  3. __fastcall(callee frees up the stack, first in register and then on stack) .
  4. thiscall(callee, RL, the this pointer is passed in ECX register).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

In debug mode, VC++ compiler adds stack-check function to check stack overrun or underrun. What is that? How it is useful?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to call 32 bit function from 16 bit code?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does .pdb file contains?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How will you post a message to a thread and not to any window created by that thread?

A

PostMessage(msg, NULL);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is windows subclassing?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is window superclassing

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

User mode synchronization objects means what? Does thread never goes in the kernel mode?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is semaphore. Where it is used?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the ways to debug ‘release’ mode application?

A
  1. Put debug info into release build as well.

2. Using MAP file and PDB file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to find crash location?

A

Use map file to find the crash address. The simple formula to find the line number and source file name is

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

what is structure of MAP file?

A

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.

  1. States binary’s preferred base address location.
  2. Puts info about different sections (PE)
  3. lists all public ‘c’ functions with RVA+base address info.
  4. source file and line number info.
  5. 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How memory is partitioned?

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the concept of 3GB user mode space?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the advantage of having multiple paging files configured on a system, on different hard drives.

A

OS can write on multiple drives simulteniously. This will improve the performance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What’s OS default behaviour for thread stack? How does it grows for OS 98/2000?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the use of ‘stack check’ function defined n c- run time library

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is hardware exception and software exception?

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is heap?

A

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().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Design a single threaded application doing both background processing & UI handling

A

Hint: use fibre and peekmessage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Write an edit control that takes only numeric input?

A

Use Subclassing in this case. The procedure should return an error message if the input is other than numeric value.

Hint: WM_CHAR massage

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Why do we need to dispatch message? Why it is not processed when received in GetMassage() loop

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is the difference bet GetMessage() and PeekMessage() API

A
  1. GetMessage() removes message from thread message queue whereas PeekMessage() function reads the message from thread message queue without removing it from there.
  2. GetMessage() functions waits if no message is present in the thread message queue whereas PeekMessage() returns if no message is present.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the difference between SendMessage() and PostMessage()

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Windows first generates virtual key messages which are then converted to character messages using function TraslateMessage(). why?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

How TranslateAccelarator( ) function works?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is the use of window subclassing?

A

By subclassing a window an application can augment, modify or moniter the behavior of the window.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

3 threads are manipulating a linked list.

  1. read,
  2. modify if not present add
  3. delete.

What synchronization technique will you use? Synchronization should be efficient.

A

The ideal synchronization technique to use here is multiple read single write lock. This will be the most efficient technique.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What are jobs? Its usage

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

C++ resources are not cleaned up calling ExitThread. (T/F)?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What are thread psuedo handler? Its usage

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What does a thread context contains?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is the difference between sleep(0) and SwitchToThread() function?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Difference between manual reset and auto reset events

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Whats use PulseEvent function?

A

PulseEvent function calls SetEvent() and ResetEvent() internally. There is no other specific use of this API

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Mutex object keeps track of which thread owns it? Why?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

When a wait function returns WAIT_ABONDONED?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Difference between waitable time and user timer

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

MMF is kernel mode object? (T/F)

A

True, that’s why it can be used in IPC

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What are dynamic and static TLS? What is the use of static TLS?

A

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

  1. TlsAlloc() makes index to point to 0 in each thread.
  2. Static TLS has overload of accessing particular memory location, so puts more code while compilation and linking.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What is local unwind?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

How will you debug a multithreaded application?

A

The best way to debug a multithreaded application is

  1. Keep the thread functions small.
  2. Synchronize at lowest level.
  3. Use logging information
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

How copy-on-write mechanism works?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

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>

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

implement spin lock - aquirespinlock() and releasespinlock() functions

A

Hint: interlocked family of functions and sleep(0)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

Difference between virtual memory and MMF

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

How data is accessed in RAM i.e. how virtual address is mapped to physical address?

A

Assuming 4k pages… ->
The virtual address gets chopped up into three parts, 10 bits, 10 bits, and 12 bits. Take, for example, 80123456: 1000 0000 00 01 0010 0011 0100 0101 0110 So, the three parts are 0x200, 0x123, and 0x456. The CR3 register contains the physical address of the Page Directory, a table of 1024 4-byte entries. The top 10 bits are an index into the Page Directory. In this case, we read the 0x200th Page Directory Entry, at CR3 + 0x800. This is the physical address of the Page Table that contains our page. The second 10 bits are an index into this Page Table. We need the 0x123rd Page Table Entry, at offset 0x48C in the Page Table. This entry contains the physical address of the start of this page. All we do then is add the low 12 bits (0x456) to that address, and we have the physical address for 0x80123456. Pretty amazing, considering this process is repeated for EVERY memory address reference.

50
Q

What is difference between c++ exception handling and structured exception handling.

A

C++ Exception handling is object oriented whereas structured exception handling is not. Structured exception handling is used in Windows system programming where both exception and termination handling is required. Also the structured exception handling gives programmer the opportunity to execute the same instruction that caused exception to occur (EXCEPTION_CONTINUE_HANDLER).

Global unwind and local unwind adds great features to structured exception handling. c++ exception handling is not designed to accept access violation, divide by zero exceptions. Its purely a language feature and should be used in that context only. (MSVC++ exception handling is implemented using structured exception handling so does capture access violation and divide by 0 errors)

51
Q

PostMessage() can take first parameter as NULL, so in this case where message is posted i.e. which window

A

The message gets posted to the thread and not to any particular window.

52
Q

Does all kernel objects are named?

A

Yes, all kernel objects are named and resides in one global namespace. All the threads and processes running in the system can access to the kernel objects.

53
Q

what is environment variable change notification message?

A

WM_SETTINGCHANGE

54
Q

What is /SUBSYSTEM:console and /SUBSYSTEM:Windows?

A

These two subsystems decides your application is windows ( /SUBSYSTEM:windows) or console (SYBSYSTEM:console) application. For console subsystem the loader automatically attaches a console to the calling program.

55
Q

What is the use of private keyword in module definition file (.def file)?

A

Private keyword is used in Export section. This keyword makes the function name not to appear in .lib file but keeps it in DLL’s export table. This makes the function to be called using LoadLibrary() API only.

56
Q

What is the use of spin count in critical section?

A

Critical section is a partial user mode object. It spins for certain number of times before transitioning into kernel mode. The spin-count specifies number of times it spins in a loop before moving the thread into wait state.

57
Q

There is a main thread which spwans a client thread. Client thread is doing some CPU intensive work. How will you notify worker thead to stop its work

A

Multiple ways to achieve this

  1. Keep a global flag and in worker thread check for this flag’s value at a certain time interval.
  2. post a message to worker thread when needed.
58
Q

Do we need a window for having a message queue

A

No, when the thread calls any GUI (user32.lib) related function a thread message queue is created.

59
Q

Does DispatchMessage() calls winproc directly?

A

Yes, It passes the message to appropriate winproc for processing

60
Q

Console application consist of
1. main instead of winmain
2. Cannot call windows API.
Is it true?

A

Console window consist of main instead of winmain. There is very little difference between console and windows application. The main difference is console application has text window. But its possible to call any windows API thru console application. Similarly a GUI application can create a console window to output some information.

61
Q

How much is the total user addressable memory in win32

A

Total process address space is 4 GB of which 2 GB is taken by kernel. So total user address space is around 2 GB

62
Q

What is the use of TranslateMessage() API

A

TranlateMessage() converts virtual-key messages to character messages

63
Q

What is process group?

A

This feature is available only in windows 2000. A group of processes can be allocated to a job object. This feature enables user to assign certain restrictions on the processes like restricted security access, CPU time, maximum and minimum working set etc.
This group of processes is called Process group

64
Q

How does MMF works?

A

Steps are -

  1. Create a file object which states the location of physical storage
  2. Create a mapping object which states the size then 3. Create a view which reserves a region of virtual memory and maps it to the memory defined by file mapping object.
65
Q

Virtual memory address capacity depends on ____ ?

A

Total virtual memory available in win32 is 4 GB out of which 2 GB is available for user

66
Q

What is structured exception handling?

A

Structured handling has two parts -

  1. Termination handler - try..finaly block - This block is always executed no matter how you exit from try block. Generally all cleanup work is done here. Premature exit of try block (return, goto etc) causes local unwind to occur. __leave keyword suppresses local unwind.
  2. Exception handler- try..except block - This block is executed when any exception occurs. The except accepts one parameter i.e. execution handler. It can have 3 values. EXECUTE_HANDLER - causes global unwind to occur and executes the except block. CONTINUE_EXECUTION - resumes execution at the statement which caused exception to occur. CONTINUE_SEARCH - continues search for next matching try block.
67
Q

How to gracefully shutdown multithreaded supplication?

A

The best way is to gracefully return from its primary thread’s function. This will ensure cleanup of all the used resources. If application is a multithreaded, to return from primary thread gracefully we need to terminate all the other threads. The same rule is applicable here too, i.e. all the other threads should get terminated gracefully so that the local resources are cleanup properly.

68
Q

What are different types of synchronization objects?

A

Following are different synchronization objects supported by Windows -

  1. Event - One thread has finished its work (say initialization) and other thread can now work on the data.
  2. Waitable timer-Some operation to be performed at a certain time.
  3. Semaphore- Access to number of resources need to be controlled.
  4. Mutex- Exclusive access to some resource is required.
69
Q

What is the difference between mutex and critical section?

A

Critical section is a user mode object so cannot be shared across process. It’s Faster and cannot be mixed with other synchronization objects for wait.

Mutex is kernel mode object, can be shared across process, it is slower that critical section, it can be mixed with other synchronization objects.

70
Q

What will happen if you call ExitThread() on primary thread? Will the process die

A

No, the process wont die and will continue executing. The process gets terminated only if it returns gracefully from primary thread or ExitProcess() is called on one of its threads.

71
Q

How to create a detached child process?

A

Use DETACHED_PROCESS attribute while creating a child process. Also detached process mean the other process don’t have any information about the created process. So after creating the process call CloseHandle() on created process’s id and created process’s primary thread handle.

72
Q

What is the best way to terminate a process

A

The best way to terminate a process is to return gracefully from its primary thread’s function. This will ensure that all the resources (c++, c runtime library or OS) are cleaned up properly. Don’t use TerminateThread, ExitThread, ExitProcess functions to terminate a process.

73
Q

Semaphore with max resource count 1 is equal to event? Is this true?

A

Yes, its same as auto-reset event. But not same as a mutex for following reasons -
A thread that owns a mutex object can wait repeatedly for the same mutex object to become signaled without its execution becoming blocked. A thread that waits repeatedly for the same semaphore object, however, decrements the semaphore’s count each time a wait operation is completed; the thread is blocked when the count gets to zero. Similarly, only the thread that owns a mutex can successfully call the ReleaseMutex function, though any thread can use ReleaseSemaphore to increase the count of a semaphore object.

74
Q

Why do we need two counters in semaphore. Is it possible to design it with one counter?

A

Its not possible to design it using one counter. The use of two counters is well defined. Max_resource_counter defines max number of resources that can be protected using semaphore and curr_resource_counter specifies resources available for use at present. The curr_resouce_counter can never be less than zero and more than max counter. So calling ReleaseSemaphore() after reaching curr_resouce_counter greater than max has no effect.

75
Q

What are queued and non-queued messages?

A

Queued messages are those that are placed in a programs message queue by Windows OS. These are then retrieved and dispatched in the message loop.
Messages that are posted to system message queue first. Normally generated as a result of postmessage() call. These are the messages that are resulted from some user action e.g. WM_KEYDOWN, WM_KEYUP etc.

Non-queued messages - Messages that are send to WinProc directly are called non-queued messages. These are generated as a result of call to SendMessage() function

76
Q

In which conditions will you use Structured exception handling and in which c++ exception handling

A

Structured exception handling is used at system level programming where both exception and termination handling is required. Also the structured exception handling gives programmer the opportunity to execute the same instruction that caused exception to occure (EXCEPTION_CONTINUE_HANDLER). Global unwind and local unwind adds great features to structured exception handling.

c++ exception handling is not designed to accept access violation, divide by zero exceptions. Its purely a language feature and should be used in that context only. (MSVC++ exception handling is implemented using structured exception handling so does capture access violating and divide by 0 errors)

77
Q

What is virtual dos machine (VDM)?

A

On 32 bit operating system, all 16 bit applications are executed in virtual dos machine. By default all 16 bit applications shares same VDM (both on win98, 2000). On 2000 you can create separate VDM for each 16 bit application. This will ensure that one 16v application doesn’t play with other 16 bit application.

78
Q

What is the use of Export Keyword in .def file

A

Windows mangles “c” functions if they are using __stdcall calling convention. DLL exporting such function could not be used across different languages. To avoid name mangling put the function name under Export section in .def file.

79
Q

What is global unwind?

A

Global unwinding starts when exception handler returns EXCEPTION_EXECUTE_HANDLER. Global unwind starts before the system begins execution of the code of except block. The system starts back at the bottom of all outstanding try blocks and searches for all try..finally blocks and executes them. If any of such try..finally blocks contains return statement then global unwinding stops and execution resumes at the first statement after except block i.e. except block is never executed.

80
Q

A global variable is defined in an DLL. How this global variable is accessed by a process which loads this dll. Does it required to export this global variable?

A

DLL should export function, variable, classes to be used by its clients. The client can be anyone. The reason is simple. The variable is declared in a DLL, so when DLL gets mapped in the process address space, the process code should know its memory address. This cannot be found out unless the DLL exports it so that it comes in DLL export section.

81
Q

A cdecl function is calling a stdcall function. The caller is crashing immediately when stdcall function returns. What could be the problem. How to solve this problem

A

In c decl stack is cleaned-up by the caller and in stdcall stack is cleaned up by the callee. So when cdecl function calls to stdcall function, stdcall function cleans up the stack while returning and then again caller being a cdecl function goes for stack cleanup resulting in stack corruption. the function pointer used in cdecl function to call stdcall function should be declared as ‘stdcall’ function function means stdcall should appear in its declaration

82
Q

Windows Vista onwards, every program work with standard users rights. UAC enforces this. How to elevate rights of the user to admin level if required. Whats the programatic way to do so?

A

UAC cannot be eleveted silently using code. It can be eleveted at process level only and with uses permission. A dialog box is shown to the user to elevet UAC

83
Q

What are different UTF standards?

A

There are 3 UTF standards for representing characters.

  1. UTF-8 - UTF-8 encodes some characters as 1 byte, some as 2 bytes, some as 3 bytes, and some characters as 4 bytes. Characters with a value below 0x0080 are compressed to 1 byte, which works very well for characters used in the United States. Characters between 0x0080 and 0x07FF are converted to 2 bytes, which works well for European and Middle Eastern languages. Characters of 0x0800 and above are converted to 3 bytes, which works well for East Asian languages. Finally, surrogate pairs are written out as 4 bytes. UTF-8 is an extremely popular encoding format, but it’s less efficient than UTF-16 if you encode many characters with values of 0x0800 or above.
  2. UTF-16- UTF-16 encodes each character as 2 bytes (or 16 bits). However, 16-bits is not enough to represent all characters from certain languages. For these languages, UTF-16 supports surrogates, which are a way of using 32 bits (or 4 bytes) to represent a single character. Because few applications need to represent the characters of these languages, UTF-16 is a good compromise between saving space and providing ease of coding.
  3. UTF-32: UTF-32 encodes every character as 4 bytes. This encoding is useful when you want to write a simple algorithm to traverse characters (used in any language) and you don’t want to have to deal with characters taking a variable number of bytes.
84
Q

How does UTF-16 handles characters that cannot be represented in 2 bytes?

A

16-bits is not enough to represent all characters from certain languages. For these languages, UTF-16 supports surrogates, which are a way of using 32 bits (or 4 bytes) to represent a single character. Because few applications need to represent the characters of these languages, UTF-16 is a good compromise between saving space and providing ease of coding.

85
Q

What is a code point?

A

A code point is the position of a symbol in a character set.

86
Q

What is the difference between macro UNICODE and _UNICODE?

A

_UNICODE macro is used by ‘c’ run time library functions to decide if wide character version of the function should be called or char (i.e. 8 bit) version.

Similarly UNICODE is used by Windows APIs to decide the same.

So if your Windows program is using ‘c’ run time library then it should declare both the macros.

87
Q

Why to use secure string functions?

A

Any function that modifies a string exposes a potential danger: if the destination string buffer is not large enough to contain the resulting string, memory corruption occurs.

For example:
WCHAR szBuffer[3] = L””;
wcscpy(szBuffer, L”abc”); // The terminating 0 is a character too!

Microsoft is has provided a set of new functions that replace the unsafe string manipulation functions such as wcscpy. These functions are defined in StrSafe.h file. _tcscpy_s and _tcscat_s are the examples of secure functions.

88
Q

What functions should be used to convert ANSI string to UNICODE and vice-versa

A

The function MultiByteToWideChar is used to convert multibyte-character strings to widecharacter
strings i.e ANSI to unicode. The function WideCharToMultiByte converts a wide-character string to its multibyte-string equivalent i.e. Unicode to ANSI.

89
Q

How can you determine if a file contains Unicode or ANSI text?

A

The IsTextUnicode() function exported by AdvApi32.dll and declared in WinBase.h can help determine if the text file contained ANSI characters or Unicode characters. The problem with text files is that there are no hard and fast rules as to their content. This makes it extremely difficult to determine whether the file contains ANSI or Unicode characters. IsTextUnicode uses a series of statistical and deterministic methods to guess at the content of the buffer. Because this is not an exact science, it is possible that IsTextUnicode will return an incorrect result.

90
Q

What is a kernel object?

A

A kernel object is simply a memory block allocated by the kernel and is accessible only by the kernel. This
memory block is a data structure whose members maintain information about the object. Some members
(security descriptor, usage count, and so on) are the same across all object types, but most are specific to a particular object type. For example, a process object has a process ID, a base priority, and an exit code, whereas a file object has a byte offset, a sharing mode, and an open mode.
Because the kernel object data structures are accessible only by the kernel, it is impossible for an application to locate these data structures in memory and directly alter their contents. Windows offers a set of functions that manipulate these structures in well-defined ways.
These kernel objects are always accessible via these functions. When you call a function that creates a
kernel object, the function returns a handle that identifies the object. Think of this handle as an opaque
value that can be used by any thread in your process. A handle is a 32-bit value in a 32-bit Windows process and a 64-bit value in a 64-bit Windows process.
To make the operating system robust, these handle values are process-relative. Kernel objects are owned by the kernel, not by a process

91
Q

What are common properties of kernel objects?

A

Common properties of kernel objects are
1. Usage counting- The kernel knows how many processes are using a particular kernel object because each object contains a usage count. The usage count is one of the data members common to all kernel object types. When an object is first created, its usage count is set to 1. When another process gains access to an existing kernel object, the usage count is incremented. When a process terminates, the kernel automatically
decrements the usage count for all the kernel objects the process still has open. If the object’s usage count goes to 0, the kernel destroys the object. This ensures that no kernel object will remain in the system if no processes are referencing the object.
2. Security- Kernel objects can be protected with a security descriptor. A security descriptor describes who owns the object (usually its creator), which group and users can gain access to or use the object, and which group and users are denied access to the object. Almost all functions that create kernel objects have a pointer to a SECURITY_ATTRIBUTES structure as an argument which can be used to define access control.

92
Q

How to restrict access to kernel object created by your process?

A

Almost all functions that create kernel objects have a pointer to a SECURITY_ATTRIBUTES structure as an argument which can be used to define access control. This parameter can be used to control access to kernel objects.

93
Q

How does CloseHandle() work?

A

Regardless of how you create a kernel object, you indicate to the system that you are done manipulating
the object by calling CloseHandle. Right before CloseHandle returns, it clears out the entry in the process’ handle table—this handle is now invalid for your process, and you should not attempt to use it. The clearing happens whether or not the kernel object has been destroyed! After you call CloseHandle, you no longer have access to the kernel object; however, if the object’s count did not decrement to zero, the object has not been destroyed. This is OK; it just means that one or more other processes are still using the object. When the other processes stop using the object (by calling CloseHandle), the object will be destroyed.

94
Q

How kernel objects can be shared across processes?

A

There are three different mechanisms that allow processes to share kernel objects: using object handle inheritance, naming objects, and duplicating object handles.

95
Q

What is a hook?

A

A hook is a point in the Windows message handling mechanism where an application can install a subroutine to monitor the message traffic in the system and process certain types of messages before they reach the target windows.
API Set WindowsHookEx() installs a hook procedure at the beginning of the hook chain.

96
Q

Kernel object inheritance

A

Kernel object handles are inheritable but not kernel objects. Object handle inheritance is applied only at the time of child process is spawned. Handle value is identical in parent and child process.

97
Q

When are the process objects signaled?

A

Process objects are signaled when the process terminates

98
Q

When are thread objects signaled?

A

Thread objects are signaled when they stop running.

99
Q

How a pseudo handle (process or thread) can be converted into real handle?

A

DuplicateHandle() function can covert a pseudo handle into a real handle

100
Q

What are CPU cache lines?

A

CPU cache lines consist of 32 or 64 bytes depending on the CPU and are always aligned on 32 bytes or 64 byes boundaries. When a CPU reads a byte from memory, it does not just fetch a single byte; it fetches enough bytes to fill cache lines. Cache lines exists to improve performance.

101
Q

Does a thread transits from user mode to kernel mode when it goes in wait state

A

Yes

102
Q

What is thrashing?

A

Operating system spends all its time swapping pages in and out of memory instead of running a program.

103
Q

What are different memory manipulating techniques supported by Windows

A
  1. Virtual memory - Use VirtualAlloc() API to reserve or commit a region of memory. VirtualFree() API to free the memory region
  2. Memory Mapped Files (MMF) - MMSs can be backed by a data file on disk or a paging file. APIs such as CreateFile(), MapViewOfFile are used.
  3. Heap - Used to allocate small amount of memory.
104
Q

When is DLLMain is called

A

When a DLL is mapped into a process, its DLLmain() function is called.

105
Q

Can you load another executable in a process

A

Yes. An executable can be loaded using LoadLibray() API to use its resources.

106
Q

What are delay loading DLLs?

A

Implicitly linked but not actually loaded until your code attempts to reference a symbol contained in it. Delay loading DLLs are loaded using compiler option /delayLoad.

107
Q

What is function forwarder?

A

pragma comment(linker, “export/somefunction=DllWork.SomeFunction)

A function forwarder is an entry into the DLLs export section that redirects a functioin call to another function in another DLL.

108
Q

What is DLL redirection?

A

Load the modules from your applications directory first. If the module is not found there then it will be searched in other directories.

109
Q

What are known DLLs?

A

DLLs that OS always look in the same directory are called as known DLLs.

110
Q

What is local unwind?

A

Local unwind is triggered because of premature exit from try block.
Global unwind is triggered when an exception is raised and exception handler with action EXECUTE_EXCEPTION catches it. The global unwind searches all inner try..except..finally blocks and executes them.

111
Q

What all different exception handlers are supportred by SEH

A

The exception filter is a function that can return one of the three values -
EXECEPTION_EXECUTE_HANDLER -
First the global unwind is triggered and completed. Then the except block is executed and exception gets handled. The application control resumes at the first instruction after except block.

EXCEPTION_CONTINUE_SEARCH -
Walk upto the previous try block that is matched with except block and call this previous except blocks exception filter.

EXCEPTION_CONTINUE_EXECUTION -
The system jumps back to the instruction which caused exception to occur and tries to execute it again.

112
Q

How a global unwind can be stopped?

A

Stop global unwind by putting a return statement in the finally block.

113
Q

How a software exception is raised in SEH?

A

using RaiseException() API.

114
Q

What resources are owned by a thread?

A

Windows and hooks are owned by the thread that created the window and installed the hook.

115
Q

What is reply message queue?

A

The thread that called SendMessage() is sitting idle waiting for a message to appear in reply message queue.

116
Q

What are different memory models defined by C compilers

A

Small - one code segment and one data segment.
Medium - Multiple code segments.
Compact - Multiple data segments.
Large - Multiple code and data segments.
Huge - Same as large but with built-in address increment logic.

Near pointers are 16 bit wide and included a default code for data segment.
Far pointers are 32 bit wide and included both an offset and segment address.

117
Q

How errors are returned by Windows APIs

A

When a Windows API detects an error, it uses thread local storage to associate appropriate error code with calling thread. This error code can be retrieved by calling GetLastError() API.

118
Q

What is throughput?

A

The number of jobs completed per unit time is called throughput of the system.

119
Q

What is turnaround time?

A

Turnaround time is the time duration between time of submission of the job and time of completion of the job

120
Q

What is waiting time?

A

The amount of time job spends waiting in a ready queue is called waiting time.

121
Q

What is seek time?

A

Time required to reach a particular track on the disk is called seek time.

122
Q

What is latency?

A

Time required to rotate a requested sector below read+write head is called latency time.