A site devoted to discussing techniques that promote quality and ethical practices in software development.

Showing posts with label Borland. Show all posts
Showing posts with label Borland. Show all posts

Sunday, April 12, 2009

Dissection of an amateurish COM business solution

There is a company which should remain nameless specialized in enterprise business application managing inventories, purchasing, work order, etc. the typical business operations. This blog post is to dissect this solution to demonstrate the:
  • superficiality of this company in the COM technology
  • wrong choice of architecture.
The dissection does not require access to source code because they are using COM, a industry wide interop standard that requires publication of the interfaces specification. This post will show you the free tools you need to see the laughable implementation. I will also offer integrator advice on controlling the rogue COM programs in future posting.

Program structure

The actual names of the programs are also altered to save the embarrassment. This program uses executables gratuitously and was first described in my previous post. It has a controller program, much like Windows Explorer, that can launch their business applications. Each business application, fictionally called M100, M200, M135, M500, etc are COM local servers allowing the controller to communicate with it and to allow inter-application communication.

The program uses Delphi3 and this is an important fact as it will become obvious. Naturally, they all have the Delphi's COM Server bug which can be observed using Process Monitor.

Their technical lead/designer knows this much that each application must implement a common interface, called IXyzApplication in order to meet the above stated objectives. But it is shown below that their modus operandi is not only naive and amateurish showing complete lack of understanding of COM but also their developers lack proper training and mentoring. In reality they have failed to meet the objectives to implement a common interface.

To dissect this program you will need to use the free tool called OleView, which is part of Visual Studio of any version or can be download from Microsoft.

The analysis

With this enterprise business application installed, it is time to use the OleView to examine the implementation defects. If you expand the interfaces tab and scroll down until you see the IXyzApplication, you will not be encountering just one entry of IXyzApplication but you will see at least 130+ copies of this interface. If you click on each IXyzApplication, the right hand pane will tell you the server supporting this interface, its type library and the COM identity.

In fact, the reason there are so many IXyzApplication is because each one of them:
  • has unique IID, thus making them unique; the name is only for human consumption and essentially irrelevant.
  • each one of them is supported in their individual business application.
In effect, they should rename the IXyzApplication to IM100Application, IM120Application, IM500Application etc to be precise.

This laughable situation is not caused by the the developer's fault but a management's fault; management has failed to provide technical leadership of sufficient caliber to guide their developers and to review their work. Their technical leaders also fail to provide structural infrastructure to allow their developers to implement this interface in their business applications; their current implementation also publishes unique IXyzApplication interface as well as implementation in each business application.

Obviously, to the management, it does not require much training to use Delphi3 IDE that so easily can produce a COM application with several keystrokes. Wow, could this be the silver bullet that has eluded Frederick Brooks [BROOK]? Don't think so and will be unveiled.

Furthermore, to their untrained technical leaders with only superficial understanding of COM, the Controller can talk to their business applications and that they are all named as IXyzApplication in each application. So isn't that fine? Not quite.

Using the OleView, we can disassemble the registered type library into IDL, Interface Description Language, to see a much clearer definition of the IXyzApplication. Here are the points to be noted:
  • IXyzApplication is derived from IDispatch interface
  • IXyzApplication is declared as dual interface
  • IXyzApplication has distinct guid for the interface.
For the moment we will forget some of the more ambitious ones, which violate more COM practices. Drilling into their COM characteristic further and comparing several IXyzApplication you will also noticed that:
  • The same method name can have different method id's in different business applications.
  • Some IXyzApplication's have different set of methods.
  • Some IXyzApplication has more methods.
  • Some has a different method in a method id that is used by others.
In other words, these developers only believe using the same interface name is all that is required. They obviously has no basic idea of COM and they are poorly served by their incompetent technical lead/architect in not providing a single definition of IXyzApplication with which they can implement it. They have no clue on the concept of implementing an interface and publishing an interface.

Digging around the installation area and using OleView reveals that they appear to have interfaces publishing DLL that they could and should include IXyzApplication there. For some unknown reason they did not. Perhaps that is out of the ordinary task supported by the IDE and that they cannot handle this.

Standing back from this problem, one wonders how the controller can communicate to all these business applications each with a unique IXyzApplication interface? The answer further illuminates their total ignorance of COM.

In order for the controller to work and for business applications to talk to another one via the 'IXyzApplication', they are not using IXyzApplication but using the following technique:
  1. They are actually using dispinterface via the IDispatch interface, the base interface of IXyzApplication.
  2. They are using a language/framework that does not cache the method id.
Reason 1) is supported by the fact that there is only one definition of IDispatch belonging to Microsoft but there are at least 130+ 'IXyzApplication'. In order words their declaration that their interfaces supporting dual is incorrect or at least superfluous.

Even allowing the client/server to be using IDispatch calls, the haphazardly assigned method ids and missing ones would have play havoc to client that caches the method id.

The only reason that their Delphi solution works is because Delphi does not cache the method id at compile time, unlike those using Microsoft Foundation Class/ATL or Visual Basic 6. Using cache id is perfectly acceptable because COM spec demands the consistency in method id assignment and there is only supposed to be one and only one IXyzApplication. Basically Delphi will call IDispatch::GetIDsOfNames() followed by IDispatch::Invoke() to call each IXyzApplication methods.

Using this inefficient dynamic technique ignoring the COM interface specification is the only way to deal with a haphazardly assigned method ids.

While the solution 'works' albeit in a very tightly coupled to a particular tool that happens to use an inefficient implementation, it means that it has completely destroyed the benefits of an opened industry-wide interop standard, such as COM.

It fails to use a more efficient call mechanism, such as v-table call supported by dual interface that the IXyzApplication has adored with. It cannot possibly use IXyzApplication because which one is to be used? There are 130+ IXyzApplication. The management of this company does not understand the fundamental of COM; it is not the name that matters in COM; it is the guid. If the guid is the same, then it must be the same interface regardless what you call it. Their mistaken belief produces such a laughable solution.

Secondly, it fails to support interop in a wider sense supported by COM. Their action prevents their customers from writing custom controller or to interop directly to those business applications in other tools than Delphi; COM is a language and tool neutral interop technology. However, there is a way to do this without using Delphi as a client and that is the subject of a future post.

As a result, the customers are the poor losers in this sad affair. If this software is a car, some form of medicine or financial instrument, I am sure the company responsible for this will be prosecuted for misrepresentation of the facts or producing unsafe product. But in software, this is masqueraded as innovation!

The company has not found a silver bullet; they have only addressed incompetently the accidental part [BROOK] of software building as their product has demonstrated unequivocally.



Frederick Brooks, "No Silver Bullet - Essence and Accidents of Software Engineering", IEEE Computer, April 1987.

Tuesday, March 18, 2008

CodeGear Delphi 2006.Net's TRegistry fails in Framework 2 SP1

An error has been detected when TRegistry.ReadString in Delphi 2006.Net is promoted to run in .Net Framework 2.0 SP1.

The error is the result of coding error in Borland's VCL.Net library code that is manifested into data corruption caused by Microsoft's tightening the compliance rule to conform to Unicode 5 in Framework 2 SP1.

This article will pin-point the exact cause in Borland's code. It is an very common coding error that has not been picked up in code review and the .Net Framework of the past has chosen to ignore that mistake. Thus masking out the coding error.

The VCL bug causes the use of TRegistry.ReadString() to return a string that has an additional Unicode character of value 0xFFFD appended to the end. This is the Unicode's standard replacement character whenever the encoder detects an invalid Unicode Character. The use of this character is the default action in the .Net Framework.

It is worth noting that Microsoft.Win32.RegistryKey.GetValue() for REG_SZ data does not produce this error and is not affected by the installation of Framework 2 SP1.

Let's begin the code review from TRegistry.ReadString(), which can be found in Borland.Vcl.Registry.Pas line 546.
function TRegistry.ReadString(const Name: string): string;
var
Len: Integer;
RegData: TRegDataType;
Buffer: TBytes;
begin
Len := GetDataSize(Name);
if Len > 0 then
begin
SetLength(Buffer, Len);
GetData(Name, Buffer, Len, RegData);
if (RegData = rdString) or (RegData = rdExpandString) then
begin
SetLength(Buffer, Len - 1); // <<--- Line(A) - The mistake. // .... end;
The coding error is located in the SetLength() as indicated. To understand why this is a mistake, we need to refer to the PInvoke declaration for the registry access function RegQueryValueEx(), which is the corner stone for GetDataSize() and GetData().

