Monday, November 03, 2014

New website for Interview Questions

Here is a new website I've been working on for interview questions for developers: volatileread.com. I have developed it in the same way as stackoverflow where you can vote, post questions and answers. I'd appreciate any feedback on my site. Please feel free to register and post any questions or answers.

Friday, June 12, 2009

HTTP could not register URL http://+:8000/. Your process does not have access rights to this namespace

Quick Fix:

Start->Programs->Accessories->(Rt Click)->Run as Administrator
On the Cmd Prompt Type: netsh http add urlacl http://+:8000/ user=DOMAIN\UserName

Details:

While running WCF services in Windows Vista you may encounter a namespace reservation exception. This occurs because Vista account does not grant administrative privileges to user accounts (even if your account has administrative privileges). Your service does not have the permissions to use the address you have specified for your endpoint. You may get the following exception while running your service:

HTTP could not register URL http://+:8000/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details)

In order to resolve this issue you need to provide the account under which your service is running the permissions to use the address specified for the endpoint.

Run Command Prompt under elevated mode (Start->Programs->Accessories->(Rt Click)->Run as Administrator). On the command prompt type the following:
netsh http add urlacl http://+:8000/ user=DOMAIN\UserName
Domain is the domain name of the account or the machine name if you are running under your local account.

Wednesday, August 06, 2008

Lock on value types again

While doing some code analysis I came across the following chunk of code. If you can, try to figure out the problem.
private static bool _blnCrap = true;

public static void CrapFunction()
{
lock((object) _blnCrap)
{
//Some more shit
}
}
The problem above is the lock isnt effective at all. The first thread comes, casts the bool variable to an object. Now when you cast a value type to a reference type boxing happens, a new object is created on the heap. Now the lock will be placed on this new object. When the first thread is still inside the lock, a second thread comes and tries to obtain a lock on (object) _blnCrap. Again when you say (object) _blnCrap, boxing will happen and a new object will be created on the heap. This object is different from the object created by the first thread and so the thread will be able to obtain a lock and go inside.

Locks cannot be placed on value types. If the explicit cast isnt placed compiler will show an error: <Type> is not a reference type as required by the lock statement.
Why? Go through my earlier post below
Synchronising access against value types

"The web services enumeration components are not available"

I was trying to add a Web Reference earlier today when Visual Studio popped up this error "The web services enumeration components are not available". I was sure I had added web references before without any problems and I do not think there we need to install web services components separately. Then I remembered that some visual studio component earlier had thrown an error and Visual Studio prompted me if I do not wish to load components at startup. I said yes. There the problem started I guess. It stopped loading all the components. to solve this problem just go to Run -> type devenv /resetskippkgs and you are done.

Quick Solution:
Start->Run->type devenv /resetskippkgs

Tuesday, November 21, 2006

Syncronizing access against a value type using Monitors (Why Monitors dont work with Value Types)

Suppose I want to syncronize access against an integer. I naturally cover the code block with the variable I need syncronization on. So I write something as follows:
C#
lock(x) //x is an integer
{
//blah blah code
}
VB.NET
SyncLock x
' Blag Blah code
End SyncLock
Whoa! the compiler throws a syntax error
'int' is not a reference type as required by the lock statement.
What on earth is wrong with the compiler???? Why wouldnt it accept value types.
Before we jump into deep valleys of nitty gritty details I'll just let you know the work around for the busy types. Hmm.. now when I think about it there's no work around. Either use the boxed type of the variable or use typeof(x) as a parameter in the lock statement. (Using typeof(x) will guard the code block against all variable of type int. Sometimes it may create more problems). Wow I bet you must have developed serious doubts about my authenticity as a .NET programmer. But that cannot be demotivating enough for me. I'll carry on....

Digging Deeper

First a litlle bit about reference types. Following diagram depicts what i really thought objects in memory look like:
[Important things first - I made those graphics :) Take your time to appreciate those.]
But I soon realized that there should be more than this to objects that aids thread synchronization which is not present in value types. I was right!!! An object in memory actually looks like following:

This Sync Block is used for syncronization. As this is not present in value types lock(x) returns a syntax error. Btw, why the hell did they put sync block before the actual address??? They outta be more intelligent than me. Any ideas???

