Lazarus raising exception class after compiling program on Windows - pascal

I've written program in Lazarus Pascal. It was entirely written on Mac, then I've switched to windows, recompiled it (recompiled .dylib to .dll, recompiled and installed custom component), and it runs, but when I try to do anything, it throws error:
While on debug mode:
Project project1 raised exception class 'External:SIGSEGV'. At address 772CD4F1
Running .exe file :
Access violation.
// EDIT
I've noticed that it has a problem with that part of code, in particular at ListView.Clear command:
procedure AddressList.updateView(ListView : TListView);
var
element : ListElement;
newItem : TListItem;
begin
ListView.Clear;
element := first;
if element = nil then
exit;
while element <> nil do
begin
newItem := ListView.Items.Add;
newItem.Caption := element^.name;
newItem.SubItems.Add(element^.surname);
newItem.SubItems.Add(element^.address);
newItem.SubItems.Add(formatNumber(element^.phoneNumber));
element := element^.next;
end;
end;
How is that possible, what could I do wrong?

In Free Pascal Classe instances are always implicit pointers.
It seems that for some reason your ListView doesn't contain a properly created class instance. The "pointer" ListView points to wherever. When the class method Cleartries to access the data you get a segmentation fault.
A watch of ListView should show either garbage data or <invalid>.

Related

How to automatically save the GUI to file? (Paradigm)

The good (and bad) old Delphi taught us the "classic" way of building application because of the way we write code "behind" the IDE.
Based on this paradigm, I built some time ago a library that allows me to save/load the GUI to INI file with a single line of code.
LoadForm(FormName)
BAM! That's it! No more INI files!
The library only saves "relevant" properties. For example, for a TCheckBox it saves only its Checked property not also its Color or Top/Left. But it is more than enough.
Saving the form has no issues. However, I have "problems" during app initialization. They are not quite problems, but the initialization code is not that nice/elegant.
For example when I assign Checkbox1.Checked := True it will trigger the OnClick event (supposing that the checkbox was unchecked at design time). But assigning a False value (naturally) will not trigger the OnClick event.
Therefore, I have to manually call CheckBox1Click(Sender) after SaveForm(FormName) to make sure that whatever code is in CheckBox1Click, it gets initialized. But this raises another problem. The CheckBox1Click(Sender) might be called twice during application start up (once by SaveForm and once my me, manually).
Of course, in theory the logic of the program should be put in individual objects and separated from the GUI. But even if we do this, the initialization problem remains. You load the properties of the object from disk and you assign them to the GUI. When you set whatever value you have in your object to Checkbox1, it will (or not) call CheckBox1Click(Sender) which will set the value back into the object.
On app startup:
procedure TForm.FormCreate (Sender: TObject);
begin
LogicObject.Load(File); // load app logic
Checkbox1.Checked := LogicObject.Checked; // assign object to GUI
end;
procedure TForm.CheckBox1Click(Sender: TObject);
begin
LogicObject.Checked := Checkbox1.Checked;
end;
Probably the solution involves writing stuff like this for EVERY control on the form:
OldEvent := CheckBox1.OnClick;
CheckBox1.OnClick := Nil;
CheckBox1.Checked := something;
CheckBox1.OnClick := OldEvent;
Not elegant.
Question:
How do you solve this specific problem OR what is your approach when saving/restoring your GUI to/from disk?
This is one of the things which botthered me in some components from the beginning. What I know the are 3 options, except separating GUI and the business logic as #David said, which is not always an option.
As you wrote above, always unassign the events so they don't get triggered
Use non-triggered events such as OnMouseDown or OnMouseUp
Or a similar solution that I use and I think is the most elegant
Create a global variable FormPreparing which is set during initialization and check its value at the beginning of the events like below.
procedure TForm.FormCreate (Sender: TObject);
begin
FormPreparing := True;
try
LogicObject.Load(File); // load app logic
Checkbox1.Checked := LogicObject.Checked; // assign object to GUI
finally
FormPreparing := False;
end;
end;
procedure TForm.CheckBox1Click(Sender: TObject);
begin
if FormPreparing then
Exit;
LogicObject.Checked := Checkbox1.Checked;
end;

Error handling in fphttpclient?