The declaration can be found in Borland.Vcl.Windows.Pas, line 21,265 and is reproduced in part here:
[SuppressUnmanagedCodeSecurity, DllImport(advapi32, CharSet = CharSet.Auto, SetLastError = True, EntryPoint = 'RegQueryValueEx')]
function RegQueryValueEx(hKey: HKEY; lpValueName: string;
lpReserved: IntPtr; ..... ): Longint; external;
According to MSDN documentation for CharSet.Auto, this declaration causes all strings to be marshaled as 2-byte Unicode strings and that it will be calling RegQueryValueExW variant of the RegQueryValueEx function.

According to the documentation for RegQueryValueEx(), the data returned from calling RegQueryValueExW() for type REG_SZ is a 2-byte Unicode string and the 6th parameter should contain the length of the string
If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, this size includes any terminating null character or characters unless the data was stored without them.
Also worth noting that the unit of this parameter is in bytes and not in characters. Therefore for a 2-byte Unicode string, this value is always even.

Now returning to Line(A) above. Since Buffer is of type TBytes, which is an array of bytes, if one subtracts 1 from the length of Buffer that is even, this will produce an odd number of bytes. The end result is in producing a nonsensical UTF-16 Unicode string, which is expected to compose of even number of bytes. Now, instead of ending with 2-bytes of zeros, the UTF-16 null terminator, the string now contains an odd byte of zero, which is clearly not a valid UTF-16 character.

According to the knowledge base article:
the trailing NULL byte was removed. However, now the NULL byte is converted to the Unicode replacement character.
As a result, a string returned from TRegistry.ReadString() was like this, for example, "C:\Program Files" now becomes "C:\Program Files\xFFFD" or in appearance like this "C:\Program Files�"

In conclusion, the extra character tagged onto the end is the result of Framework 2 SP1 highlighting the programming error in VCL library. As mentioned, Microsoft.Win32.RegistryKey class does not have this kind of mishandling in all versions of framework. It is not a bug in Framework 2 SP1.

If you have Delphi 2006.Net program, it is therefore recommended that you include an application configuration file containing the <supportedRuntime> element that constrains your application to run only in Framework 1 as a safety measure. Apparently this bug has been rectified in Delphi 2007.Net.

Tuesday, October 16, 2007

Post Delphi Studio 2006 installation experience

With the replacement of my old trusty work horse machine, I have to go through the ritual of reinstalling all the software packages that I use on daily basis.

One of them is the Delphi Studio 2006. With the new machine that is relatively clean in terms of LUA conformance it is also a good opportunity to see how well D2006 behaves in LUA. On my previous machine, it seemed fine but I might have been less stringent with the conformance.

As required, D2006 was installed in an Administrator account. This is an interesting fact to remember. It is not in an Administrator console. I actually logged into the Administrator's account to install. The installation went pretty flawlessly.

After that I logged back into my normal account, which is an LUA, things got interesting. With ProcMon and ProcExp configured to monitor BDS.EXE, I was ready to fire up Delphi Studio and here are the problems encountered:
1) During the start up, bds tried to copy "<.Net 1.1 Framework SDK Dir>\bin\lc.exe to the "C:\Program Files\Borland\BDS\4.0\bin" as lc.dll. Of course this is futile as I am only a LUA.

I am just wondering why Borland would want to change Microsoft's License Compiler into a License DLL. Doesn't Borland know that it can late bind into LC.EXE just as easily as LC.DLL by virtue of the CLR assembly probing algorithm coupled with reflection? All you need to do is to specify the type name correctly. But perhaps Borland did an early binding in their lab. Not very elegant in my mind. Is it also ethical to rename a Microsoft executable?

Anyway, realizing BDS is trying to do the impossible, I gave it a helping hand so as to go past this hurdle.

2) Next that showed up on the radar screen was that BDS trying to change the value of this registration item:
HKCR\TypeLib\{F939BACD-3FD5-437A-833F-BA3535A45966}\a.0\0\Win32\(Default)

Of cource this is another futile exercise. I am not allow to write to HKCR! But this issue did not seem to both BDS.

3) Next, with the IDE fully up, I began to test it. It could easily debug a VCL.Win32 HelloWorld application. But a different story when I tried to debug a VCL.Net application. As soon as I pressed the Run menu, it popped up an assertion failure dialog box (could Borland been shipping debug version of their C++ packages?)

Like this:

My machine, prior to installing D2006, has every version of .Net Frameworks installed, include 3.5 as well as all version of Visual Studio. .Net Framework are by design to support side-by-side installation and hence should be able to live in harmony. Pressing OK brought BDS crashing down instantly.

A search of Google brought me into contact with a report of this problem in Borland's Developers Network's Quality Central. You can find my rather less drastic and more .Net correct solution to this problem posted as a reply to the brutal solution offered on the Quality Central.

After the simple addition of a .Net Config file to rmtdbg100.exe, the IDE can then debug .Net application.

Incidentally, if you are building .Net COM component to be used in say Excel, make sure you give Excel an application config file to set the supported run time, otherwise, your component may fail to load because one that loads before you could change the CLR version to become incompatible with yours.

4) These operations did not cause any problem but were observed in the tools. BDS seemed to demand Generic Read/Generic Write whenever it was opening .Net system dcpil, such as System.Xml.Dcpil, etc. When the access was denied for obvious reasons, it then tried to open with Generic Read.

These operations look very strange and highly inefficient. It should demand the lease privilege particularly in a non-installation situation. Very strange. Not only BDS opening DCPIL files like this but BDS did this with other DLLs as well.

5) BDS had trouble executing in an Adminstrative Console. This is one that is constructed from RunAs command with an embedded /Netonly to provide network connectivity. It fired up fine by using the "Run As" from its short cut and from a cmd.

So far, the reason for this misbeviour has eluded me. Since this is the only program that fail to run in my Administrator console, it is not a big deal. One day, the penny will drop and so stay tune.

Saturday, June 23, 2007

Bug reporting - a lesson CodeGear can learn from Open Source

My recent usage of the GNU Win32 port of Grep resulted in my discovery of a bug and in custom with my practice, I filed a report. What happened next is a lesson that Borland/CodeGear should learn from the Open Source community.

Not only did they not whinged, throwing up excuses, calling their user and bug reporter not understanding their 'feature', they digested my bug report carefully and promptly acknowledged that was a genuine bug. Even when Borland's bug has been proven beyond doubt, yet they still refused to fix it.

Within a short time, they posted me a message advising me a bug fixed version is available. Full mark for that.

Contrasting that with CodeGear's Delphi bug reports I have filed over the years, I have never received this kind of acknowledgment and quick response. More disturbingly CodeGear's Delphi product is NOT FREE and yet providing far worse support than free stuff. Hence, price does not equate to provision of support, not even meager support.

People considering CodeGear software needs to remember this before spending your money.

Saturday, June 9, 2007

Different approaches in handling users' bug report

I have used many software libraries and software packages over the years and whenever I discover something that does not agree with the intended usage, I always take the time and effort to develop the simplest scenario to demonstrate the anomaly. Then I will submit this to the developer for comments. Since I am a developer, I know one cannot always be right and if someone can show you a scenario that can duplicate the anomaly, it is a great help as half the work is done to improve the product.

Below are a number of cases of my fault reporting experiences and the vastly different experiences I have encountered. You be the judge who should deserve the wooden spoon.

Possible Microsoft Enterprise Library bug - Range Validation configuration.

Recently, I have decided to use the Microsoft Enterprise Library 3.0 and in particular the Validation Application Block. During my experimentation with using the Configuration Console, I have discovered the console is not behaving logically. After extensive experimentation, I have formed the opinion that the validation process used in the console is faulty preventing me to save the configuration file and that a work around has been found.

So I fired a comment to the forum responsible for the Ent Lib to seek the expert opinion. With speed commensurates with Internet Time, the moderator of the forum recognized a bug and raise a work item. Full mark for their effort.