Sunday, June 11, 2006

Inside Calling Conventions

Introduction
Hi! In this article, I will try to explain all the calling conventions, their advantages and disadvantages. I will also explain why in C we can pass variable number of arguments and not in C++, and also cover fast call.

Background
Knowledge of assembly coding will be helpful but I will try to explain as much as I can, so don't worry and just relax.

Using the code
So you all must have come across the famous words, "Calling convention", in your career till now. If not, be prepared for runtime error such as value of ESP not saved properly across function calls. So what is all this about calling convention? Don't worry, all your doubts will be cleared. Why C can pass variable number of arguments to a function and C++ cannot? what is fast call? So, ready to go...

We will start by Cdecl calling convention or the C Declaration style. Just have a look at the simple code below:


#include "stdio.h"

int __cdecl Function(int a, int b, int c)
{
return a + b -c;
}

void main()
{
int r = Function(1, 2, 3);
}


Just a simple function and a main. Now, we will start with assembly. For those who don't know assembly, don't worry, it's not a big deal thanks to Microsoft. We will use Dumpbin utility that ships with VC++ to disassemble the code and get the assembly. First compile the code using the command line: cl Cdecltest.c, and the output will be the obj and exe. We will now use the Dumpbin utility on command line:



dumpbin /disam Cdecltest.obj > Cdecltest.txt


and redirect the output to a text file. The output is:

Dump of file CdeclTest.obj



File Type: COFF OBJECT

_Function:
00000000: 55 push ebp
00000001: 8B EC mov ebp,esp
00000003: 8B 45 08 mov eax,dword ptr [ebp+8]
00000006: 03 45 0C add eax,dword ptr [ebp+0Ch]
00000009: 2B 45 10 sub eax,dword ptr [ebp+10h]
0000000C: 5D pop ebp
0000000D: C3 ret
_main:
0000000E: 55 push ebp
0000000F: 8B EC mov ebp,esp
00000011: 51 push ecx
00000012: 6A 03 push 3
00000014: 6A 02 push 2
00000016: 6A 01 push 1
00000018: E8 00 00 00 00 call 0000001D
0000001D: 83 C4 0C add esp,0Ch
00000020: 89 45 FC mov dword ptr [ebp-4],eax
00000023: 8B E5 mov esp,ebp
00000025: 5D pop ebp
00000026: C3 ret



where the first two lines of main are known as prolog and always have Opcode 55 8B EC. While passing the parameters to the function from the main, we are pushing it on the stack. Arguments are pushed from right to left, i.e., push 3, push 2 and push 1, and finally the return address where it has to return after executing the function. Now take a look at the stack diagram:

Initially, the stack pointer is at 98H, i.e., high memory location. As we go on pushing, the stack becomes as shown above. Now the problem begins in calling function. If we pop three entries assuming we have pushed three arguments, then it will pop the return address and then it wont know at what address to return. So have a look at the assembly code of the function call and try to understand how it pops element without disturbing the return address. As seen, it first pushes its ebp (base pointer) at address 80H, then moves the stack pointer in ebp.

Now look at instruction mov eax,dword ptr [ebp+8], i.e., nothing but address 88H i.e., the pushed element 1 then next instruction is add eax,dword ptr [ebp+0Ch], i.e., ebp+0Ch gives second element i.e., 2 and addition of them similarly it gets the third element. Then it pops Ebp at address 80Hi.e stack becomes as in figure 1 and then it returns which is the correct return address i.e., 84H.

This is all the assembly programming we needed. So once again, back to our main discussion. Sorry for diverting you from the track. But now a problem is that the stack is not cleaned, i.e., we haven't popped the three elements pushed on the stack. So someone needs to clean it up, who will it be......????? Back to the assembly... in the main, after the call, there is an instruction add esp,0Ch which cleans the stack 0CH since three elements were pushed. If two elements would be pushed, it will be... you got it right... add esp,08h.

That's it. So in CDecl calling convention, the main one who calls the function has the responsibility of cleaning the stack.


StdCall (std calling convention __stdcall)
#include "stdio.h"

