To whom static int Main return value? - c#

I have written a program by changing void to int
class Program
{
static int Main(string[] args)
{
return -1;
}
}
To whom this value will get return ...is it CLR? If so, how... because a called function can return a value to a calling function.
If this is the called function, then who is the calling function..is it CLR?
How it is happening ?
Does CLR returns any value to someone, e.g. OS?

If this is the called function, then who is the calling function..is
it CLR? How it is happening ?
The Main method is called by the CLR. How is this happpening?
Initially, windows examines the exe's file's header to determine whether to create a 32-bit process or a 64-bit process, or a WoW64 process.
Then windows loads the x86, x64, or IA64 version of MSCorEE.dll into process's address space.
After this, the process's primary thread calls a method defined inside MSCorEE.dll. This method initializes the CLR, loads the exe assembly, and then calls its entry point method Main.
The method Main can return nothing, void or and int. If we choose to return an int, then usually we select to return 0, at the end of Main, which means that the execution of the Program was successful. If Main return another negative int, then we have an error. Both of them are conventions that are used widely.
That being said, it is clear that the value that Main returns is returned to the process's primary thread.
Update
How we could read this value?
We could build a batch file that will execute our executable. (I have given it the name ExecutableName, you should change it correspondingly.) We can read the value that Main returns using the %ERRORLEVEL%. If it is not 0, then the message Failed with error code with the corresponding error value will be printed to the screen.
#echo off
ExecutableName.exe
IF NOT %ERRORLEVEL% == 0 goto error
echo OK
goto end
:error
echo Failed with error code %ERRORLEVEL%.
:end

If you compile this piece of code it will produce a .exe program.
This is called by the operating system.
The return value will be passed back to the operating system when your program terminates.
You can use this return value for example in a batch script (*.bat) by observing %ERRORLEVEL%
If you start your .exe from another .Net program using the Process class, you'll find this return value in Process.ExitCode after your .exe has finished.

Related

Is there a way to validate that the CNC GCode program actually started running?

My current solution to ask the CNC (via ThincAPI) whether or not the program has Completed is not working. It doesn't care if I change programs, once it is successful it will always report true even after changing the loaded program.
What I would like is a variable that I can reset right before firing cycle start so I can check and see if the program truly ran. Ideally I would reset this CycleComplete method that is already being used.
I think what I'm going to end up doing is writing to a macro (common) variable and setting a value, then having the GCode change that value at the very end of the GCode program. Then I will read that value to verify it changed.
Okuma.CMDATAPI.DataAPI.CProgram myCProgram;
myCProgram = new Okuma.CMDATAPI.DataAPI.CProgram();
...
case "cycle":
string cycle = myCProgram.CycleComplete().ToString();
Console.WriteLine(" Response: " + cycle);
return cycle;
You might have to check machine in Auto Mode, and running status by using
CMachine class with method
GetNCStatus ()
GetOperationMode()
In the case of schedule program, part program is loaded really fast by NC. As a result, you might always see RUNNING status.
Using CV is also a good way to ensure that program have been set/reset.
I suspect you must be using an SDF Scheduled Program and the next program is being called before your application has a chance to catch that the previous .MIN program has completed.
The CycleComplete() method will reset when a new program is selected.
If it is returning true and the program in question didn't complete, that is because the subsequent .MIN program completed.
I would suggest putting a Dwell in between the PSelect calls in the SDF to give your app time to catch that the previous .MIN has completed or not.

get process mdoules c# with kernel.dll

I'm getting some trouble while running this:
public MODULEENTRY32 getModule(String ModuleName)
{
MODULEENTRY32 module32;
module32.dwSize = (uint) Marshal.SizeOf(typeof(MODULEENTRY32));
IntPtr hSnap = CreateToolhelp32Snapshot(SnapshotFlags.TH32CS_SNAPMODULE | SnapshotFlags.TH32CS_SNAPMODULE32, (uint) process.Id);
Module32First(hSnap, out module32);
if (hSnap == IntPtr.Zero)
{
return new MODULEENTRY32();
}
do
{
if (module32.szModule.Equals(ModuleName))
{
CloseHandle(hSnap);
return module32;
}
} while (Module32Next(hSnap, out module32));
return new MODULEENTRY32();
}
I was trying to get modules from a process but it always return 0,
I'm sure that the module name is corrent and the process id too
I don't think you have provided enough information to determine what the problem is.
If you read the CreateToolHelp32Snapshot documentation you should check if hSnap returned is INVALID_HANDLE_VALUE (-1). If it is, you need to call GetLastError to determine the reason for the failure.
Possible reasons for failures are documented:
If the specified process is the Idle process or one of the CSRSS
processes, this function fails and the last error code is
ERROR_ACCESS_DENIED because their access restrictions prevent
user-level code from opening them.
If the specified process is a 64-bit process and the caller is a
32-bit process, this function fails and the last error code is
ERROR_PARTIAL_COPY (299).
and:
When taking snapshots that include heaps and modules for a process
other than the current process, the CreateToolhelp32Snapshot function
can fail or return incorrect information for a variety of reasons. For
example, if the loader data table in the target process is corrupted
or not initialized, or if the module list changes during the function
call as a result of DLLs being loaded or unloaded, the function might
fail with ERROR_BAD_LENGTH or other error code. Ensure that the target
process was not started in a suspended state, and try calling the
function again. If the function fails with ERROR_BAD_LENGTH when
called with TH32CS_SNAPMODULE or TH32CS_SNAPMODULE32, call the
function again until it succeeds.

Making application run only through launcher [duplicate]