Something amiss - two minor releases of Gnu Win32 port of grep behaving differently

I am a frequent user of this great tool called grep that is rooted in Unix. Recently, I had to perform some recursive search using regular expression in some C# files. I found a version of grep in my machine that allowed me to successfully locate the lines with this command line:
 grep -R --include="*.cs" -P "^[ \t]+class" *
I looked at my grep and realized it was slightly dated and wondering if there was more recent one. So I searched Google and found the two sites on SourceForge. The GNU Utilities port to Windows (UnxUtils) and the Win32-versions of GNU tools (GnuWin32); not sure why two. To cut the story short, the UnxUtils contains a old version of grep, 2.4.1, which does not have the --include and -P (the Perl Regular Expression) switches.

In the latest version of GnuWin32 version 2.5.1a-1, it has the grep with the required switches. However, it does not function according to the man page. On that site it also has an earlier release, 2.5.1a, and surprisingly, this version not only has the required switches, they function according to the man page.

Seeing these distinct differences in behavior, I duly submitted a bug report. The information provided must be clear enough to indicate something was wrong and the status had been changed and assigned to someone for further investigation. It could mean my usage of the switches combination is wrong too. In that case, 2.5.1a-1 needs to be correct. If my usage is right, and I am pretty sure I am right, the 2.5.1a-1 needs to be compared to 2.5.1a and rectified accordingly.

Problem in Borland's Delphi library.

I must admit that I am not a long time user of Borland's Delphi programming language but in the last 2 years, I have begun reading code and writing code in Delphi - both the Win32 and Delphi.Net, of course including the VCL.Net.

I am also fortunate that I am surrounded by Delphi experts who can either correct my usage or advises me of this 'Delphi specialties'. They have also fed me many interesting stuff and many I have taken on as a challenge to get them fixed as they are clearly illogical.

Many are definitely bugs while others are of their own creation. A samples can be found in this blog for example, Delphi handles COM Server, or trying to change ECMA CLI standard. There are others that are not reported in my blog.

It is particularly interesting to note that the COM problem was first discovered in Delphi 3 and numerous users tried in vain to have this rectified. The support would preferred to argue at length of the classification of this problem than to discuss the technical issues. Perhaps they were not skillful enough to understand.

My discovery actually unearths a possibility that someone in Borland has accidentally deleted the line testing the start up mode and the code still compiled correctly giving Borland an impression of correctness.

They do not see anything wrong when they are not developing in LUA. Thanks Borland for giving me a real life illustration of the danger for not developing in LUA. This may be the same reason why their TRegistry fails too.

Even putting this aside, my code analysis of their code clearly indicates that Borland's developers do not know what is the exception handler and thus have thrown the wrong exception or vice versa. This allows the application to crash catastrophically during start up.

With only 9 lines in dispute and a well described test scenario, they steadfastly maintained that there was no bug. If that is the case, why would an automation server, that is running as a stand alone, thus not requiring to be registered, fail to run in LUA? When cornered, Borland offered all sorts of stupid 'fixes', like using special registration to HKCU hive.

Stubbornness does not fix code. It only gives developers more reason to look down on this product. It gives me indisputable examples showing the poor quality of the product and more convincing argument in product evaluation or elimination. Developers that following my suggestion to address this issue came out smiling without the need to use unorthodox hacks and even considering the laughable work around from Borland.

My blog has documented many other reports of these kind of encounters. Some of the 'incorrect behaviour' are trying to be justified as features. While others the company could not bother to comment.

To be fair, their developers had acknowledged some of my finding, not documented here, to be more than spot on, exploring areas that they had not considered. But that was as far as it went. Hardly called satisfactorily resolved.

A far cry from other more mature and definitely users friendly companies or communities.

I will definitely be monitoring the Delphi 2007 to see if these issues are addressed. If they cannot even admit fault, the first step in fixing any bug, my bet is that the fault will still be there. So if you were considering upgrade, check these issues out first or else you may be getting the same old thing with a new wrapper!

Friday, June 8, 2007

Class libraries not aware of LUA

[This is a reproduction of a message in my old blog. With the imminent release of Delphi 2007, I am really interested to see if they have addressed this and how.]

Many frameworks have provided class wrapper to deal with Windows Registry access and many, including the ATL's CRegKey and Borland's Delphi TRegistry have a problem in dealling with registry access in LUA (Least-Privilege Users Account).

Not that they do not have facility to deal with this but the default security access rights is set too high making unwary developers that do not develop in LUA falling into the pitfall.

For ATL::CRegKey::Open() it is default to KEY_READ | KEY_WRITE and TRegistry.OpenKey uses as its TRegistry.Access which has a default value of the same.

What makes Borland's class not capable in dealing with LUA failure than that in ATL is the return value of these respective member functions. CRegKey::Open() returns the value from ::RegOpenKeyEx(), the raw API, which Borland returns a Boolean which is true if the API returns ERROR_SUCCESS. In so doing Borland has discarded the vital information that can allow the caller to take appropriate action.

For example, when using default security access value, the CRegKey::Open() returns 0x5 for an existing key in HKLM and this means "Access is denied". If the key does not exist and that you have access rights, the return value is 0x2. In the case of Borland's TRegistry.OpenKey(), all it can return is false to indicate if something is wrong. What's wrong is that the caller is unable to determine through the lack of information. Hence in many of Borland's usage, when it fails to gain access to the HKLM with the default access rights, it will simply assumes that the key does not exist and hence performing the wrong recovery routine!

Given that Borland has already published this interface, it cannot change it. At best, it can add a read-only property to allow caller to query it after the operation but this requires code to change. Oops!!! One such Borland's library function that causing me grieve with LUA is the BDE.DbiInit().

I am just wondering if Borland's developer developing their products in LUA or in Admin accounts. From what I have seen, obviously the former.

VCL Form Vs Win Form performance (old posting)

[This a reproduction of a message in my old blog. It is reproduced here to remind me to retest this when the BDS 2007 is released]


There are plenty of noises on the Internet regarding the performance of Windows Forms (WinForm) Versus Delphi Forms but not too many of them are willing to publish any profiler results to back the claims.
While the results published here are not exhaustive, they are repetitive and are here to compare two aspects:
  • How are Vcl.net, Vcl32 and Win form compared to each other on loading a form?
  • Are they sensitive to the number of controls on a form?

The tool I used to profile them is AQTime4 from AutomatedQA, which can be used to profile, Delphi.Win32, Delphi.Net, C#, C++ (managed or unmanaged).

Two applications are developed. One, the Large App, has 1 tab control with 5 tab pages and they contains buttons (47), combo boxes (20), edit boxes (40), rich edit controls (12), and treeview (16). All together 241 controls.

The other is a lot smaller with 1 tab control 5 tab pages and all up 40 controls of similar types.

These applications were developed in Delphi.Win32 and re-compiled to Delphi.Net and then re-coded to WinForm using either Delphi or C# all using Delphi Studio 2006. All these applications did not contain any code other than what was generated by the Form Designer.

Here are the results for the large app:

Large application with 241 controls
Build Type Method and Children Time (sec)
VCL 32 TForm2::Create() 0.16606
VCL.Net TForm2::ctor() 1.20292
WinForm/C# WinForm::ctor() 0.2645

For smaller applications here are the results:

Small Applications with 40 controls
Build Type Method and Children Time (sec)
VCL.32 [No Debug Symbols]
VCL.Net TForm1::ctor 0.53663
WinForm/Delphi TWinForm12::ctor 0.21640

Profile results on two real applications one using Delphi3 and the other Delphi2006 produced data in agreement with the trend but with a much severe ratio because they contain actual code that increases the load time further.

From these data we can conclude:

  1. VCL.Net is slower than VCL.Win32 and analysis of the call stacks in these two technologies revealed a lot more methods calls were involved in VCL.Net as compared to the lean VCL.32, even for reading form resources.
  2. VCL.Net is also slower than WinForm, regardless of the language used to program it.
  3. VCL.Net is more sensitive to the number of controls on a form as compared with WinForm, which is essentially flat. The ratio of VCL.Net : WinForm is 2.5 : 1 for a form with 40 controls as compared with 4.5 : 1 for one with 241 controls. Hence this means the load time of VCL.Net is sensitive to the number of controls on the form.
  4. The WinForm is relatively insensitive to the number of controls on the form.