int __stdcall Function(int a, int b, int c)
{
return a + b -c;
}

void main()
{
int r = Function(1, 2, 3);
}


And similarly, let's look at the assembly code: cl stdcalltest.c and then dumpbin /disasm stdcalltest.obj > stdcalltest.txt.

Dump of file StdcallTest.obj



File Type: COFF OBJECT

_Function@12:
00000000: 55 push ebp
00000001: 8B EC mov ebp,esp
00000003: 8B 45 08 mov eax,dword ptr [ebp+8]
00000006: 03 45 0C add eax,dword ptr [ebp+0Ch]
00000009: 2B 45 10 sub eax,dword ptr [ebp+10h]
0000000C: 5D pop ebp
0000000D: C2 0C 00 ret 0Ch
_main:
00000010: 55 push ebp
00000011: 8B EC mov ebp,esp
00000013: 51 push ecx
00000014: 6A 03 push 3
00000016: 6A 02 push 2
00000018: 6A 01 push 1
0000001A: E8 00 00 00 00 call 0000001F
0000001F: 89 45 FC mov dword ptr [ebp-4],eax
00000022: 8B E5 mov esp,ebp
00000024: 5D pop ebp
00000025: C3



As seen from the assembly code, in stdcall, the stack is cleaned by the function called. I.e., ret 0Ch in the last line of the function.

So if you are using a function which is called twenty times, the cleanup code will be placed only once in the function called, if __stdcall is used. But if __cdecl is used, it will be twenty times in the code, i.e., everywhere in main after function is called, and if we have say fifty functions in a file each of which is called twenty times, then the size of the EXE in CDecl will be large. But then what is the advantage of __cdecl... that's something that only C has and not even C++.

In __cdecl calling convention, you can pass variable number of arguments. Remember the ellipses (...). But it is not possible in __stdcall which C++ uses. Let's see how. As seen in __stdcall, the function cleanup code is placed only once in the function and the value is ret no. of args passed. I.e., if three arguments are passed, then 0Ch, which is fixed so we cannot pass variable number of arguments to the function. Whereas in __cdecl, the cleanup code is number of times the function is called, so it is possible to cleanup as it knows the number of arguments passed each time. Got it? Else refer to the above explanation and the assembly code. Also observe the function name mangling in assembly code in both cases. The function name is prefixed by _. But in case __stdcall contains @somevalue, that value is nothing but the size of numbers of elements passed on the stack that has to be cleaned up before returning. So in our case, it is ...yes, you got it right.

For __cdecl, call _Function, and for __stdcall, _Function@12.

Anyways, one more example to clear up things.

Below is the code using __cdecl calling convention and it will compile:



#include "stdio.h"

int __cdecl Function(int a,...)
{
//do some processing with all arguments
return 1;
}

void main()
{
int r = Function(1, 2, 3);
}


Below is the code using __stdcall calling convention and it will not compile:



#include "stdio.h"

int __stdcall Function(int a, ...)
{
//do some processing with all arguments
return a;
}

void main()
{
int r = Function(1, 2, 3);
int x = Function(1, 2);
}


Now last but not the least, fast call. So, let's have a look at the assembly code:



#include "stdio.h"

int __fastcall Function(int a, int b, int c)
{
return a + b -c;
}

void main()
{
int r = Function(1, 2, 3);
}


Microsoft (R) COFF Binary File Dumper Version 6.00.8168
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.


Dump of file FastCallTest.obj



File Type: COFF OBJECT

@Function@12:
00000000: 55 push ebp
00000001: 8B EC mov ebp,esp
00000003: 83 EC 08 sub esp,8
00000006: 89 55 F8 mov dword ptr [ebp-8],edx
00000009: 89 4D FC mov dword ptr [ebp-4],ecx
0000000C: 8B 45 FC mov eax,dword ptr [ebp-4]
0000000F: 03 45 F8 add eax,dword ptr [ebp-8]
00000012: 2B 45 08 sub eax,dword ptr [ebp+8]
00000015: 8B E5 mov esp,ebp
00000017: 5D pop ebp
00000018: C2 04 00 ret 4
_main:
0000001B: 55 push ebp
0000001C: 8B EC mov ebp,esp
0000001E: 51 push ecx
0000001F: 6A 03 push 3
00000021: BA 02 00 00 00 mov edx,2
00000026: B9 01 00 00 00 mov ecx,1
0000002B: E8 00 00 00 00 call 00000030
00000030: 89 45 FC mov dword ptr [ebp-4],eax
00000033: 8B E5 mov esp,ebp
00000035: 5D pop ebp
00000036: C3 ret



