I'm trying to build an android c++ app using tflite. I failed to compile the .so file on my own so I got some pre-compiled one's from the internet. I've created a dummy project to test it and it works just fine. However when I implement it on my project everything falls apart. I've checked whether the inputs are right, they are, the size is right, initialization is fine, it's almost identical with my dummy project, so what could be the issue?
Here is my code:
tflite.cpp:
#include "tflite.hpp"
tflite::tflite(uint8_t *data, size_t size)
{
try
{
lib_tflite::ErrorReporter* error_reporter;
this->m_env = lib_tflite::FlatBufferModel::BuildFromBuffer((const char *)data, size, error_reporter);
lib_tflite::ops::builtin::BuiltinOpResolver resolver;
lib_tflite::InterpreterBuilder(*this->m_env, resolver)(&m_interpreter);
if (m_interpreter->AllocateTensors() != kTfLiteOk)
{
throw std::runtime_error("Failed to allocate tensor");
}
m_interpreter->SetNumThreads(2);
this->m_input_node_count = m_interpreter->inputs().size();
this->m_output_node_count = m_interpreter->outputs().size();
for (size_t idx = 0; idx < this->m_input_node_count; ++idx)
{
int input = m_interpreter->inputs()[idx];
auto height = m_interpreter->tensor(input)->dims->data[1];
auto width = m_interpreter->tensor(input)->dims->data[2];
auto channels = m_interpreter->tensor(input)->dims->data[3];
std::vector<int> res = {(int)this->m_input_node_count, channels, width, height};
this->m_inputDims.push_back(res);
const TfLiteTensor* input_tensor = m_interpreter->input_tensor(idx);
size_t element_count = 1;
for (int i = 0; i < input_tensor->dims->size; i++)
{
element_count *= input_tensor->dims->data[i];
}
this->m_input_elem_size.push_back(element_count);
}
for (size_t idx = 0; idx < this->m_output_node_count; ++idx)
{
int output = m_interpreter->outputs()[idx];
auto height = m_interpreter->tensor(output)->dims->data[1];
auto width = m_interpreter->tensor(output)->dims->data[2];
auto channels = m_interpreter->tensor(output)->dims->data[3];
std::vector<int> res = {(int)this->m_output_node_count, channels, width, height};
this->m_outputDims.push_back(res);
const TfLiteTensor* output_tensor = m_interpreter->output_tensor(idx);
int element_count = 1;
for (int i = 0; i < output_tensor->dims->size; i++) {
element_count *= output_tensor->dims->data[i];
}
this->m_output_elem_size.push_back(element_count);
}
for (size_t idx = 0; idx < this->m_input_node_count; ++idx)
{
this->m_input_buffer.emplace_back(this->m_input_elem_size[idx], 0
);
}
for (size_t idx = 0; idx < this->m_output_node_count; ++idx)
{
this->m_output_buffer.emplace_back(this->m_output_elem_size[idx], 0
);
}
}
bool tflite::run(std::vector<float> &t_out_buffer,
std::vector<float> &t_cls_buffer,
std::vector<float> &t_buffer,
size_t region_size) noexcept
{
for(size_t idx = 0; idx < this->m_input_node_count; idx++)
{
float* data_ptr = m_interpreter->typed_input_tensor<float>(idx);
memcpy(data_ptr, t_buffer.data(), this->m_input_elem_size[idx]);
}
// This is where it fails
if (kTfLiteOk != this->m_interpreter->Invoke())
{
log_error("Failed to invoke\n");
return false;
}
for(size_t idx = 0; idx < this->m_output_node_count; idx++)
{
float* output = this->m_interpreter->typed_output_tensor<float>(idx);
this->m_output_buffer[idx] = std::vector<float> (output,
output + this->m_output_elem_size[idx]);
}
t_cls_buffer = this->m_output_buffer[0];
t_out_buffer = m_output_buffer[1];
}
/* end_of_file */
tflite.hpp:
#ifndef TFLITE_DRIVER_HPP
#define TFLITE_DRIVER_HPP
#include <memory>
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/optional_debug_tools.h"
namespace lib_tflite = ::tflite;
class tflite
{
public:
tflite() = delete;
virtual ~tflite() noexcept = default;
tflite(tflite &&) = delete;
tflite & operator=(tflite &&) = delete;
tflite(const tflite &) = delete;
tflite & operator=(tflite &) = delete;
tflite(uint8_t *data, size_t size);
bool run( std::vector<float> &t_out_buffer,
std::vector<float> &t_cls_buffer,
std::vector<float> &t_buffer,
size_t region_size) noexcept;
private:
lib_tflite::ErrorReporter* error_reporter;
lib_tflite::ops::builtin::BuiltinOpResolver resolver;
std::unique_ptr<lib_tflite::FlatBufferModel> m_env;
std::unique_ptr<lib_tflite::Interpreter> m_interpreter;
std::vector<const char *> m_input_names;
std::vector<const char *> m_output_names;
size_t m_input_node_count;
size_t m_output_node_count;
std::vector<lib_tflite::Tensor> m_inputTensors;
std::vector<lib_tflite::Tensor> m_outputTensors;
std::vector<size_t> m_input_elem_size;
std::vector<size_t> m_output_elem_size;
std::vector<std::vector<int>> m_inputDims;
std::vector<std::vector<int>> m_outputDims;
std::vector<std::vector<float>> m_input_buffer;
std::vector<std::vector<float>> m_output_buffer;
std::unique_ptr<lib_tflite::MemoryAllocation> m_memory_info;
};
#endif // TFLITE_DRIVER_HPP
/* end_of_file */
Note that my project runs on 2 threads, one get's the input and the other calls tflite. Like I've said the input's are indeed correct. The constructor is ran once, but the run function runs every frame.
Here is the output I get when I run it:
E/libc: Access denied finding property "ro.mediatek.platform"
E/libc: Access denied finding property "ro.chipname"
A/libc: Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x13c6759bfc61 in tid 27936 (processing), pid 27893 (ample.nerveblox)
I've debugged and found out the line this error happens is where I call this->m_interpreter->Invoke() inside the run function.
access denied error seems like there is no property for "ro.mediatek.platform" & "ro.chipname" if you run the "adb shell getprop".
So, I think, "ro.mediatek.platform" & "ro.chipname" are not a property.
Related
Using FFmpeg 4.0.2 and call its ffmpeg.c's main function twice causes Android app crash (using FFmpeg shared libs and JNI)
A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 20153
Though it works ok for FFmpeg 3.2.5
FFmpeg 4.0.2 main
int main(int argc, char **argv) {
int i, ret;
int64_t ti;
init_dynload();
register_exit(ffmpeg_cleanup);
setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
av_log_set_flags(AV_LOG_SKIP_REPEATED);
parse_loglevel(argc, argv, options);
if(argc>1 && !strcmp(argv[1], "-d")){
run_as_daemon=1;
av_log_set_callback(log_callback_null);
argc--;
argv++;
}
#if CONFIG_AVDEVICE
avdevice_register_all();
#endif
avformat_network_init();
show_banner(argc, argv, options);
/* parse options and open all input/output files */
ret = ffmpeg_parse_options(argc, argv);
if (ret < 0)
exit_program(1);
if (nb_output_files <= 0 && nb_input_files == 0) {
show_usage();
av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
exit_program(1);
}
/* file converter / grab */
if (nb_output_files <= 0) {
av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
exit_program(1);
}
// if (nb_input_files == 0) {
// av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
// exit_program(1);
// }
for (i = 0; i < nb_output_files; i++) {
if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
want_sdp = 0;
}
current_time = ti = getutime();
if (transcode() < 0)
exit_program(1);
ti = getutime() - ti;
if (do_benchmark) {
av_log(NULL, AV_LOG_INFO, "bench: utime=%0.3fs\n", ti / 1000000.0);
}
av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
decode_error_stat[0], decode_error_stat[1]);
if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
exit_program(69);
ffmpeg_cleanup(received_nb_signals ? 255 : main_return_code);
return main_return_code;
}
FFmpeg 3.2.5 main
int main(int argc, char **argv) {
av_log(NULL, AV_LOG_WARNING, " Command start");
int i, ret;
int64_t ti;
init_dynload();
register_exit(ffmpeg_cleanup);
setvbuf(stderr, NULL, _IONBF, 0); /* win32 runtime needs this */
av_log_set_flags(AV_LOG_SKIP_REPEATED);
parse_loglevel(argc, argv, options);
if (argc > 1 && !strcmp(argv[1], "-d")) {
run_as_daemon = 1;
av_log_set_callback(log_callback_null);
argc--;
argv++;
}
avcodec_register_all();
#if CONFIG_AVDEVICE
avdevice_register_all();
#endif
avfilter_register_all();
av_register_all();
avformat_network_init();
av_log(NULL, AV_LOG_WARNING, " Register to complete the codec");
show_banner(argc, argv, options);
/* parse options and open all input/output files */
ret = ffmpeg_parse_options(argc, argv);
if (ret < 0)
exit_program(1);
if (nb_output_files <= 0 && nb_input_files == 0) {
show_usage();
av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n",
program_name);
exit_program(1);
}
/* file converter / grab */
if (nb_output_files <= 0) {
av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
exit_program(1);
}
// if (nb_input_files == 0) {
// av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
// exit_program(1);
// }
for (i = 0; i < nb_output_files; i++) {
if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
want_sdp = 0;
}
current_time = ti = getutime();
if (transcode() < 0)
exit_program(1);
ti = getutime() - ti;
if (do_benchmark) {
av_log(NULL, AV_LOG_INFO, "bench: utime=%0.3fs\n", ti / 1000000.0);
}
av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
decode_error_stat[0], decode_error_stat[1]);
if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
exit_program(69);
exit_program(received_nb_signals ? 255 : main_return_code);
nb_filtergraphs = 0;
nb_input_streams = 0;
nb_input_files = 0;
progress_avio = NULL;
input_streams = NULL;
nb_input_streams = 0;
input_files = NULL;
nb_input_files = 0;
output_streams = NULL;
nb_output_streams = 0;
output_files = NULL;
nb_output_files = 0;
return main_return_code;
}
So what could be issue? It seems FFmpeg 4.0.2 doesn't release something (resources or its static variables to initial values after the first command)
Adding next lines from FFmpeg 3.2.5 to FFmpeg 4.0.2 to the end of main function solved the problem (I downloaded FFmpeg 3.2.5 as someone's Android project so that user added those lines)
nb_filtergraphs = 0;
nb_input_streams = 0;
nb_input_files = 0;
progress_avio = NULL;
input_streams = NULL;
nb_input_streams = 0;
input_files = NULL;
nb_input_files = 0;
output_streams = NULL;
nb_output_streams = 0;
output_files = NULL;
nb_output_files = 0;
I want my Android application to create a fake virtual device, to achieve this the device needs to be rooted and uinput module is needed.
I am using the following code to create the device, calling
static{ System.loadLibrary("myModule"); }
CreateVirtualDevice("Devname",0x123,0x123);
inside my java code.
Here the native code:
#include <string.h>
#include <jni.h>
#include <fcntl.h>
#include <linux/input.h>
#include <linux/uinput.h>
static int fd;
static struct uinput_user_dev dev;
short int analog_axis_list[] = { ABS_X,ABS_Y,ABS_RX,ABS_RY, -1};
jint Java_com_example_app_MyClass_CreateVirtualDevice(
JNIEnv* env, jobject thiz, jstring param, jint param2, jint param3) {
int i;
memset(&dev, 0, sizeof(dev));
fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
if (fd < 0)
return -1;
if(ioctl(fd, UI_SET_EVBIT, EV_ABS)<0) return -4;
for(i=0;analog_axis_list[i]>=0;i++){
if(ioctl(fd,UI_SET_ABSBIT,analog_axis_list[i])<0) return -5;
dev.absmax[analog_axis_list[i]]=32767;
dev.absmin[analog_axis_list[i]]=-32768;
}
const char *cparam = (*env)->GetStringUTFChars(env, param, 0);
snprintf(dev.name, UINPUT_MAX_NAME_SIZE, cparam);
(*env)->ReleaseStringUTFChars(env, param, cparam);
dev.id.bustype = BUS_VIRTUAL;
dev.id.vendor = param2;
dev.id.product = param3;
dev.id.version = 1;
if (write(fd, &dev, sizeof(dev)) < 0)
return -7;
if (ioctl(fd, UI_DEV_CREATE) < 0)
return -8;
return 0;
}
The device is successfully created, and the return value is 0.
Inside input.h the ABS values are so defined:
#define ABS_X 0x00
#define ABS_Y 0x01
#define ABS_RX 0x03
#define ABS_RY 0x04
But when checking the axis on android, I get proper values for AXIS_X and AXIS_Y, but ABS_RX and ABS_RY have wrong values. I used this code to check the axis values:
InputDevice device = InputDevice.getDevice(ids[position]);
List<InputDevice.MotionRange> ranges = device.getMotionRanges();
StringBuilder sb = new StringBuilder("");
if(ranges.size()==0){
sb.append("NO_MOTION_RANGES");
}
else{
int i = 0;
for(InputDevice.MotionRange range:ranges) {
if(i>0) {
sb.append(",");
}
sb.append(MotionEvent.axisToString(range.getAxis()));
sb.append("(").append(range.getAxis()).append(")");
i++;
}
}
return sb.toString();
And the result is:
AXIS_X(0),AXIS_Y(1),AXIS_Z(11),AXIS_RZ(14)
I am using the latest NDK release (r10d) without any particular settings enabled. What can cause these errors?
I want to point out that it's my code to have something wrong, because with an actual controller the axis numbers are correct.
Edit 1:
I tried to return analog_axis_list[2], which is ABS_RX, at the end of my function instead of 0 and it returns 3, so I think I'm passing a wrong type to the ioctl call.
Which type should I choose?
Android uses AXIS_Z and AXIS_RZ for the right stick; this is consistent with USB HID.
I'm trying to share data between kernel and user space. The ultimate goal is to port it to Android, so I'm using unix domain sockets. (I don't know if this is the best option).
I have a kernel module acting as socket client and a c program acting as socket server. And vice-versa, a kernel module acting as socket server and a c program acting as socket client.
Programs are very simple. Servers just send a string to clients and they print it.
I run server_user.c and then I try to insert client_module.ko using insmod. I get the following error:
Kernel panic - not syncing: stack - protector: Kernel stack is corrupted in: ffffffffa0005157
drm-kms-helper: panic occurred, switching back to text console
What's wrong?
Module Server
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/socket.h>
#include <linux/net.h>
#include <linux/un.h>
#include <net/sock.h>
#define SOCK_PATH "/tmp/usocket"
#define LISTEN 10
struct socket *sock = NULL;
struct socket *newsock = NULL;
static int __init server_module_init( void ) {
int retval;
char* string = "hello_world";
struct sockaddr_un addr;
struct msghdr msg;
struct iovec iov;
mm_segment_t oldfs;
// create
retval = sock_create(AF_UNIX, SOCK_STREAM, 0, &sock);
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, SOCK_PATH);
// bind
retval = sock->ops->bind(sock,(struct sockaddr *)&addr, sizeof(addr));
// listen
retval = sock->ops->listen(sock, LISTEN);
//accept
retval = sock->ops->accept(sock, newsock, 0);
//sendmsg
memset(&msg, 0, sizeof(msg));
memset(&iov, 0, sizeof(iov));
msg.msg_name = 0;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iov->iov_base = string;
msg.msg_iov->iov_len = strlen(string)+1;
msg.msg_iovlen = 1;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
oldfs = get_fs();
set_fs(KERNEL_DS);
retval = sock_sendmsg(newsock, &msg, strlen(string)+1);
set_fs(oldfs);
return 0;
}
static void __exit server_module_exit( void ) {
printk(KERN_INFO "Exit usocket.");
}
module_init( server_module_init );
module_exit( server_module_exit );
MODULE_LICENSE("GPL");
Module Client
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/un.h>
#include <linux/net.h>
#include <net/sock.h>
#include <linux/socket.h>
#define SOCK_PATH "/tmp/usocket"
#define MAX 100
struct socket *sock = NULL;
static int __init client_module_init( void ) {
int retval;
char str[MAX];
struct sockaddr_un addr;
struct msghdr msg;
struct iovec iov;
mm_segment_t oldfs;
printk(KERN_INFO "Start client module.\n");
// create
retval = sock_create(AF_UNIX, SOCK_STREAM, 0, &sock);
// connect
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, SOCK_PATH);
retval = sock->ops->connect(sock, (struct sockaddr *)&addr, sizeof(addr), 0);
// recvmsg
memset(&msg, 0, sizeof(msg));
memset(&iov, 0, sizeof(iov));
msg.msg_name = 0;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_iov->iov_base= str;
msg.msg_iov->iov_len= strlen(str)+1;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
oldfs = get_fs();
set_fs(KERNEL_DS);
retval = sock_recvmsg(sock, &msg, strlen(str)+1, 0);
set_fs(oldfs);
// print str
printk(KERN_INFO "client module: %s.\n",str);
// release socket
sock_release(sock);
return 0;
}
static void __exit client_module_exit( void )
{
printk(KERN_INFO "Exit client module.\n");
}
module_init( client_module_init );
module_exit( client_module_exit );
MODULE_LICENSE("GPL");
User Server
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCK_PATH "/tmp/usocket"
int send_msg_to_client(int socketfd, char* data) {
struct msghdr msg;
struct iovec iov;
int s;
memset(&msg, 0, sizeof(msg));
memset(&iov, 0, sizeof(iov));
msg.msg_name = NULL;
msg.msg_namelen = 0;
iov.iov_base = data;
iov.iov_len = strlen(data)+1;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
s = sendmsg(socketfd, &msg, 0);
printf("after send - iov_base: %s, length: %d\n", (char *) msg.msg_iov->iov_base, (int) strlen(msg.msg_iov->iov_base));
if(s < 0){
perror("sendmsg");
return 0;
}
return s;
}
int main(int argc, char* argv[])
{
if (argc != 2) {
printf("Usage: $ %s <string>\n",argv[0]);
return 0;
}
int s, s2, len, slen;
socklen_t t;
struct sockaddr_un local, remote;
char* data = argv[1];
printf("print data: %s\n",data);
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
memset(&local, 0, sizeof(local));
local.sun_family = AF_UNIX;
strcpy(local.sun_path, SOCK_PATH);
unlink(local.sun_path);
len = strlen(local.sun_path) + sizeof(local.sun_family);
if (bind(s, (struct sockaddr *)&local, len) == -1) {
perror("bind");
exit(1);
}
if (listen(s, 5) == -1) {
perror("listen");
exit(1);
}
printf("Waiting for a connection...\n");
t = sizeof(remote);
if ((s2 = accept(s, (struct sockaddr *)&remote, &t)) == -1) {
perror("accept");
exit(1);
}
printf("Connected.\n");
slen = send_msg_to_client(s2, data);
if(slen < 0)
perror("send");
close(s2);
return 0;
}
User Client
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCK_PATH "/tmp/usocket"
#define MAX 100
int recv_msg_from_server(int socketfd, char data[MAX]) {
struct msghdr msg;
struct iovec iov;
int s;
memset(&msg, 0, sizeof(msg));
memset(&iov, 0, sizeof(iov));
msg.msg_name = NULL;
msg.msg_namelen = 0;
iov.iov_base = data;
iov.iov_len = MAX;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
s = recvmsg(socketfd, &msg, 0);
printf("after recv - iov_base: %s, length: %d\n", (char *) msg.msg_iov->iov_base, (int) strlen(msg.msg_iov->iov_base));
if(s < 0){
perror("recvmsg");
}
return s;
}
int main(void)
{
int s, len, slen;
struct sockaddr_un remote;
char data[MAX];
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
printf("Trying to connect...\n");
memset(&remote, 0, sizeof(remote));
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCK_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
if (connect(s, (struct sockaddr *)&remote, len) == -1) {
perror("connect");
exit(1);
}
printf("Connected.\n");
slen = recv_msg_from_server(s, data);
if (slen < 0) {
perror("recvmsg");
}
//printf("print data received > %s\n", data);
close(s);
return 0;
}
I have just faced a similar issue (with UNIX datagrams though), and I believe there is a bug in the unix_mkname() function which is part of the kernel: this function makes sure the sun_path field of the given sockaddr_un structure is always null terminated by adding a NUL character after the end of that field. Since this is the last field, it will corrupt the area (stack or heap) where that structure has been allocated.
The best solution is to patch that function in the kernel source code, so that it only sets to NUL the last character of the sun_path field. Meanwhile, you can make your code work by decreasing by 1 byte the size you give for the sockaddr_un structure:
Module Server
// bind
retval = sock->ops->bind(sock,(struct sockaddr *)&addr, sizeof(addr) - 1);
Module Client
retval = sock->ops->connect(sock, (struct sockaddr *)&addr, sizeof(addr) - 1, 0);
As I am using UNIX datagrams, I cannot really tell if it fixes the issue for bind() and connect(), but a least, it fixes it for sock_sendmsg().
#shu-suzuki: thanks for the leads.
After 5 years I came back here...
I again stucked with this problem and found that I did the same thing 5 years ago.
The cause is as in Tey's answer and the solution is OK (sutbract 1 from the length) but here's another solution.
What you can do is to use struct sockaddr_storage as struct sockaddr_un. As far as I read the kernel code this is what they use to handle bind system call from user space.
sockeaddr_storage is larger than sockaddr_un so kernel code can write beyond the sizeof(sockaddr_un).
The code should be like
struct sockaddr_storage addrStorage;
struct sockaddr_un* addr;
memset(&addrStorage, 0, sizeof(addrStorage));
addr = (struct sockaddr_un*)&addrStorage;
addr->sun_family = AF_UNIX;
strcpy(addr->sun_path, "/my/sock/name");
kernel_bind(listenSock, (struct sockaddr*)addr, sizeof(*addr));
This looks working for me.
I am trying to run a simple IOCTL example on Android. I am using kernel 2.6 and ICS. The module is properly registered/unregistered (insmod/rmmod). However, every time a try to execute ./user_app on the emulator, I always get
error: first ioctl: Not a typewriter
error: second ioctl: Not a typewriter
message: `�
This is clearly a ENOTTY. I debugged the application, and no fops procedure (device_ioctl, read_ioctl and write_ioctl) is being executed.
I would like to know if there is any restriction with the usage/implementation of IOCTL on Android. Thank you very much in advance.
--Raul
Here is the code:
module.c
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#define MY_MACIG 'G'
#define READ_IOCTL _IOR(MY_MACIG, 0, int)
#define WRITE_IOCTL _IOW(MY_MACIG, 1, int)
int main(){
char buf[200];
int fd = -1;
if ((fd = open("/data/local/afile.txt", O_RDWR)) < 0) {
perror("open");
return -1;
}
if(ioctl(fd, WRITE_IOCTL, "hello world") < 0)
perror("first ioctl");
if(ioctl(fd, READ_IOCTL, buf) < 0)
perror("second ioctl");
printf("message: %s\n", buf);
return 0;
}
user_app.c
#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#define MY_MACIG 'G'
#define READ_IOCTL _IOR(MY_MACIG, 0, int)
#define WRITE_IOCTL _IOW(MY_MACIG, 1, int)
static char msg[200];
static ssize_t device_read(struct file *filp, char __user *buffer, size_t length, loff_t *offset)
{
...
}
static ssize_t device_write(struct file *filp, const char __user *buff, size_t len, loff_t *off)
{
...
}
char buf[200];
int device_ioctl(struct file *filep, unsigned int cmd, unsigned long arg) {
int len = 200;
switch(cmd) {
case READ_IOCTL:
...
break;
case WRITE_IOCTL:
...
break;
default:
return -ENOTTY;
}
return len;
}
static struct file_operations fops = {
.read = device_read,
.write = device_write,
.unlocked_ioctl = device_ioctl,
};
static int __init example_module_init(void)
{
printk("registering module");
return 0;
}
static void __exit example_module_exit(void)
{
printk("unregistering module");
}
module_init(example_module_init);
module_exit(example_module_exit);
MODULE_LICENSE("GPL");
It this the whole code that you've posted? You don't register a char device when initializing a module, so this can't work.
Also, be carefull when assigning IOCTLS numbers. When using reserved IOCTL on a wrong file, you will get ENOTTY. Consult this to make sure you don't have conflicts.
Read more about char drivers here.
Im writing a programme that opens and openGL windows with an image and connects to my android device where the user uses the device as a sort of trackpad to pan and zoom in and out. All is working fine however the programme gets stuck in the glutMainLoop and will not proceed with accepting data from the device. Apparently glutIdleFunc is the solution to my problem however i cant see how to implement this in my code without getting a memory error? Could someone show me how to put the function into my code so it runs the connection code as well as the opengl stuff?
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <vrpn_Shared.h>
#include <vrpn_Analog.h>
#include <vector>
#include <GL/freeglut.h>
#include <imageviewer.h>
using namespace std;
int done = 0;
int accepted = 0; // Signals that the program should exit
unsigned tracker_stride = 1; // Every nth report will be printed
//-------------------------------------
// This section contains the data structure that holds information on
// the devices that are created. For each named device, a remote of each
// type analog is created.
class device_info {
public:
char *name;
vrpn_Analog_Remote *ana;
};
const unsigned MAX_DEVICES = 2;
//-------------------------------------
// This section contains the data structure that is used to determine how
// often to print a report for each sensor of each tracker. Each element
// contains a counter that is used by the callback routine to keep track
// of how many it has skipped. There is an element for each possible sensor.
// A new array of elements is created for each new tracker object, and a
// pointer to it is passed as the userdata pointer to the callback handlers.
class t_user_callback {
public:
char t_name[vrpn_MAX_TEXT_LEN];
vector<unsigned> t_counts ;
};
//Callback handlers
void VRPN_CALLBACK handle_analog (void *userdata, const vrpn_ANALOGCB a)
{
int i;
const char *name = (const char *)userdata;
printf("Input from %s:\n \n %5.0f", name, a.channel[0]);
for (i = 1; i < a.num_channel; i++) {
printf(" %5.0f \n", a.channel[1]);
}
printf(" \n");
}
int main (int argc, char * argv [])
{
int print_for_tracker = 1; // Print tracker reports?
int print_for_button = 1; // Print button reports?
int print_for_analog = 1; // Print analog reports?
int print_for_dial = 1; // Print dial reports?
int print_for_text = 1; // Print warning/error messages?
device_info device_list[MAX_DEVICES];
unsigned num_devices = 0;
int i;
// Parse arguments, creating objects
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-notracker")) {
print_for_tracker = 0;
} else if (!strcmp(argv[i], "-nobutton")) {
print_for_button = 0;
} else if (!strcmp(argv[i], "-noanalog")) {
print_for_analog = 0;
} else if (!strcmp(argv[i], "-nodial")) {
print_for_dial = 0;
} else if (!strcmp(argv[i], "-notext")) {
print_for_text = 0;
} else if (!strcmp(argv[i], "-trackerstride")) {
if (tracker_stride <= 0) {
fprintf(stderr, "-trackerstride argument must be 1 or greater\n");
return -1;
}
} else { // Create a device and connect to it.
device_info *dev;
// Name the device and open it as everything
dev = &device_list[num_devices];
dev->name = argv[i];
dev->ana = new vrpn_Analog_Remote(dev->name);
if (print_for_analog) {
printf(" Analog");
dev->ana->register_change_handler(dev->name, handle_analog);
}
printf(".\n");
num_devices++;
}
}
// main interactive loop
printf("Press ^C to exit.\n");
while ( ! done ) {
unsigned i;
// Let all the devices do their things
for (i = 0; i < num_devices; i++) {
device_list[i].ana->mainloop();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowSize(400,300);
glutInitWindowPosition(200,100);
glutCreateWindow("ImageViewer");
init();
glutDisplayFunc(display);
glutMotionFunc(drag);
glutMouseFunc(mouse);
// glutIdleFunc(IdleFunc);
glutMainLoop();
}
}
return 0;
}
glut is fine if it can manage all of the input devices, and everything is event-driven from the inputs that it manages. Once you have unmanaged input devices or non-event-based processing, you probably want to use something other than glut. Your other alternative is to fork and run your asynchronous stuff in a separate process (or thread).