fphttpclient works fine with simple examples like
procedure ReadFromURL(theURL: string);
var
httpClient: TFPHTTPClient;
FileContents: String;
theStatusCode: integer;
begin
httpClient := TFPHTTPClient.Create(nil);
try
FileContents := httpClient.Get(theURL);
theStatusCode := httpClient.ResponseStatusCode;
if theStatusCode = 200 then
begin
; // do something
end
else
ShowMessage(IntToStr(theStatusCode));
finally
httpClient.Free;
end;
end;
but only, if the URL exists, so that the status code is 200. In other cases the code crashes at httpClient.Get with an exception of class EHTTPClient, ESocketError or EXC_BAD_ACCESS, although the procedure uses a try ... finally section (formulating it as try ... except doesn't change anything). Unfortunately, the exception is raised before the status code can be processed.
What is the recommended way to handle errors with fphttpclient? Is there any method to check for the existence of a resource (and, possibly, the correctness of an URL, too), before invoking the Get method?
Make sure the various events are assigned, so that the class knows what to do on password prompts, redirects etc.
Standard examples init the class like
With TFPHTTPClient.Create(Nil) do
try
AllowRedirect:=True;
OnRedirect:=#ShowRedirect;
OnPassword:=#DoPassword;
OnDataReceived:=#DoProgress;
OnHeaders:=#DoHeaders;
{ Set this if you want to try a proxy.
Proxy.Host:='ahostname.net.domain';
Proxy.Port:=80;
etc.
Please study examples and try to sort through your problems till you have reproducible cases. If then there is still a problem, please submit it to the bugtracker
In rare cases, checking the existences of headers with HEAD() can speed up e.g. sifting through lists of old urls

Enumerate installed Packages in Windows 8+ with Delphi 10

Delphi 10 comes with Windows RT headers translated to Pascal. Based on this C++ code i am trying to enumerate all installed Metro applications in Windows 8+. The only problem is, that i don't know how to get iterator correctly, from IIterable_1__IPackage. FindPackages method of Deployment_IPackageManager is called correctly, and i can confirm it by scanning memory process (before and after method call). Process memory contains strings like Microsoft.SkypeApp etc. so packages are ready to be iterated. Once i set IIterator_1__IPackage to first package, it becomes invalid pointer value (on my PC that is $3). I wonder now, if it has something to do with incorrect RT headers in Delphi or me approaching iteration process wrong way (most likely). Current code:
program PackagesManager;
{$APPTYPE CONSOLE}
{$R *.res}
uses
Winapi.Windows,
System.SysUtils,
WinAPi.Management,
WinApi.ApplicationModel,
WinApi.WinRT,
System.Win.ComObj;
var
LClassId: HString;
pInspectable: IInspectable;
pAct: IActivationFactory;
packageManager: Deployment_IPackageManager;
pkgs: IIterable_1__IPackage;
pIter: IIterator_1__IPackage;
hasCurrent: Boolean;
packageId: IPackageId;
package: IPackage;
begin
// COM/Runtime Object Initialization
OleCheck(RoInitialize(RO_INIT_SINGLETHREADED));
try
if Succeeded(WindowsCreateString(PWideChar(SDeployment_PackageManager),
Length(SDeployment_PackageManager), LClassId)) then
begin
// Get the activation factory
OleCheck(RoGetActivationFactory(LClassId, IActivationFactory,
pInspectable));
// Activate or create an instance from the Activation Factory
pAct := pInspectable as IActivationFactory;
pAct.ActivateInstance(pInspectable);
// Extract the PackageManager via QueryInterface
OleCheck(pInspectable.QueryInterface(Deployment_IPackageManager,
packageManager));
// Get the `IIterable` Collection of all packages
//
// after below call, process memory contains strings with package names
// i.e. Microsoft.SkypeApp, it means FindPackages was called properly
// confirmed this by scanning process memory for known strings,
// before and after FindPackages call
pkgs := packageManager.FindPackages;
// Get the Iterator from the IIterable
pIter := pkgs.First; // pIter is now $00000003...
hasCurrent := pIter.HasCurrent; // obviously Access Violation
while hasCurrent do
begin
package := pIter.Current;
packageId := package.Id;
hasCurrent := pIter.MoveNext;
end;
end;
finally
RoUninitialize;
end;
end.
I'm not looking for read registry or set NTFS access in %programfiles\WindowsApps solution, because this is just a base for project that functionality will be expanded. Being able to list all packages in elegant & Microsoft designed way would be a great start.

Calling procedure from dll in Delphi XE2

So, I'm trying to call a procedure from a DLL in Delphi XE2.
but the procedure just won't assign.
I have tried several examples found on the internet.
The DLL is being loaded as expected.
The exports are correctly written.
Everything seems fine but still no success.
What is up with that?
The code I have is the following
type
TStarter = procedure; stdcall;
...
fTheHookStart: TStarter;
...
procedure TForm1.LoadHookDLL;
begin
LogLn('Keyboard Hook: Loading...');
// Load the library
DLLHandle := LoadLibrary('thehookdll.DLL');
// If succesful ...
if Handle <> 0 then
begin
LogLn('Keyboard Hook: DLL load OK!');
LogLn('Keyboard Hook: assigning procedure ...');
fTheHookStart := TStarter(GetProcAddress(DLLHandle, 'StartTheHook'));
if #fTheHookStart <> nil then
begin
LogLn('Keyboard Hook: procedure assignment OK!');
LogLn('Keyboard Hook: Starting...');
fTheHookStart;
end
else
begin
LogLn('Keyboard Hook: procedure assignment FAIL!');
FreeLibrary(DLLHandle);
if Handle <> 0 then LogLn('Keyboard Hook: DLL free OK!') else LogLn('Keyboard Hook: DLL free FAIL!');
end;
end
else
begin
LogLn('Keyboard Hook: DLL load FAIL!');
end;
end;
One error is that you assign DllHandle when you load the dll, but then you check if Handle <> nil. Handle is actually your forms handle, which ofcourse is not nil. That will not matter if the loading succeeded, but if it failed, you will get wrong logging.
Since you also have some logging functions, what does the log show?
As I understand it, the DLL loads, but GetProcAddress returns nil. There is only one such failure mode. The DLL does not export a function with that name.
Watch out for name decoration and letter case. C and C++ DLLs may export decorated names. And exported names are sensitive to letter case.
Use dumpbin or Dependency Walker to check the exported function name.
For reference, when GetProcAddress fails, as the documentation explains, a call to GetLastError will yield an error code.
And it looks like the other answer is onto something. You believe that you have loaded the DLL correctly, but your code doesn't perform that check correctly.
If you'd called GetLastError then the system could have alerted you to this. If you'd inspected the variables under the debugger, the problem would have been obvious.

Problems creating a form in a jvPlugin dll and displaying it as a child of a control on the mail form

I'm trying to write a plugin system for my application based on jvPlugin. I create forms in the plugin dll, then reparent them into DevExpress docking controls. At first sight, it seems to work. The problem is that none of the controls on the dll forms ever receive focus. Also, when clicking on controls like TSplitter, a "Control 'xxx' has no parent window" exception is raised.
Here's how I'm doing it (condensed version).
The plugin host implements an IPluginHost interface
IPluginHost = interface
['{C0416F76-6824-45E7-8819-414AB8F39E19}']
function AddDockingForm(AForm: TForm): TObject;
function GetParentApplicationHandle: THandle;
end;
The plugin implments an IMyPlugin interface
IMyPlugin = interface
['{E5574F27-3130-4EB8-A8F4-F709422BB549}']
procedure AddUIComponents;
end;
The following event is called when the plugin is initialised:
procedure TMyPlugin.JvPlugInInitialize(Sender: TObject; var AllowLoad: Boolean);
var
RealApplicationHandle: THandle;
begin
if Supports(HostApplication.MainForm, IPluginHost, FPluginHost) then
begin
RealApplicationHandle := Application.Handle;
Application.Handle := FPluginHost.GetParentApplicationHandle; // Returns Application.Handle from the host application
try
FMyPluginForm:= TMyPluginForm.Create(Application); // Plugin host app owns the form
finally
Application.Handle := RealApplicationHandle;
end;
end;
end;
When the plugin host has loaded I call IMyPlugin.AddUIComponents in my plugin. It's implemented like this:
procedure TMyPlugin.AddUIComponents;
begin
// Add the docking form
FPluginHost.AddDockingForm(FMyPluginForm);
end;
AddDockingForm is implemented in the host like this:
function TfrmMyPluginHost.AddDockingForm(AForm: TForm): TObject;
var
DockPanel: TdxDockPanel;
begin
// Create a new dockpanel
DockPanel := TdxDockPanel.Create(Self);
DockPanel.Name := DPName;
DockPanel.Height := AForm.Height;
DockPanel.DockTo(dxDockSite1, dtBottom, 0);
DockPanel.AutoHide := TRUE;
// Rename the dock panel and parent the plugin
DockPanel.Caption := AForm.Caption;
DockPanel.Tag := Integer(AForm);
AForm.Parent := DockPanel;
AForm.BorderStyle := bsNone;
AForm.Align := alClient;
AForm.Show;
FDockedPluginFormList.Add(AForm);
Result := DockPanel;
end;
If I run the following function on any of the controls on the plugin form I see a list going all the way back to my host's main form. Yet TSplitters tell me they have no parent window. How can this be?
function TfrmMyPlugin.GetParents(WC: TWinControl): String;
begin
if (WC <> nil) and (WC is TWinControl) then
Result := WC.Name + ' [' + WC.ClassName + '] - ' + GetParents(WC.Parent);
end;
I must be missing something somewhere. Anybody got any good ideas?
Build both the plugin and the host application with runtime packages.
Without using runtime packages, the DLL uses a distinct copy of the RTL, VCL and any used units. For example, the DLL's TForm class is not the same as the host's TForm class (is operator fails across the host/DLL boundary and therefore a DLL control will not recognize host parent form as a valid instance of TForm), global variables like Application, Mouse, Screen are separate instances, you have two copies of RTTI, etc, etc.
The VCL was simply not designed to be used like this.
With runtime packages on, all the problems are solved and the plugin (either a runtime package itself or a DLL built with runtime packages) can integrate seamlessly with the host application using runtime packages.
We made it work using "runtime packages" adding "vcl,rtl,ourownpckg"
Where ourownpckg is a our-own-package created with all the DX dependencies and some other that we use across exe-plugins, including JVCL ones.
The three packages must be shiped along the exe
Hope it helps

Resources