So here you are.

Sunday, April 29, 2007

Passing array of items in Delphi.Net - revisit

I have blogged about the worrying result of passing array of items in Delphi.Net using the "array of" type.

Apparently, there is another way to specify array of items to a function, that generates the same parameter type in IL code but causing the compiler to generate slightly different code inside the function, all without warning the user.

The technique is akin to C/C++'s use of typedef, except that in C/C++, typedef does not cause the compiler to generate different code. It is merely a form of short hand notation.

Not so in Delphi.Net.

The different form of specifying the array of items in a function's argument is by means of a type alias like this:

type
TArraryOfString = array of String;

procedure TSample.DoSomething(ar: TArrayOfString);
begin
// ....
end;

This form of declaration instructs the compiler not to overwrite the ar argument with its cloned copy. If one examine the IL code for the method's signature, it is identical to that of using "array of String" syntax. This generates identical code to that using any non-Delphi.Net languages.

This is a dangerous practice because both Delphi.Net Pascal syntax generate the same method signature in IL but with very different code in the function body and the developer is not told of the difference. The developer cannot see and feel any difference. The only time a developer can feel anything is different is when one tried to pass a nil array to the function. It is even worse if that assembly is to be used with other .Net assembly which can result in difference in behaviour, see my previous blog.

The morale of the story: Do not trust any assembly that is developed in Delphi.Net with array of parameter. Always check the code, with the help of Lutz Reflector or ILDasm, to determine if the argument has been overwritten with its clone. No non-Delphi.Net language will generate code like that without explicit action from the developer.

You can test this by passing a nil in the argument where you see array of in a method. If you get an NullReferenceException on entry to the method before your source code, you can bet your dollar that if is a Delphi.Net assembly using "array of" parameter.

Borland is more interested in Delphi.Win32 compatibility than to produce a compiler that generate safe, well behave and ECMA conforming assemblies.

Tuesday, March 27, 2007

More on Delphi.Net's handling of "array of" parameter.

I have raised a concern and claimed that Delphi.Net generated CLI incompatible assembly to handle method that contained "array of String" in my previous blog.

In this message, I would like to make one correction that I made in that blog, though it does not invalidate the claim, to set the record straight and to report the complete analysis of the issue in handling "array of" in Delphi.Net.

The correction I would like to make is in relation to the Array.Clone() in which I allegedly and mistakenly claimed that it would invoke the ICloneable.Clone() and would perform deep copy.

System.Array.Clone() does not use deep copy. In fact according to the standard documentation, System.Array.Clone() performs only shallow copy. This operation will be proven to be Delphi's Achilles heel in its naive attempt to prevent code from changing elements of an array when ECMA clearly permits.

It will be shown that Delphi.Net's naive implementation restricts the design of a method of allowing null array of anything to be passed.

Passing an array of immutable objects

This is actually a generalised case of "array of String" because System.String is an immutable class. The situation is no different from that reported in my previous blog.

In dealing with an array of anything, Delphi compiler immediately generates a call to the Array.Clone() to overwrite the incoming array with its cloned version in vein attempt to prevent changes propagating back to the caller upon returning. The following IL fragment confirms this:

.method public newslot virtual final instance
void PlayWithData(string[] ar) cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor()
.override [CloneDemoSupport]LMar.CloneDemoSupport.IDataChanger2::PlayWithData
.maxstack 6
.locals init (
[0] int32 n,
[1] int32 num,
[2] int32 len)
L_0000: ldarg.1
L_0001: callvirt instance object [mscorlib]System.Array::Clone()
L_0006: castclass string[]
L_000b: starg.s ar
So any user code will be accessing this cloned version. The minute the clone is made, each element is referring to the same address since shallow copy simply duplicates the object reference (ie. the address).

However, because each element is an immutable object, its state cannot be changed unless a new object, with therefore a new object reference, is created. But this object reference is now stored in an array that is inside the function, a la an auto-variable of array type. Its value will not be passed back to the caller since only the address or reference to the array is pushed onto the stack in passing to the function.

In this scenario, Delphi.Net is successful in preventing changes made in the function from propagating back to the caller. In so doing, it has damaged the ECMA-CLI compatibility because such an assembly produces a different behaviour that a conforming one.

Passing an array of mutable objects

Previously we have considered an array of immutable objects and have found that Delphi.Net is successful in creating ECMA-CLI incompatible methods. How successful is it in dealing with an array of mutable objects?

Once again, we have discovered that Delphi.Net does not distinguish this and blindly invokes the Array.Clone() as shown here:
.method public newslot virtual final instance
void PlayWithData(class [CloneDemoSupport]CloneDemoSupport.Foo[] ar) cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor()
.override [CloneDemoSupport]CloneDemoSupport.IDataChanger::PlayWithData
.maxstack 5
.locals init (
[0] int32 n,
[1] int32 num,
[2] int32 len)
L_0000: ldarg.1
L_0001: callvirt instance object [mscorlib]System.Array::Clone()
L_0006: castclass [CloneDemoSupport]CloneDemoSupport.Foo[]
L_000b: starg.s ar

If the function does not attempt to replace each element with a brand new element, one can use the class' methods to change the state because by definition of mutable class, the class supports methods to change the state.

Since the object's reference is not changed in the cloned version, it is now addressing the same object as that held by the caller. In so doing changing the state of that object inside the function is the same as if the caller is changing the state of the same object.

In this usage, Delphi.Net's attempt to prevent method from changing the array fails and the Array.Clone() operation is superfluous wasting CPU and memory.

It can only be successful when one replaces an element with a brand new one.

Hence depending on implementation technique, Delphi.Net can produce assembly that sometimes conforms to ECMA-CLI specification while other time it becomes incompatible. This kind of inconsistency is not acceptable.

Array of any parameter is not allow to receive nil in Delphi.Net