I need to make the primary .exe unrunnable from it (When you try to start it directly ,you get a message : Cannot start directly,if it runs from the secondary exe (only it,must have a crc verification i think) then start .
Hope i make myself clear
First .exe can't start directly
Second .exe can start the first exe (only)
Make the first exe a DLL. Then the second program can use it but a user won't be able to run it directly.
Set up the EXE that can't be started directly to accept a parameter, such as a SHA-256 hash of some unique data from the one that's supposed to start it. If that parameter doesn't exist or is not what's expected, display an error and exit.
EDIT:
static class Program
{
static void Main(params string[] args) //<- first needed change
{
if(args.Length == 0 || args[0] != "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
{
Console.WriteLine("Cannot execute this program directly.")
return;
}
... //rest of main function
}
}
The simplest way to do that is to have command line parameters, or beter still, set an environment variable and run it, so theres little way to trace the requirements from a "can I get round the fact you want me to use your app to run it". However, I would say a DLL would be the way to go really.
I am not sure if the process name (Process.GetCurrentProcess().ProcessName) would give you the 1st or the second EXE name but you can make the 1st EXE as a DLL and the second as an EXE.

Windows: Delete EXE after execution

I am working on an application in C# which does the following things:
Write an EXE to disk
Execute the EXE through Process.Start()
I am now trying to ensure that the EXE will be deleted once it is closed.
The easiest way to do so is to set the FileOptions.DeleteOnClose parameter when creating the EXE using File.Create.
However, this means that the EXE can not be executed while is in use. Once the file handle is closed, the EXE is immediately deleted before it can be executed.
Is there any way to retain a "weak reference" to the EXE in my application which does not lock the file and allows it to be executed? Alternatively, is there any way to unlock the EXE for execution with the file handle still open? Are there any other obvious solutions I am missing?
CLARIFICATION A: I am aware of other methods to delete files in use which will delete the file eventually (e.g. upon reboot). I am however looking for a method to delete the file immediately once it starts executing which is handled by the OS (e.g. when running a batch that first executes the file and then deletes it, the file would remain on disk if the batch job is terminated).
CLARIFICATION B: To explain the bigger picture: The application receives and decrypts an executable file. After decryption, the file should be executed. However, I want to make sure the decrypted version of the EXE does not stay on disk. Ideally, I also want to prevent users from copying the decrypted EXE. However, since the decryption application runs as the same user, this will be impossible to achieve in a truly secure fashion as both have the same privileges on the system.
You could use Process.WaitForExit:
var process = Process.Start(processPath);
process.WaitForExit();
// File.Delete(processPath); // Not strong enough (thanks to Binary Worrier)
DeleteOrDie(processPath); // Will attempts anything to delete the file.
But it gives the possibility to copy the exe from where you writed it.
A good solution is to run it from memory.
If your target exe is a CLR program, you can use the Assembly.Load function:
// read the file and put data in bin
...
Assembly a = Assembly.Load(bin);
MethodInfo method = a.EntryPoint;
if (method == null) throw new NoEntryPointException();
object o = a.CreateInstance(method.Name);
method.Invoke(o, null);
More details here.
If you want to load/execute any exe in memory, you could use the Nebbett’s Shuttle approach but you will need to code it in C/C++ and make a call to it from C#.
Also it looks like Microsoft doesn't like it (security issues) and I don't think you can achieve it from C# only. Good anti-virus will probably detect it.
In a not very good way but a way that can give you what you want, I suggest this solution:
(I use a Console Application with some input arguments for this solution)
[1: ] Write a function to check opened processes:
/// <summary>
/// Check application is running by the name of its process ("processName").
/// </summary>
static bool IsProcessOpen(string processName)
{
foreach (Processing.Process clsProcess in Processing.Process.GetProcesses())
{
if (clsProcess.ProcessName.ToUpper().Contains(processName.ToUpper()))
return true;
}
return false;
}
[2: ] Define some variables:
static bool IamRunning = true;
static int checkDuration = 1; // in seconds
[3: ] Use a Thread for run a loop for checking:
Thread t = new Thread(delegate() {
DateTime lastCheck = DateTime.MinValue;
while (IamRunning)
{
var now = DateTime.Now;
int dd = (now.Hour - lastCheck.Hour) * 3600 + (now.Minute - lastCheck.Minute) * 60 + now.Second - lastCheck.Second;
if (dd >= checkDuration)
if (!IsProcessOpen("ProcessName"))
{
delApplication(); // You have a function to delete ...
break;
}
}
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
[4: ] Use a loop at the end of the program:
while (t.ThreadState == ThreadState.Running)
{
// just wait.
}
Note: This solution by Console Application in my low computer have 50% usage of CPU.

C# : Making an exe to not run directly

I need to make the primary .exe unrunnable from it (When you try to start it directly ,you get a message : Cannot start directly,if it runs from the secondary exe (only it,must have a crc verification i think) then start .
Hope i make myself clear
First .exe can't start directly
Second .exe can start the first exe (only)
Make the first exe a DLL. Then the second program can use it but a user won't be able to run it directly.
Set up the EXE that can't be started directly to accept a parameter, such as a SHA-256 hash of some unique data from the one that's supposed to start it. If that parameter doesn't exist or is not what's expected, display an error and exit.
EDIT:
static class Program
{
static void Main(params string[] args) //<- first needed change
{
if(args.Length == 0 || args[0] != "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
{
Console.WriteLine("Cannot execute this program directly.")
return;
}
... //rest of main function
}
}
The simplest way to do that is to have command line parameters, or beter still, set an environment variable and run it, so theres little way to trace the requirements from a "can I get round the fact you want me to use your app to run it". However, I would say a DLL would be the way to go really.
I am not sure if the process name (Process.GetCurrentProcess().ProcessName) would give you the 1st or the second EXE name but you can make the 1st EXE as a DLL and the second as an EXE.

Categories

Resources