How do I use Emacs's DBUS interface? - emacs

I looked up the dbus package and it seems like all of the functions are built-in to the C source code and there's no documentation for them.
How do I use the dbus-call-method function?

I just had the same problem and found the emacs-fu article that comes up when googling a little too basic for my needs.
In particular I wanted to export my own elisp methods via dbus, and had problems making sense of the dbus terminology and how it applies to the emacs dbus interface.
First thing to check out, the emacs documentation, C-h f dbus-register-method
dbus-register-method is a built-in function in `C source code'.
(dbus-register-method BUS SERVICE PATH INTERFACE METHOD HANDLER)
Register for method METHOD on the D-Bus BUS.
BUS is either the symbol `:system' or the symbol `:session'.
SERVICE is the D-Bus service name of the D-Bus object METHOD is
registered for. It must be a known name.
PATH is the D-Bus object path SERVICE is registered. INTERFACE is the
interface offered by SERVICE. It must provide METHOD. HANDLER is a
Lisp function to be called when a method call is received. It must
accept the input arguments of METHOD. The return value of HANDLER is
used for composing the returning D-Bus message.
BUS is just going to be :session or :system (where you probably almost always want to use :session like a desktop application I suppose).
SERVICE is a unique name for the application on the bus, like an address or domain name. Dbus.el defines dbus-service-emacs as "org.gnu.Emacs".
PATH is to different types of application functionality what SERVICE is to different applications itself. For example a certain emacs module might expose functionality in the /ModuleName PATH under the org.gnu.Emacs SERVICE.
INTERFACE is just like an interface in programming. It is a specification that tells other dbus clients how to communicate with the object(s) your application exposes. It contains for example type signatures for your methods.
So you might have an interface that says something like: under the service org.gnu.Emacs, in the path /ModuleName, you will find a method named helloworld that will take zero arguments and return a string.
The difficult thing to figure out for me was: how do I define an interface for my method?
Poking around dbus.el you'll find that there is dbus-interface-introspectable (among others) defined, that just contains a string "org.freedesktop.DBus.Introspectable", which names a standard interface that just exposes one method:
org.freedesktop.DBus.Introspectable.Introspect (out STRING xml_data)
(link to the spec http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-introspectable)
And that is the method which is called by clients to find out about what applications expose on the dbus. So we can use that method to look at how other applications advertise their stuff on dbus, and then we can implement our own Introspect method just mimicking what the others are doing and everything will be fine.
Note however that the spec says that applications may implement the Introspectable interface, they don't have to. In fact you can call dbus-register-method just fine with an empty string as interface (anything will do it seems). You will be able to call your method. However I got always NoReply errors and problems with applications hanging waiting for a response from dbus which went away when I figured out how to make my stuff introspectable. So I assume that Introspect() is expected quite often.
So lets do this:
(defun say-world ()
;; you need to map between dbus and emacs datatypes, that's what :string is for
;; if you're returning just one value that should work automatically, otherwise
;; you're expected to put your return values in a list like I am doing here
(list :string "world"))
(dbus-register-method
:session
"org.test.emacs"
"/helloworld"
"org.test.emacs"
"hello"
'say-world)
That is what we want to implement and therefore want to define an interface for (named "org.test.emacs"). You can use it just like that and try to call the hello method with qdbus org.test.emacs /helloworld org.test.emacs.hello. It should work, for me it works only after 20 seconds of waiting (making the application hang), but it works.
Now lets make it introspectable:
(defun dbus-test-slash-introspect ()
"<node name='/'>
<interface name='org.freedesktop.DBus.Introspectable'>
<method name='Introspect'>
<arg name='xml_data' type='s' direction='out'/>
</method>
</interface>
<node name='helloworld'>
</node>
</node>")
(dbus-register-method
:session
"org.test.emacs"
"/"
dbus-interface-introspectable
"Introspect"
'dbus-test-slash-introspect)
(defun dbus-test-slash-helloworld-introspect ()
"<node name='/helloworld'>
<interface name='org.freedesktop.DBus.Introspectable'>
<method name='Introspect'>
<arg name='xml_data' type='s' direction='out'/>
</method>
</interface>
<interface name='org.test.emacs'>
<method name='hello'>
<arg name='' direction='out' type='s' />
</method>
</interface>
</node>")
(dbus-register-method
:session
"org.test.emacs"
"/helloworld"
dbus-interface-introspectable
"Introspect"
'dbus-test-slash-helloworld-introspect)
There we go. We just define two Introspect methods (one for each level of our path hierachy) and return some hand written xml telling other applications about the /helloworld path and the hello method within it. Note that dbus-test-slash-helloworld-introspect contains <interface name="org.test.emacs">...</interface> that has a type signature for our method, that is, as far as I am concerned, the definition of the interface we used when we registered our method with dbus.
Evaluate all that and poke around with qdbus:
~> qdbus org.test.emacs
/
/helloworld
~> qdbus org.test.emacs /
method QString org.freedesktop.DBus.Introspectable.Introspect()
~> qdbus org.test.emacs /helloworld
method QString org.freedesktop.DBus.Introspectable.Introspect()
method QString org.test.emacs.helloworld()
~> qdbus org.test.emacs /helloworld org.test.emacs.hello
world
Hooray, works as expected, no hanging or NoReply errors.
One last thing, you might try to test your method like so:
(dbus-call-method :session "org.test.emacs" "/helloworld" "org.test.emacs" "hello" :timeout 1000)
and find that it just timeouts and wonder why. Thats because if you register and call a method from within the same emacs instance then emacs will wait for itself to answer. There is no fancy threading going on, you will always get a NoReply answer in that situation.
If you have to call and register a method within the same emacs instance you can use dbus-call-method-asynchronously like so:
(defun handle-hello (hello)
(print hello))
(dbus-call-method-asynchronously :session "org.test.emacs" "/helloworld" "org.test.emacs" "hello" 'handle-hello)

Google to the rescue... Follow the link for the example, it's not my code so I won't put it here.
http://emacs-fu.blogspot.com/2009/01/using-d-bus-example.html

Here is a safe way to test for dbus capabilities:
(defun dbus-capable ()
"Check if dbus is available"
(unwind-protect
(let (retval)
(condition-case ex
(setq retval (dbus-ping :session "org.freedesktop.Notifications"))
('error
(message (format "Error: %s - No dbus" ex))))
retval)))
And here is a way to send a dbus notification:
(defun mbug-desktop-notification (summary body timeout icon)
"call notification-daemon method METHOD with ARGS over dbus"
(if (dbus-capable)
(dbus-call-method
:session ; Session (not system) bus
"org.freedesktop.Notifications" ; Service name
"/org/freedesktop/Notifications" ; Service path
"org.freedesktop.Notifications" "Notify" ; Method
"emacs"
0
icon
summary
body
'(:array)
'(:array :signature "{sv}")
':int32 timeout)
(message "Oh well, you're still notified")))

Or, just evaluate the following within Emacs:
(info "(dbus)")

Related

Is it possible to tail call eBPF codes that use different modes?

Is it possible to tail call eBPF codes that use different modes?
For example, if I coded a code that printk("hello world") using kprobe,
would I be able to tail call a XDP code afterwards or vice versa?
I programmed something on eBPF that uses a socket buffer and seems like when I try to tail call another code that uses kprobe, it doesn't load the program.
I wanted to tail call a code that uses XDP_PASS after using a BPF.SOCKET_FILTER mode but seems like tail call isn't working.
I've been trying to figure this out but I can't find any documentations regarding tail calling codes that use different modes :P
Thanks in advance!
No, it is not.
Have a look at kernel commit 04fd61ab36ec, which introduced tail calls: the comment in the first piece of code (in internal kernel header bpf.h), defining the struct bpf_array, sets a owner_prog_type member, and explains the following in a comment:
/* 'ownership' of prog_array is claimed by the first program that
* is going to use this map or by the first program which FD is stored
* in the map to make sure that all callers and callees have the same
* prog_type and JITed flag
*/
So once the program type associated with a BPF program array, used for tail calls, has been defined, it is not possible to use it with other program types. Which makes sense, since different program types work with different context (packet data VS traced function context VS ...), can use different helpers, have return functions with different meanings, necessitate different checks from the verifier, ... So it's hard to see how jumping from one type to another would work. How could you start with processing a network packet, and all of a sudden jump to a piece of code that is supposed to trace some internals of the kernel? :)
Note that it is also impossible to mix JIT-ed and non-JIT-ed programs, as indicated by the owner_jited of the struct.

Understanding higher level call to systemcalls

I am going through the book by Galvin on OS . There is a section at the end of chapter 2 where the author writes about "adding a system call " to the kernel.
He describes how using asmlinkage we can create a file containing a function and make it qualify as a system call . But in the next part about how to call the system call he writes the following :
" Unfortunately, these are low-level operations that cannot be performed using C language statements and instead require assembly instructions. Fortunately, Linux provides macros for instantiating wrapper functions that contain the appropriate assembly instructions. For instance, the following C program uses the _syscallO() macro to invoke the newly defined system call:
Basically , I want to understand how syscall() function generally works . Now , what I understand by Macros is a system for text substitution .
(Please correct me If I am wrong)
How does a macro call an assembly language instruction ?
Is it so that syscallO() when compiled is translated into the address(op code) of the instruction to execute a trap ?(But this somehow doesn't fit with concept or definition of macros that I have )
What exactly are the wrapper functions that are contained inside and are they also written in assembly language ?
Suppose , I want to create a function of my own which performs the system call then what are the things that I need to do . Do , I need to compile it to generate the machine code for performing Trap instructions ?
Man, you have to pay $156 dollars to by the thing, then you actually have to read it. You could probably get an VMS Internals and Data Structures book for under $30.
That said, let me try to translate that gibberish into English.
System calls do not use the same kind of linkage (i.e. method of passing parameters and calling functions) that other functions use.
Rather than executing a call instruction of some kind, to execute a system service, you trigger an exception (which in Intel is bizarrely called an interrupt).
The CPU expects the operating system to create a DISPATCH TABLE and store its location and size in a special hardware register(s). The dispatch table is an array of pointers to handlers for exceptions and interrupts.
Exceptions and interrupts have numbers so, when exception or interrupt number #1 occurs, the CPU invokes the 2d exception handler (not #0, but #1) in the dispatch table in kernel mode.
What exactly are the wrapper functions that are contained inside and are they also written in assembly language ?
The operating system devotes usually one (but sometimes more) exceptions to system services. You need to do some thing like this in assembly language to invoke a system service:
INT $80 ; Explicitly trigger exception 80h
Because you have to execute a specific instruction, this has to be one in assembly language. Maybe your C compiler can do assembly language in line to call system service like that. But even if it could, it would be a royal PITA to have to do it each time you wanted to call a system service.
Plus I have not filled in all the details here (only the actual call to the system service). Normally, when you call functions in C (or whatever), the arguments are pushed on the program stack. Because the stack usually changes when you enter kernel mode, arguments to system calls need to be stored in registers.
PLUS you need to identify what system service you want to execute. Usually, system services have numbers. The number of the system service is loaded into the first register (e.g., R0 or AX).
The full process when you need to invoke a system service is:
Save the registers you are going to overwrite on the stack.
Load the arguments you want to pass to the system service into hardware registers.
Load the number of the system service into the lowest register.
Trigger the exception to enter kernel mode.
Unload the arguments returned by the system service from registers
Possibly do some error checking
Restore the registers you saved before.
Instead of doing this each time you call a system service, operating systems provide wrapper functions for high level languages to use. You call the wrapper as you would normally call a function. The wrapper (in assembly language) does the steps above for you.
Because these wrappers are pretty much the same (usually the only difference is the result of different numbers of arguments), wrappers can be created using macros. Some assemblers have powerful macro facilities that allow a single macro to define all wrappers, even with different numbers of arguments.
Linux provides multiple _syscall C macros that create wrappers. There is one for each number of arguments. Note that these macros are just for operating system developers. Once the wrapper is there, everyone can use it.
How does a macro call an assembly language instruction ?
These _syscall macros have to generate in line assembly code.
Finally, note that these wrappers do not define the actual system service. That has to be set up in the dispatch table and the system service exception handler.

testing asynchronous code with buttercup

I want to test a method which takes a callback. The callback is then executed via deferred at some later point. I have
(describe
"Nimsuggest"
(it "should suggest on a simple file"
(with-current-buffer (find-file "tests/nimsuggest/simple.nim")
(expect (nim-call-epc 'sug callback)))))
but I'm not sure what to use as the testing callback.

Clojure Web App : How to step through requests

I have inherited a clojure app using the following components:
Jetty server
Compojure
Ring
In order to gain an understanding of the app, I'd like to step through requests.
I'm using Emacs as my IDE.
Is there any tool or techniques I can use to accomplish this ?
Sadly, Clojure doesn't have any readily available step debugger. One can connect to the jvm with jdb and step through the bytecode, but this will not be a direct reflection of your Clojure code (especially thanks to things like laziness, potentially causing certain code to be evaluated from different contexts in the app than the source layout would lead you to expect).
All is not lost though. Because there is a strong focus on using immutible data and pure functions in idiomatic Clojure code, it is straightforward to capture the values of the inputs your functions get at runtime, in order to investigate and / or experiment with new values. For example:
inside your core namespace, you define your handler and launch jetty, and start an nrepl server from the same process:
(ns my-server.core
(:require [ring.middleware
[json :refer (wrap-json-params)]
[multipart-params :refer (wrap-multipart-params)]]
...
[clojure.tools.nrepl.server :as nrepl-server]))
...
(defn init
[]
(when (= (System/getProperty "with_shell") "true")
(nrepl-server/start-server :port 7888))
(run-jetty handler :port 8080))
within a namespace with the code serving a particular request, you can keep track of incoming data in order to use it / investigate it in the repl
(ns my-ns.controllers.home)
(defonce debug (atom []))
(defn home
[request]
(let [in (java.util.Date.)
response (process request)
out (java.util.Date.)]
(swap! debug conj {:in request :out response :fn home :timing [in out]})
response))
Then, from the repl connection you can query the state of my-ns.controllers.hom/debug, by derefing the atom and seeing the various input and output values. This can be generalized to investigate the contents of various intermediate values, whereever you want to track execution. Since the data objects are more often than not immutible, you can have a full record to walk through if you create an atom to store the values. Note that by creating timestamps before and after calculating the request, you can profile the execution of the request handling function's body (which I have abstracted to a single function for clarity here).
There are also libraries like clojure.tools.trace if you want to use print based tracing.

Details about APPLICATION-FINDER-FN in sw-http

I'm looking to do some synchronous web-programming in Common Lisp, and I'm rounding up options. One of them is sw-http, an "HTTP server tailored for AJAX/Comet". The documentation seems to be a bit lacking because the only piece I could find tells you to
Sub-class SERVER and set the APPLICATION-FINDER-FN slot to a callback
that generates your content.
There doesn't seem to be any notes or examples about what that callback should look like (some prodding told me that it should expect a server and a connection as arguments, but nothing about what it should return or do).
setting it to something naive like
(lambda (server conn) (declare (ignore server conn)) "Hello world")
doesn't seem to do anything, so I assume I either need to write to a stream somewhere or interact with the server/connection in some less-than-perfectly-obvious way.
Any hints?
The handler takes a connection which has a response which has some chunks.
Presumably you're to add your content to the chunks (which are octets) of the response of the connection. Luckily there are some helper methods defined to make this easier.
You might try this (I couldn't get SW-HTTP to compile so I can't):
(defun hello (server connection)
(let*((response (cn-response connection))
(chunks (rs-chunks response)))
(queue-push chunks
(mk-response-status-code 200)
(queue-push chunks
(mk-response-message-body "Hello cruel world"))))
(defclass my-server (server)
((application-finder-fn :initform #'hello)))
Good luck!