In the case of fast call, as seen from the assembly code of main, just one variable is pushed and two are passed using registers. I.e., in the case of fast call, first and second arguments are passed through the register and rest as normal, i.e., on stack. Since registers are used for passing, it's much faster, but only a maximum of two arguments can be passed through registers. Also notice the name mangling, the function begins with @ and has number of arguments passed, i.e., in our case, @Function@12.

A quick review
__stdcall:
Stack Cleaning Responsibility: The called function (i.e., cleanup code only once)
Name mangling: _FunctionName@4 * argumentspassed
Advantages: Small size of EXE


__cdecl:
Stack Cleaning Responsibility: The calling function (each time function is called)
Name mangling: _Function
Advantages: Can pass variable number of arguments

__fastcall:
Stack Cleaning Responsibility: The called function (i.e., cleanup code only once)
Name mangling: @FunctionName@4 * argumentspassed fast calling by the use of registers
Advantages: fast calling by the use of registers

Note
I would like to thank Mr. Sameer Vasani, my team, and my friend Rahul Bhamre from whom I have learnt a lot and is still learning new stuff.

Sachin Sangoi

Pinning Pointers

Consider this situation: You have a well written tested native function which expects an array. You want to pass an managed array to the function. How would you do that? Think... Whatever your ideas are here's a cool way to do that in the new C++/CLI syntax. Use Pin Pointers

Before we understand how to use pin pointers lets give a thought on why cant a native pointer point to a managed location. An easy question. The simple answer to this is if it was allowed then it would work fairly smooth only till GC throws itself into action. During GC cycle compaction of the heap takes place. The pointer now points to some other data even though the location is same.

So it is not allowed for a native pointer to point to a location in the Managed heap. What if there was a way by which we can avoid relocation of the data during GC cycle. In that case our problem would get solved. Here pinning pointers come into picture.


pin_ptr ppC = &arr[0]; //implicit conversion from interior to pin pointer


Now the location of this array wont change in the Managed Heap.

Caution: Creating pin_ptrs interfere with the working of garbage collector. Use them carefully. You should try to allocate them in such a way that they remain in older generations of the Managed heap.

Calling C# assembly functions having same name differing only by case, in VB.NET

I faced this very unlikely problem a couple of days before. I wanted to call a function written in C# from my VB.NET code, but I found out that the coder of the library had not followed Microsoft guidelines for interoperability and had used same name for two functions differing only by case having the same signature. I didn't have access to the C# code, so was helpless as VB.NET does not allow me to use any of these functions. It gives a compile time error:

Overload resolution failed because no accessible ' is most specific for these arguments: : Not most specific

In this case, we need to use Reflection. At least, I could only find this solution. Suppose my C# assembly code looks like the following:



namespace CompTest
{
///
/// Summary description for Class1.
///
public class Class1
{
public string cameLate()
{
return "He came late";
}

public string camelAte()
{
return "Camel Ate Him";
}
}
}


We can call the function camelAte in VB.NET as follows:


Dim CSClass As New CompTest.Class1
Dim ReturnValue As Object
ReturnValue = CSClass.GetType.InvokeMember("camelAte", _
System.Reflection.BindingFlags.Instance Or _
BindingFlags.Public Or _
BindingFlags.InvokeMethod, _
Nothing, CSClass, Nothing, _
Nothing, Nothing, Nothing)
TextBox1.Text = ReturnValue



InvokeMember function used here Invokes the specified member, using the specified binding constraints and matching the specified argument list. You can find more information on MSDN.

To pass parameters, create an array of Object. Insert parameters required to call the function in the array. Pass the array as a parameter in the InvokeMethod function.