If you examine the above listed IL code fragment, it becomes obvious that any Delphi.Net method having a "array of" anything parameter is not allowed to pass in a nil (or null in C#) array. The designer has no choice!

The reason is that if an array is nil, calling its Clone() method will cause NullReferenceException to be thrown.

In fact, we encountered this situation in practice but at that time we naively trusting Delphi.Net compiler to be doing the right thing. Now we realise that it is due to its naive implementation. The bug was made harder to track down because the exception pointed to none of the user code but to the method's entry.

For all these problems, Borland/CodeGear should reconsider its folly in trying to make Delphi.Net, which is governed by an ECMA standard, to be compatible, without consistent success I may add, with something proprietary! It is sheer madness.

Given Borland/CodeGear's pass history in addressing their bug, I doubt Delphi.Net will be corrected. Hence anyone contemplating of developing .Net solution should take these bugs into consideration.

Monday, March 19, 2007

Delphi.Net generating .Net incompatible call convention for array of parameter

Delphi.Net in Delphi 2006 generates IL code that render the .Net incompatible call convention for methods with array of any type parameter.

For example, if one implements a method like this:

type MyDemo = class( System.Object, IDoSomething )
public
procedure PlayWithData( data : array of System.String );
// ....
end;
where the interface IDoSomething is specified in a different assembly in C# as follows:

public interface IDoSomething {
void PlayWithData( String[] data );
}

In Delphi.W32 language the data parameter thus specified is a non-var parameter and hence it tries to implement the C++'s "const object" semantics preventing the callee from changing the content. That it is the address of object is passed by value and the content is then protected from bring modified.

In C++, this protection is enforced via const methods but in Delphi there is no way to specify a const member functions/procedures. So it is kind of half-baked adoption. In C++, the compiler ensures that only const member functions can be used to access const objects.

In .Net world there is no support for const object in parameter passing. If the parameter is not specified and if the object is a reference object the ECMA standard says (12.4.1.5.1):
For built-in types (integers, floats, etc.) the caller copies the value onto the stack before the call. For objects the object reference (type O) is pushed on the stack.
Therefore, if someone passes an "array of String" to the PlayWithData(), .Net permits the callee to change any element in the array. The only thing .Net does not permit under this condition is for the function to replace the object reference on the stack upon returning from the function.

In fact, if the parameter of type Foo, the callee can change the state of Foo with any methods the callee can access. There is nothing the caller can do to prevent callee from changing it other than passing a copy to the callee.

OK. Now comes the crunch time. In Delphi.Net, the compiler generates code in clear violation of this call convention. If one examines the code generated in PlayWithData(), the first thing Delphi does is to emit code (in pseudo-code style) like this:

data := (data.Clone as String[]);

In other words, before anyone is allowed to deal with the array, the function's code is actually dealing with a cloned version of the array. Hence anything you do to the array element will be discarded by the function upon function exit.

Using a cloned version inside the function clearly will upset the expected behaviour of any .Net assembly because of the lack of const control in the parameter passing. Whether it is good or bad is not the debate in this blog message. Delphi.Net emitting code like that inside the callee will produce incompatible assembly because there is a published ECMA standard governing the convention.

It may be perfectly logical to do that in Delphi.32 where there is no standard at all. But now the world is different.

In fact, this standard actually forces C++ code to disobey the ISO C++ standard when code is compiled with /clr switch when it comes to the treatment of virtual function call convention in the Constructor and Destructor.

Hence it is wise for Delphi to toe the CLI line rather than creating incompatible assemblies.

This means that C# implementation of IDoSomething can result in different behaviour of that using Delphi.Net. This clearly violates ECMA standard introducing incompatibility.

Not only that, such parameter passing convention can result is memory and CPU wastage because of cost of cloning an array can be very high if the array is an array of some objects with deep object model. Remember ICloneable.Clone() is a deep copy function. Not very smart!

For example implementations a swap interface in Delphi and C# will resulted in totally different behaviour. In Delphi.Net, a swap method will require by-ref parameter passing, while C# can be done with a by-value passing.

One should not use By-ref parameter passing convention for this usage because (12.4.1.5.2):
By-ref parameters are the equivalent of C++ reference parameters or PASCAL var parameters: instead of passing as an argument the value of a variable, field, or array element, its address is passed instead; and any assignment to the corresponding parameter actually modifies the corresponding caller’s variable, field, or array
element....

Passing a value by reference requires that the value have a home (see §12.1.6.1) and it is the address of this home that is passed.
In essence, home is defined as (12.1.6.1):
The home of a data value is where it is stored for possible reuse.
Since the function is not asked to redefine a new array of string. It merely allowing it to change any or all of the elements in-place as permitted in ECMA standard and hence the use of pass by-value is correct.

At the moment, I have not explored this parameter passing conflict between Delphi.Net/Pascal and that in ECMA-CLI with other parameter types. But this will be reported in another blog once I have done sufficient investigation.

For the moment, be careful when you are implementing interfaces specified by others and for users of assembly to beware of using assemblies developed in Delphi.Net language. Delphi.Net does not follow the ECMA standard and this can cause integration problem.

Could this be another example of bastardisation of CLR?

This issue is actually more thorny to Borland than their special treatment of assembly accessible member because in that situation Borland uses the Delphi Compiler to restrict Delphi's private member to behave like CLR private when accessed outside the unit but with an IL assembly access qualifier. In that situation, one needs to use their compiler to compile Pascal code and hence they can control this kind of strange behaviour - until they support netmodule.

But in this situation it involves calls to and from any .Net assembly out of the control of Borland's compiler!!

Friday, March 16, 2007

Nearly become another victim of Delphi.Net's feature

Ever since my discovery of Borland's infamous bastardisation of CLR, I have become totally distrustful of the IL code generated by Delphi.Net compiler. My paranoia is not unfounded. Now I will not accept anything from the Delphi.Net compiler without checking them with Lutz Reflector.

The other day as I was developing our own Form Creation code that replaced the need to have compile time construct demanded by

TApplication.CreateForm()

I nearly became a victim of the infamous Delphi's feature disguised as static linkage in .Net.

I got D2006's wizard to create a VCL.Net application project so that it can become a runner using my Delphi class to perform the routine

Application.CreateForm()

where the parameters came from either the configuration file, command line or some other means removing the need to use the name of the type etc. by a call like this:

FormLoader.CreateForm( assemblyName,
unitName,
formName,
formVariableName );
So when I removed the customarily generated start up form as it would be supplied in another package, that action took the reference of Delphi.Vcl and others from the list of referenced assemblies.

When I added a unit to the project and began to use Vcl artefacts in that unit, I did not change the project's references list. The uses statement needed to successfully compile the unit, forces these Vcl types and their supporting types to be transferred into this executable.

Thanksfully my distrust of Borland's output insisting on being validated by Lutz Reflector paid off.

So my next challenge is to develop an automated tool to catch this kind of stupid act.

The recommendation to anyone using Delphi.Net, check your output with Lutz Reflector before each successful compilation! It is a wicked 'feature' only its creator would love it.

Monday, March 5, 2007

Wasting a whole week because of some "Borland feature"

Late last year, by accident I discovered this "Borland feature" whereby Delphi.Net compiler will suck the type and all its necessary supporting types from one assembly and dump them into the assembly you are referencing it, if you do not declare the depending assembly in the project.

One respondent to my blog said:
This is a common mistake that many people make, so don't feel bad. Let me explain. When you referenced the Borland.Vcl.Forms unit and did *not* reference the Borland.Vcl.dll assembly, you linked into your application a new and distinct copy of Borland.Vcl.Forms and all the types therein.

This same exact scenario is possible using C# simply by including the same class into to two different assemblies or in an assembly and an application.
This sounds too illogical as one cannot compare source file binding as in C# to one that transfer chunks of IL code from one assembly to another in complete disregard to the ECMA-CLI specification in relation to the definition of type.

Perhaps Borland/CodeGear can post some example how I could achieve this without source file in C#.

Anyway, I then outlined a number of scenarios that this "Borland feature" will get developers into deep trouble.

I have unfortunately (but fortunately for Borland) that I missed a few. My colleague, a Delphi programming veteran of more than 10 years, fell into one that I did not reported and it took 2 developers one whole week to unravel this mystery.

In the end, the trusted Type.AssemblyQualifiedName confirmed the minefield.

The scenario was compounded by another Type-dropping bug. The .Net architecture we tried to realise involved a number of assemblies (some are packages while others are executable assemblies being use as if they are dll assemblies).

This Type-dropping bug for some reason causes the types to be rammed into the assembly referencing the types via the Delphi Metadata as oppose to the IL metadata. Lutz Reflector confirmed the bug had discarded the expected types.

Because Borland's relying on Delphi metadata as opposed to IL metadata, Delphi.Net compiled and produced assemblies. But at run time, CLR ruled the world and the assemblies thus produced bite the dust.

All without informing the user of this wonderful feature during compilation. This stealthiness is mainly my complaint as Borland is free to add whatever it sees fit to violate ECMA creating .Net incompatible assemblies. It has lots of warning about platform depending features being used.

But it must also allow and in fact encourage the user to choose to comply with ECMA so that what one produces will play well in the .Net world. Their compiler does not have a switch to turn this feature on or off.

This kind of stupidity, which benefits very few, caused 2 senior developers' one whole week and I am sure there are many other victims like me. We knocked up a C#/VS2003 solution that mimicked the architecture in less than 15 minutes to confirm the architecture was sound.

Of course VS2003/C# does not have this Type-dropping bug. I could as well use C# Builder to perform this validation check. It is not a VS verse C# Builder contest.

One of the alleged benefit of this "Borland feature" is to allow developer to choose how to deploy the application - one executable and a bunch of DLL's or all in one.

While I do not dispute this alleged benefit in Delphi.W32 land (there is no standard of any sort in that area), doing this in CLI is not only wrong, in clear violation of ECMA standard, but also totally unnecessary.

The reason is that you could either use ILMerge or Borland's own version DILMerge. It is better for Borland to discard this dangerous practice, to promote the use of these tools and to encourage Delphi developers to write proper .Net assemblies.

Bug in Delphi.Net in handling class function of Char

Every time, when I tried to do some .Net programming in Delphi, I often run into compiler and/or runtime bug by Delphi.Net (D2006) and it is getting to the annoying point. I must have missed something. Should I simply program Delphi as if .Net does not exist? If I do that would I have better experience? Weird!

I did not discover this bug but I was asked why one needs an object instance to use Char's class procedure or function (in C#, they are known as static function or in UML, they are the classified function).

At first, I did not know the answer thinking that Delphi.Net may be using TChar or something like that. On deeper investigation, there is no such type in Delphi.Net.

So I cooked up a sample application so that I can examine the IL code it generates - very important when dealing with Delphi.Net output. As previously blogged, while Borland can spin its own flavour, but ultimately at run time, it has to obey the CLR.

System.Char in .Net is a structure containing mostly static methods and by definition these methods can be accessed without the need to use an object instance.

The following code fragment illustrates the compiler bug:

00000001 var
00000002 c : System.Char;
00000003 cc : Char;
00000004 b : system.Boolean;
00000005 begin
00000006 c := 'a';
00000007 cc := 'b';
00000008
00000009 Console.WriteLine( 'Is it a Char? ',
00000010 System.Char.IsLetter( c ).ToString() );
00000011 Console.WriteLine( 'Type of cc is {0}',
00000012 cc.GetType().AssemblyQualifiedName );
00000013 Console.WriteLine( 'Type of Char is {0}',
00000014 Typeof(Char).AssemblyQualifiedName );
00000015 Console.WriteLine( 'Char is {0}', cc.ToString() );
00000016 // b := Char.IsLetter( 'b' );
00000017 end;
Here is the output from the above code fragment:

Result:
Is it a Char?
Type of cc is System.Char, mscorlib, Version=1.0.5000.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
Type of Char is System.Char, mscorlib, Version=1.0.5000.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
Char is b
If you uncomment Line 16 above, the code fragment will not compile complaining that it needs a object reference. Lines 11 & 13 clearly shows that Delphi.Net's Char is simply System.Char and hence it should allow the syntax in Line 16 to be used.

Insisting on having a object reference just to use static method is just plain wrong!

Another tip for using Delphi.Net, when in doubt, always print out the Type.AssemlyQualifiedName as Delphi.Net has a habit of giving you this Borland Special Treatment.

As my colleague said, Char is one of the most basic thing in any programming language, why can Borland handle this without error? I am not a Borland employee and I do not have an answer for that other than to tell him that it is another Delphi.Net compiler bug.

Tuesday, February 20, 2007

Delphi.Net Bug - Discarding unreferenced types

I have used compilers and languages for a long time and it is the first time that I have encountered a compiler (Delphi 2006) that actually throws away public types from not only .Net executables but also packages.

Discarding from an executable is kind of understandable because Borland simply extends the same assumption they used in Delphi.W32 to Delphi.Net, admittedly very foolishly and ignorantly. Borland probably does not realise that one can load an executable assembly in much the same way as a DLL assembly.

To see this, you can get the IDE wizard to generate say a VCL.Net Form application. Anywhere in a pas file, create a type in the interface section and build it.

Then examine the final product with a Lutz Reflector and you will find that Delphi has discarded this type. I suspect that Borland only discards the IL metadata of this type, the one that the Reflector and System.Reflection depends on but keeping them in Delphi's metadata.

In other word, Delphi.Net is producing dll for Borland environment only.

To retain this type, you need to create a dummy variable of this type in the implementation section. Now you will see this type being retained.

What is insane of Borland is to discard public types from a package? Public type in a DLL is meant to be used by another DLL or executable and so how could Delphi know that no one is going to reference this type and is safe to discard them?

My discovery has proved that Borland has made very unsafe judgment bordering on insane.

This discarding public types bug is the root cause of Delphi not generating correct IL code.

Saturday, February 17, 2007

A Delphi.Net IL generation bug

A Delphi.Net IL code generation bug has been discovered that can mislead non-Delphi.Net assembly. This is case that shows that Delphi.Net is generating assemblies that not only use CLR metadata but also Delphi.Net metadata, which is unknown to any CLR compiler.

Here is the structure that demonstrates the bug.

I have a Delphi.Net (Delphi 2006) package, called PackageA, which contains UnitA that contains an interface IA. It is irrelevant what method IA prescribes but for argument sake, let's say if specifies a method called SayHi() like this.

unit UnitA;

interface

type IA = interface
procedure SayHi();
end;

Then we have a second Delphi.Net package, called PackageB, which contains a UnitB that contains IB as follows:

unit UnitB;

interface

uses UnitA;

type IB = interface( IA )
procedue Yell();
end;
Everything compiled and linked provided that you have defined the references correctly. Now let's consider PackageA.dll and PackageB.dll as kind of interfaces publishing assemblies and we then implements the following concrete class that implements IB in C#:

using namespace UnitB;
public class CSharpClass : IB {
public void Yell() { Console.WriteLine( "I am yelling" ); }
};
When I used VS2003 to develop this and pressing the tab key after typing IB the IDE only added the implementation of Yell() method. I was puzzled.

Even more bizarre is that that assembly not only compiled and built but it also runs!

I then check the PackageB.dll with Lutz's Reflector and to my horror, I cannot see the base interface of IB and this explains why the C# class compiled and built.

Digging this further I disassembly the IB in PackageB and this is the IL code Delphi.Net generates:

.class interface public abstract auto ansi IB
{
.custom instance void .ctor(string) = ( ...... ) // ...
.method public hidebysig newslot abstract virtual
instance void Yell() cil managed
{
} // end of method IB::Yell

} // end of class IB

No wonder the C# only requires to implement just Yell(). I am wondering will this make any difference if I implement a concrete class in Delphi.Net just like the C# class.

To my astonishment, my class

type MyDelphiClass = class( System.Object, IB )
public:
procedure Yell();
end;

did not compiled and was complaining about the need to implement IA.SayHi() and the need to include UnitA.

According to the IL code of PackageB.dll it does not contain any IL code of the base (required interface) of IB, where does Delphi get the information. The only conclusion one can draw is that Delphi.Net is not playing by the rule properly again! It is digging into its Delphi metadata rather than relying purely on CLR metadata.

According to ECMA-335 CLI standard Partition II, 12.1 this is what it says:
Interfaces shall declare that they require the implementation of zero or more other interfaces. If one interface, A, declares that it requires the implementation of another interface, B, then A implicitly declares that it requires the implementation of all interfaces required by B.

Now if PackageB.dll is rewritten in C# or even VB.Net, it would generate the following IL code for the interface IB:

.class interface public abstract auto ansi IB
implements [UnitA]UnitA.IA
{
} // end of class IB
Note that now IB specifies that it requires IA unambiguously.

You may ask what is the big deal when the final concrete class's class IL code is the same. Yes, that is so provided that you are using Delphi.Net throughout and that you are not using Reflection. This is not .Net!

If you use reflection to examine PackageB.dll for IB, you will discover that:
# typeIB.IsInterface is true
# (typeIB.GetInterfaces()).Length = 0

This means Delphi.Net is generating wrong IL code misleading the user of that assemblies.

Digging this further, I discovered that the missing IA from interface IB is caused by the now infamous symbol tossing bug. Delphi.Net has this bug that when it detects no one references a symbol - be it in a package or an executable application, the compiler simply tosses it away.

The only way to keep them is to litter your program with variables of the type you want to keep. This not only promotes dangerous trap for maintenance worker but also being stupid particularly in a package. By definition of the non-.Net world, any public symbols in a package is for someone outside to use. In .Net, executable assembly is being loaded just like a package. So how can the package foretell no one outside the package is using it and then tossing it away.

Either way, it is a compiler bug that does not generate CLI conforming code. Beware when you are planning to migrate to .Net world in Delphi. You could be producing solution that you, in your all Delphi.Net solution, works fine but your customer using your public artifacts to extend finding their assemblies not working.

Tuesday, December 12, 2006

A Borland feature or bastardation of CLR? Continue...

Further to my previous blog questioning the wisdom of this 'feature', I have adjusted the demo and test out some of the scenarios mentioned.

Here I want to clear up a few things and to posit that this 'feature' creates more trouble than is worth.

I have removed the use of any C# assembly in my demo as it is always safer in highlighting problem in Delphi.Net to leave out C#.

Delphi.Net prevents one to use static linking when building DLL package (Delphi's term for .Net Class library) and only allows VCL.Net application to use static linking.

I will show below that while this is a good move but it will still create a confusing situation and that the compiler should have a switch to flag missing referenced assembly when building application.

It is worth noting that the normal CLR probing algorithm will look for this type "MyDemoLib.MyClass, MyClassLib" in MyClassLib.dll, MyClassLib\MyClassLib.dll, MyClassLib.exe and MyClassLib\MyClassLib.exe before it throws a type load exception, in the absence of any PrivateBinPath specification.

In other words, as far as loading a type is concern, it does not matter if the type is packaged in a DLL or executable assembly. I therefore argue that because of this added flexibility, Borland's porting of their static binding from VCL32 to VCL.Net not only creates an assembly in violation of ECMA-335 but also prevents the assembly from being exploited fully. This will be demanded below.

Moreover, Delphi.Net's prevention of DLL Package from using static binding while permitting application to use static binding destroys the symmetry that is part of CLR standard as demonstrated in the CLR Probing algorithm.

Incidentally when a type is loaded from a Delphi.Net executable, the initialization section in the DPR is completely by-passed. Using .Net executable assembly as a stand alone as well as publishing features that others can load, as an assembly, saves one from distributing executable as well as dll assembly. It also allows one to unit test types inside an executable without having to package them as DLL assembly.

At the moment, Delphi 2006 does not support adding a reference to an application or application project to another .Net project and hence any runtime interaction has to be done using late binding using technique such as System.Activator.CreateInstance(). Visual Studio 2005 is the only one that supports this. So you can effectively directs a VS2005 project to reference a VCL.Net application to use the type inside. In fact, this capability has been exploited to construct NUnit assembly to unit test types inside Delphi.Net application.

Because Delphi.Net/Pascal does not have qualifier to restrict types declared in the interface section to have CLR assembly visibility, all those types, that have to be declared in the interface section so that they can be accessed by types in other units, are free for anyone to use and this makes unit test very easy but creating a very loosely control design in .Net.

Now let consider some scenario.

App1.exe (dynamically linked) using types in App2.exe (statically linked)
This situation will prevent types that depends on VCL in App2 from being used in App1 for reason disclosed in my previous blog.

App2.exe (static bind) using types in MyDemoLib.dll
While Borland tries to make their DLL package to conform to the standard CLI, the MyDemoLib.dll is now prevented from being used in App2 because the above situation would result in two sets of distinct VCL classes.

I suppose in Vcl32 world, one cannot use types in an executable the same way as in .Net supports and as a result, the IPC mechanism insulates the difference.

I am also wondering why Borland or CodeGear prevents DLL Package from using static linking. In Win32, DLL is allowed to use either static or dynamic binding. If Borland is to maintain compatibility with Win32, it should support static binding in DLL. May be VCL32's dll does not have static linking.

As shown, because of the flexibility of the CLR Probing algorithm that does not distinguish DLL assembly from executable assembly as far as type loading is concern, the support of this so-called static binding in Delphi.Net gains nothing but creating compatibility issues for assemblies generated by Borland and ignoring the ECMA-335 standard.

Wednesday, November 29, 2006

Unsafe to use TApplication.OnMessage in VCL.Net

Recently, I have been called to investigate some strange problem that causes program to misbehave.

To cut the long story short, it turns out that their application depends on the dispatching of TApplication.OnMessage event. If this is disturbed their program misbehaves.

TApplication.OnMessage is part of the Borland VCL framework. So how can a framework be so fragile to be disturbed?

My investigation led me to the bowel of the message pump of Borland's VCL and this looks like this in pseudo code:

TApplication.ProcessMessage()
if PeekMessage( ...., PM_REMOVE ) then
begin
if Assigned(FOnMessageHandler) FOnMessageHandler( ..... );
Do some other processing;
TranslateMessage( ... );
DispatchMessage( .... );
end;
This is the only place that the OnMessage event is fired and this is the weakness of the VCL framework. Why?

If you do not call TApplication.ProcessMessage() but instead using their Windows unit's GetMessage(), TranslateMessage() and DispatchMessage() (which are mapped down to P/Invoke using the Win32 API), you can prevent OnMessage being fired and yet your Windows messages are still correctly dispatched.

For example, if you either in your Delphi code or in some managed or unmanaged (for example a COM component), introduces a modal loop like this:

     while someFlag || GetMessage( .... )!= -1
{
if ( msg.message == ..... )
break;
else
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
Using standard Win32 API constructs that are commonly used by non-Delphi developers would immediately defeat the VCL's framework with respect to the OnMessage dispatching. To avoid this you must call TApplication.ProcessMessage() but even then you still cannot prevent other component from interfering with the VCL.

As said, this could be introduced by calling Win32 API that introduces a modal loop like a message box, or someone's code that has been designed with no knowledge of VCL. Such harmless usage immediately rendering that component incompatible with VCL or render your application's dependency on this feature useless.

This highlights the fragility of the VCL framework.

So the advice is that do not rely on TApplication.OnMessage(). Furthermore this event allows you to steal messages because it is called before the message is dispatched to the rightful owner.

A Borland feature or bastardation of CLR ?

A recent chance development of a .Net prototype solution took me face to face with a ugly finding of fiddling of .Net/CLR. Fiddling other's structure or framework is not new to Borland as reported elsewhere but this surpasses all I have seen.

Let's describe the structure of my prototype leading to the discovery of this damaging technique.

I have a Delphi.Net VCL Form application, MyApp.exe, which uses a VS/C# assembly in which one finds a factory object. Because of a Delphi 2006 (D2006) internal compiler bug, this .Net assembly cannot reference any Borland assembly directly. If this assembly references any Borland vcl assembly, you cannot directly reference this assembly in a Delphi VCL package (Delphi's term for DLL assemblies). Hence this factory object, FormFactory, uses Activator.CreateInstance() to dynamically creating Delphi VCL.Net forms from a number of Delphi.Net packages directed by some policy. The factory returns System.Object to the caller.

These Delphi packages contain VCL.Net forms and that they declare references to Borland.Vcl.dll which provides the type Borland.Vcl.TCustomForm, the base type of the forms in these packages.

In MyApp.exe, it has a reference to my factory assembly but it does not have a reference to Borland.Vcl.dll and yet I can compile code like this:

obj := FormFactory.CreateInstance( .... );
Debug.Assert( obj is TCustomForm );

I built all the assemblies and they do not have any compilation error. Surprise as I expect this to complain just like their C# builder would. But when it runs, the above assert fail!!

This is totally crazy. In the debugger, I can see the base type of obj is TCustomForm so what's happening. I even do this:

Debug.WriteLine( obj.GetType().BaseType.BaseType.Fullname );

This shows Borland.Vcl.TCustomForm. So what is happening?

Initially I thought Borland must have translated the is operator to something else because their as operator and Pascal cast operator behave exactly opposite to C#. So I fired up Lutz's Reflector and is operator is generated to isinst IL instruction. So that proves the Pascal is operator is being translated to some Borland operator.

The explanation only surfaces when I type out the Type.AssemblyQualifiedName. The outputs of obj.GetType().BaseType.BaseType and TCustomForm from MyApp explain why isinst is failing.

The Delphi compiler took action when it sees that I have not defined a reference to Borland.Vcl.dll and rammed the IL code into MyApp.exe to produce this:

Borland.Vcl.TCustomForm, MyApp, Version=1.0.27277.2828, Culture=neutral, PublicKeyToken=None

The base class from obj is
Borland.Vcl.TCustomForm, Borland.Vcl, Version=10.xxxxxx, .....

In other words, as far as CLR is concerned, these are two distinct types. Borland must mistakenly believing that CLR would simply use namespace qualified type names. How wrong is such a view!

Let's see what the standard says about the above types - are they 2 distinct types or one the same?

With reference to Partition I, section 8.5.2 Assmblies and Scoping:
To fully identify a type, the type name shall be qualified by the scope that includes the type name. A type name is scoped by the assembly that contains the implementation of the type. An assembly is a configured set of loadable code modules and other resources that together implement a unit of functionality. The type name is said to be in the assembly scope of the assembly that implements the type. Assemblies themselves have names that form the basis of the CTS naming hierarchy.

Here you have the unambiguous definition from the standard that says the above encounter resulted in two distinct types.

In fact, Borland is willing to throw away the strongly name attribute of their Borland.Vcl.dll to a non-strongly name one. Gee I am wondering if I can use that to con users that I am a genuine Borland assembly. I will leave that for another day.

After discovering this, a report was dispatched to Borland. As usual, it is not a bug but a 'feature' and 'an advantage'. Oh Yah! Probably the COM bug in their code is also a feature. It is a special feature called static binding. Indeed it is a static binding! If you open the assembly with Lutz's Reflector, you can see all the IL code rammed into your assembly as if they were in Borland.Vcl.dll. The trouble is that they have just allowed you to give their type your version and assembly scope. Even if it is in an executable, you can still load it as if an ordinary DLL assembly.

Incidentally, their compiler does not even have a switch to turn off this 'feature' nor does it generates any warning. So beware!

Now let's consider a number of normal .Net usages in which Borland's 'feature' can wreck havoc to a CLR solution.

Scenario 1
Let's say a gun ho Delphi developer comes up with this special component that he wants other to use. Seeing it is cooler not having to dispatch Borland.Vcl.dll, he uses this static linkage to produces his assembly.

The other developer using factory pattern to load this will have lots of problem.

In fact, if this developer wants to achieve this, he/she would be better to use DILMerge.

Scenario 2
Let say developer creates MyAssem1.dll using static binding, another one produces MyAssem2.dll, etc. (incidentally don't be fool to believe that if you have MyAssem1.exe, MyAssem2.exe, two separate applications will not encounter this madness), soon you have as many distinct TCustomForm types as you have assemblies.

Scenario 3
When Borland finally catches up to .Net 2 and that they support generic, whose syntax is still a mystery, you cannot use List because if you have a number of distinct TCustomForm types as far as CLR is concerned. I pray Borland will not create its own flavour of System.Collections.Generic.List<>? The only way out is to resort back to using ArrayList that support inhomogenous collection.

Clearly Borland must be naively believing type comparison is only performed based on namespace qualified name rather than what is defined by CLI. Perhaps in their VCL32 world this is the case. Well that's fine as that is their own creation and they can be as free as they like because there is no one they have to be compatible with except themselves. Sorry Borland. Someone must have forgotten to tell you that the world has changed!

I would like to agree with Borland that this is a 'feature' or 'advantage' but if this creates more problems, violates CLI specification, misleads developers and has no real benefit at all, I am afraid that my logical thinking does not allow me to agree. So what can I say other than to label this as a bug and an attempt to bastardize CLR or to create Borland's CLR.

Having features to distinguish oneself from others is great but the features should not damage and confuse a framework that promotes interchangeability, cross-language programming and component technology.

What Borland has done is to transplant their VCL32 features to .Net and blindly or rather arrogantly ignoring the need to meet the ECMA CLI standard.

VCL namespace is already non-compatible with the System namespace and this is another Borland's feature to take their product further away from being compatible with .Net. So users be warned and stay clear.

Wednesday, November 15, 2006

Fixing up Borland Delphi's COM Server Registration Problem

The story where Borland does not even understand their requirement for COM Server registration and then translating that to code has been described in the most kiddish format in my other blog message.

I doubt Borland will have the courage to admit mistake and fix their problem as this problem exists in their product unchanged since Delphi 3 to the latest, including those not yet released product. Hence it is a dead loss trying to get Borland to do something. I am going to show you how to fix this problem. It is as easy as learning "Mary has a little lamb" rhyme.

Before I'll show you the fix, let me reproduce their documentation partially here:
Start mode Switch Meaning
smAutomation embedding The application was started by Windows in response to a request from an automation controller.
smRegServer regserver The application was started only to add the server to the system registry.
smStandalone
The user started the application as a stand-alone, interactive application.
smUnregServer unregserver The application was started only to remove the server from the system registry.
Table 1 - Permissible COM Server switches

For running the automation server as a stand alone application, you do not include any switch.

From the above requirement, it seems pretty obvious that you only have to run through the COM registration manipulation code when you encounter the switches /regserver or /unregserver. Incidentally this is the standard stuff if you build the COM local server using VB6, MFC and ATL.

Now it is time to reveal how Borland handles this situation badly. To see this you can locate this code fragment in ComServ.pas at around line 373, if you have access to Borland's Delphi tool or simply search for TComServer.Initialize in Unit ComServ. It is reproduced here in Listing 1,
// Listing 1
procedure TComServer.Initialize;
begin
try
UpdateRegistry(FStartMode <> smUnregServer);
except
on E: EOleRegistrationError do
// User may not have write access to the registry.
// Squelch the exception unless we were explicitly told to register.
if FStartMode = smRegServer then raise;
end;
if FStartMode in [smRegServer, smUnregServer] then Halt;

ComClassManager.ForEachFactory(Self, FactoryRegisterClassObject);
end;
In merely 9 lines (ignoring comments), the two bold red lines are erroneous and I am going to show you why.

Let's take the bug number 1 and that is the COM Server registration code (the first line in red).

If you assign the values listed in column 1 in table 1 to the variable FStartMode, one value at a time, and then ask yourself under what value does the function UpdateRegistry() is not called.

If your answer is that UpdateRegistry() is called regardless of the value of FStartMode, then you are correct and you begin to see how silly that piece of code is.

UpdateRegistry() is a procedure that executes COM registration steps when the parameter is true. Otherwise it performs COM unregistration steps.

If you have a basic understanding of COM, you will realise that by the time COM successfully launches your local server via a client's call to COM method like CoCreateInstance(), your server must have been registered properly. So in that situation a Delphi automation server will have a FStartMode = smAutomation.
If you have followed me so far, UpdateRegistry() is called regardless of the switch and this also include the situation when you, the COM server, are launched by COM. So why do you then have to update the registry again? Doing so is like you have just flew into an airport and you still insist on buying an inbound ticket. It is silly.

To fix that all you have to do is to check if the FStartMode is smRegServer or smUnregServer. If so then called UpdateRegistry().

Now the second bug requires one to perform a function calls tracing code review. But in short, no one in the possible call chain throws EOleRegistrationError the one that Borland has programmed to catch (see the second line in red in Listing 1). Instead the code throws EOleSysError when there is COM registration error.
If you look up Delphi documentation you can see that these are two distinct exceptions both derived from EOleError and that they are siblings to EOleError.
So the corrected code is as follows, Listing 2:
// Listing 2
procedure TComServer.Initialize;
begin
try
if FStartMode in [smRegServer, smUnregServer] then
UpdateRegistry(FStartMode <> smUnregServer);
except
// on E: EOleRegistrationError do
on E: EOleError do
// User may not have write access to the registry.
// Squelch the exception unless we were explicitly told to register.
if FStartMode = smRegServer then raise;
end;
if FStartMode in [smRegServer, smUnregServer] then Halt;

ComClassManager.ForEachFactory(Self, FactoryRegisterClassObject);
end;
I have left Borland's incorrect catch statement there for comparison. Comparing this to that shown in Listing 1, you can see that it is pretty obvious that someone must have accidentally deleted the test for /Regserver or /Unregserver (the line in greed) or someone must be high on illegal substance and thinking what is left in Borland's code is a pretty cool optimisation.

As mentioned, many people have reported this bug before and Borland showed a complete lack of consumer concern to fix this problem. Incidentally, once you have registered, the subsequent calls to UpdateRegistry( true ) does not cause problem in LUA because COM's RegisterTypeLib() performs a read check to see if the COM information is the same. If so it does not update it. Otherwise it does. When that happen, you need power users or higher privilege.

If you want to replace Borland's buggy code, all you have to do is:
  • Take a copy of ComServ.pas to somewhere safe.
  • Edit the TComServer.Initialize to that shown in Listing 2.
  • In the Delphi's COM Server project, include a copy of this file.
  • Delete all the dcu file and close the entire project/group. Delphi IDE has this crazy frequently happening moment of memory lapse that it fails to pick up that your project now has a new file. Pretty dumb stuff.
  • Reopen this and rebuild it.

This automation server should now work properly. The best way to test this is to unregister the COM Local server (just the executable) in an Admin account. Then start the automation server as a stand alone in LUA. In this situation, the program should start up properly. If this is built using Borland's buggy code, it will throw an exception and that is not the one Borland programmed to catch.

It is this simple to fix Borland's bug!

Blog Archive