Ada - does pragma Attach_Handler() can attach handler with System.Priority'Last priority? - interrupt

The next two declarations are equivalent:
protected type prot_Type is
....
pragma Priority(System.Priority'Last);
end;
protected type prot_Type is
....
end;
One way of attaching interrupt handler is:
protected type prot_Type is
procedure Handler;
pragma Attach_Handler(Handler, ...);
end;
--//Attach is made at the creation of the next object:
Object : prot_Type;
it's a legal attachment (It works).
How is it possible that the handler has ceiling priority of System.Priority Last ? (As far as I know the legal priority is in range Priority'Last+1 .. Any_Priority'Last).
Another thing:
if I add the pragma Priority(System.Priority'Last); to the protected declaration, a program_error exception is raised at the elaboration (when attaching the handler).
Someone can please spread the fog?

I finally manage to understand thanks to:
http://www.iuma.ulpgc.es/users/jmiranda/gnat-rts/node33.htm
The fact that an hadler that defined in a protected with ceiling priority System.Priority'Last managed to be attached to Interrupt seems to me like bug in the compiler.
Only hendlers that defined in a protected with ceiling priority in Interrupt_Prioriy'Range can be attached to interrupt.
Another important thing - for non static protected (i.e declared with "protected type ... ") the attachment is made by the creation of the object of that type. The object must be allocated dynamicly.
Yony.

This question is about attaching interrupts (or signals) to a protected object to function as interrupt handlers. It is wonderful that Ada provides you a mostly language-standard way to do this, but there are limits to what is in the standard, and I think your question hits one. You really need to read your compiler's documenation for this one.
For example, if what you are attaching to is an honest-to-god system interrupt, then it is quite possible that your handler will get called directly from the system interrupt, which is of course completely outside of (and thus above) both your OS's process priority and Ada's task priority systems.
Generally in such a case, like with any ISR, you'd want to do the absolute minimum required to make note of and deal with the interrupt, interact with the system as little as possible (no I/O or tasking interactions), and return control back to the system so it can start behaving normally again. In your case, you might want to increment a variable or set a flag internal to your tagged type, take down any volatile info about the interrupt you may need later, then return.

Related

What does ‘serial’ do?

From the docs that say,
Returns the self-reference to the instance itself:
my $b; # defaults to Any
say $b.serial.^name; # OUTPUT: «Any␤»
my $breakfast = 'food';
$breakfast.serial.say; # OUTPUT: «food␤»
I do not have the foggiest what this routine does, please can someone explain?
On Supplys, it is an informational method that is supposed to indicate whether there will never be any concurrent emit on that Supply.
On HyperSeq and RaceSeq, it returns a serialized Seq, so you could consider it the opposite of the hyper and race method.
In general, it appears to return itself, which seems to make sense from the HyperSeq and RaceSeq point of view.
And yes, these should be documented properly, so please create a documentation issue. Thank you!
In the doc example it does nothing. That is, if you remove it you get the same results:
my $b; # defaults to Any
say $b.^name; # OUTPUT: «Any␤»
my $breakfast = 'food';
$breakfast.say; # OUTPUT: «food␤»
More generally, I think you'd best ignore the serial method other than to open a doc issue pointing to this SO if you'd like to improve the doc.
The serial method does not appear to be in the official language
A search of the roast repo for "serial" yields zero matches.
Within Rakudo source code the method name serial has been overloaded to have one of three meanings:
A boolean declaring whether a Supply sequence is always serial. Rakudo source examples: 1, 2. This looks to me like an internal method that doesn't need to be documented.
A coercion of parallel sequence (hyper or race) to a serial version of the same sequence. This looks to me like an internal method that doesn't need to be documented.
A "no op" that returns its invocant. I suspect it would be best if it were not documented, at least until such time as its raison d'etre is clear; its official status viz-a-viz the spec (roast) is clear; and/or there's an attempt to systematically document which operations have the is nodal set on them.
None of the above seems to warrant ordinary users' attention or documentation.
The Any class definition of a serial method seems pointless
The Any class serial method returns self, i.e. when called it is a no op.
I don't currently understand why there is an Any class definition.
One possible point for it would be that there are .serial calls made by internal code on instances of an unknown and generally unknowable class and there thus needs to be a default definition of serial in the Any class.
But a search of the rakudo repo for ".serial" suggests that calls are only made to supplies or hyper/race seqs.
That said, I note the is nodal trait on the proto serial declaration in Any that immediately precedes the multi method serial declaration. Perhaps that is the reason it's in Any.
See also Arbitrary drift of methods to Mu and Any.
The documentation you quoted seems pointless
The definition and example seem to reflect someone's sense of humor. I applaud use of humor but in this case I suspect the best improvement would be to just remove the page you linked.

Is there any delayed MultiCast-Event, which is able to be interruptable?

I am looking for an interruptable, delayed event, which I hope could be already part of Spring4D, or easily implemented there.
What would be best way anyway, to achieve this ?
Probably the Event wouldn't be the right place.
Basically looking for something like
Event.InvokeDelayed(1000, nil); and
Event.InvokeCancel;
procedure TTestMulticastEvent.Test;
var
e: Event<TNotifyEvent>;
begin
e.Add(HandlerA);
e.Invoke(nil); // Yes, this is the normal behaviour
// But would this make sense in Events,
// or better use other concept, like TTask.IdleWorker, e.g. ?
e.InvokeDelayed(1000, nil); // waits 1sec
Sleep(100); // Interrupts after 100ms
e.InvokeCancel; // Prevent future Event, started earlier
end;
Maybe I oversee something already available to solve this task in S4D.
Rollo
No, multicast events as they are in the library are synchronous. For them to work properly asynchronously in all cases it would require way more than just delaying their invokation but capturing any data you pass through them, make sure that data does not get invalid and so on.
If you need a mechanism like that you should use one of the existing libraries out there to do asynchronous things.
For example with the PPL (naive code to just show the concept):
var
e: Event<TNotifyEvent>;
t: ITask;
begin
e.Add(HandlerA);
t := TTask.Run(
procedure
begin
Sleep(1000);
if t.Status <> TTaskStatus.Canceled then
TThread.Synchronize(nil,
procedure
begin
e.Invoke(nil);
end);
end);
Sleep(100);
t.Cancel;
end;
You can probably wrap this into your own routine depending on your needs and the actual implementation. It will not be possible however to make a InvokeDelayed method with an additional parameter to what the event type has as signature because Event<T>.Invoke is not a method but a property returning T which you can invoke (which makes it look like a method call itself).
Anything beyond that requires as I said preserving the parameters passed to Invoke to pass them later (something that anonymous methods to for you to a certain degree) which is not trivial (at least not when we are talking about the generic Event<T>)

How to access CAN signals dynamically (by string) in CAPL?

I'm trying to force CAN signals to given values using COM interface of CANalyzer. Since there is no COM method to send CAN messages, I'm implementing a workaround using CAPL:
void SendMySignal(int value) {
message MyMessage msg;
msg.MySignal = value;
output(msg);
}
This works fine, however since MyMessage and MySignal are referenced statically (by name) here, I'll have to implement N functions to be able to send N signals (or an N-way switch statement, etc). Is there a way to avoid the hassle and access signals inside a message by string? Something like this:
void SendSignal(int MessageID, char SignalName, int value)
I'm also open to alternative solutions in case I have missed something in the COM interface. If there is a solution which only works for CANoe, I can ask my boss for a license, but of course I'd prefer to do without.
there is such function, but it is restricted to be used only in test nodes
long setSignal(char signalName[], double aValue);
you can find details in:
CAPL Function Overview » Test Feature Set / Signal Access » SetSignal
Special Use Case: Signal is not known before Measurement Start
and take care about not to send for each signal a new message to avoid bus over-flooding. In my opinion it is a better style to set all signals for whole message and to send it on change only when it is not cyclic. Signal updates in cyclic messages mostly have to be sent in next cycle.

Confusion regarding reentrant functions

My understanding of "reentrant function" is that it's a function that can be interrupted (e.g by an ISR or a recursive call) and later resumed such that the overall output of the function isn't affected in any way by the interruption.
Following is an example of a reentrant function from Wikipedia https://en.wikipedia.org/wiki/Reentrancy_(computing)
int t;
void swap(int *x, int *y)
{
int s;
s = t; // save global variable
t = *x;
*x = *y;
// hardware interrupt might invoke isr() here!
*y = t;
t = s; // restore global variable
}
void isr()
{
int x = 1, y = 2;
swap(&x, &y);
}
I was thinking, what if we modify the ISR like this:
void isr()
{
t=0;
}
And let's say, then, that the main function calls the swap function, but then suddenly an interrupt occurs, then the output would surely get distorted as the swap wouldn't be proper, which in my mind makes this function non-reentrant.
Is my thinking right or wrong? Is there some mistake in my understanding of reentrancy?
The answer to your question:
that the main function calls the swap function, but then suddenly an interrupt occurs, then the output would surely get distorted as the swap wouldn't be proper, which in my mind makes this function non-reentrant.
Is no, it does not, because re-entrancy is (by definition) defined with respect to self. If isr calls swap, the other swap would be safe. However, swap is thread-unsafe, though.
The correct way of thinking depends on the precise definition of re-entrancy and thread-safety (See, say Threadsafe vs re-entrant)
Wikipedia, the source of the code in question, selected the definition of reentrant function to be "if it can be interrupted in the middle of its execution and then safely called again ("re-entered") before its previous invocations complete execution".
I have never heard the term re-entrancy used in the context of interrupt service routines. It is generally the responsibility of the ISR (and/or the operating system) to maintain consistency - application code should not need to know anything about what an interrupt might do.
That a function is re-entrant usually means that it can be called from multiple threads simultaneously - or by itself recursively (either directly or through a more elaborate call chain) - and still maintain internal consistency.
For functions to be re-entrant they must generally avoid using static variables and of course avoid calls to other functions that are not themselves re-entrant.

What is the appropriate amount of error-checking?

public void PublicMethod(FooBar fooBar)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null");
// log the call [added: Thanks S.Lott]
_logger.Log("PublicMethod called with fooBar class " + fooBar.Classification);
int action = DetermineAction();
PrivateMethod(fooBar, action);
}
private void PrivateMethod(FooBar fooBar, int action)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null"); // Is this line superfluous?
/*
Do something
*/
}
Is it OK to skip this kind of error checking in private methods if the input is already checked on the public interface? Usually there's some sort of rule-of-thumb one can go by...
Edit:
Maybe ArgumentNullException isn't such a good example because the argument can be made that you should check at both levels but return different error messages.
I would say no.
While it certainly holds true that you in this case knows that it has already been checked for nullability, in two months time the youngest intern will come along and write
PublicMethod2 that also calls PrivateMethod, but lo and behold he forgot to check for null.
Since the public method doesn't really use foobar, I'm not sure why it's checking. The current private method cares, but it's the private method's responsibility to care. Indeed, the whole point of a private method is to delegate all the responsibilities to it.
A method checks the input it actually uses; it doesn't check stuff it's just passing through.
If a different subclass has the same public method, but some different private method implementation -- one that can tolerate nulls -- what now? You have a public method that now has wrong constraints for the new subclass.
You want to do as little as possible in the public method so that various private implementations are free to do the right thing. Don't "over-check" or "just-in-case" check. Delegate responsibility.
I'd error check everything you can, you never know when something might happen that you didn't think about. (and its better safe than sorry)
When using design by contract (http://en.wikipedia.org/wiki/Design_by_contract) it’s normally client’s (public method) responsibility to make correct invocation, i.e. pass on valid parameters. In this particular scenario it depends whether null belongs to a set of valid input values, therefore there are 3 options:
1) Null is valid value: throwing exceptions or errors would have meant breaking the contract, the server (private method) has to process the null and shouldn’t complain.
2) Null is invalid value and passed by code within your control: it is up to the server (private method) to decide how to react. Obviously, throwing an exception is more graceful way of handling the situation, but it has a cost of having to handle that exception somewhere else up the stack. Exceptions are not the best way to deal with violation of contract caused by programming blunders. You really should throw exceptions not when a contract is already violated but when it cannot be fulfilled because of environmental problems what cannot be controlled in software. Blunders are better handled by sticking an assertion into the beginning of the private method to check that the parameter is not null. This will keep the complexity of your code down, there is no cost of having to handle the exception up the stack and it will achieve the goal of highlighting broken contracts during testing.
3) Then there is defensive programming (http://en.wikipedia.org/wiki/Defensive_programming). When dealing with parameters passed by an external code outside your control the immediate layer of your code needs to run paranoid level of checks and return errors according to its communication contract with the external world. Then, going deeper into the code layers not exposed externally, it still makes more sense to stick to the programming by contract.
At least put a comment that PrivateMethod must have a non-null FooBar and that PublicMethod checks this.
You might want to also mark the "private" method as private or protected.
That depends if a null-value indicates an error for a method. Remember that methods could also be called messages to an object; they operate on the state of the object aswell. Parameters can specialize the kind of message sent.
If publicMethod() does not use a parameter and changes the state of the instance while privateMethod() uses the parameter, do not consider it an error in publicMethod, but do in privateMethod().
If publicMethod() does not change state, consider it an error.
You could see the latter case as providing an interface to the internal functioning of an object.
I'd consider the answer to be "yes, do the check again" because:-
The private member could be reused again in the future from a different path through the code, so program defensively against that situation.
If you perform unit tests on private methods
My view might change if I had a static analyser that could pick this up and not flag the potential use of a null reference in the private method.
In cases where PrivateMethod will be called frequently with input that has already been verified, and only rarely with user input, Then I would use the PublicMethod/PrivateMethod concept with no error checking on PrivateMethod (and with PublicMethod doing nothing other then checking the parameters and calling PrivateMethod)
I would also call the private method something like PublicMethod_impl (for "implementation") so it's clear that it's an internal use/ no checking method.
I maintain that this design leads to more robust application, as it forces you to think about what's checked when. Too often people who always check parameters fall into the trap of "I've checked something, therefore I've checked everything".
As an example of this, a former co-worker (programming in C) would, before using a pointer, always check to see if it was null. Generally, the pointers in his code were initialized as startup and never changed, so the chances of it being null were quite low. Moreover, the pointer has one correct value and 65535 possible wrong values, and he was only checking for one of those wrong values.