Can eBPF's perf_submit() be used in a socket_filter program as well? - bpf

So I was trying to send some data from the kernel space program to the user space program using perf_submit.
I've done some studies and here(https://github.com/iovisor/bcc/issues/2423), yonghong-song answered(the last comment) that a socket_filter program can not access bpf_perf_event_output helper and therefore it can only be used for tracing program types.
However, on BCC reference site(https://github.com/iovisor/bcc/blob/master/docs/reference_guide.md#2-bpf_perf_output), if you ctrl+f and search for : 3. perf_submit()
, it says on the fifth line that "for SOCKET_FILTER programs, the struct __sk_buff *skb must be used instead."
I believe this infers that perf_submit() can be used for socket_filter programs as well?
So I have hard time figuring out if perf_submit() can indeed be used for a socket filter program. Maybe some functionalities have been added since Yonghong-song answered the question above?
I'm checking if perf_submit() would work with a socket filter and there's not really a line of code that grabs the data output by perf_submit because just addint perf_submit() in the kernel program already omitted an error.
Here's the code for my program :
from bcc import BPF
# Network interface to be monoitored
INTERFACE = "br-netrome"
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <net/sock.h>
#include <bcc/proto.h>
#include <linux/bpf.h>
#define IP_TCP 6
#define IP_UDP 17
#define IP_ICMP 1
#define ETH_HLEN 14
BPF_PERF_OUTPUT(events); // has to be delcared outside any function
int packet_monitor(struct __sk_buff *skb) {
u8 *cursor = 0;
u64 saddr;
u64 daddr;
u64 ttl;
u64 hchecksum;
struct ethernet_t *ethernet = cursor_advance(cursor, sizeof(*ethernet));
if (!(ethernet -> type == 0x0800)) {
return 0; // drop
}
struct ip_t *ip = cursor_advance(cursor, sizeof(*ip));
/*
if (ip->nextp != IP_TCP)
{
if (ip -> nextp != IP_UDP)
{
if (ip -> nextp != IP_ICMP)
return 0;
}
}
*/
saddr = ip -> src;
daddr = ip -> dst;
ttl = ip -> ttl;
hchecksum = ip -> hchecksum;
events.perf_submit(skb, &saddr, sizeof(saddr));
// bpf_trace_printk("saddr = %llu, daddr = %llu, ttl = %llu", saddr, daddr, ttl); // only three arguments can be passed using printk
// bpf_trace_printk("Incoming packet!!\\n");
return -1;
}
and here is the error code :
R0=inv2048 R6=ctx(id=0,off=0,imm=0) R7=inv0 R10=fp0,call_-1
4: (20) r0 = *(u32 *)skb[26]
5: (7b) *(u64 *)(r10 -8) = r0
6: (18) r2 = 0xffff9bde204ffa00
8: (18) r7 = 0xffffffff
10: (bf) r4 = r10
11: (07) r4 += -8
12: (bf) r1 = r6
13: (18) r3 = 0xffffffff
15: (b7) r5 = 8
16: (85) call bpf_perf_event_output#25
unknown func bpf_perf_event_output#25
Traceback (most recent call last):
File "packet_monitor.py", line 68, in <module>
function_skb_matching = bpf.load_func("packet_monitor", BPF.SOCKET_FILTER)
File "/usr/lib/python2.7/dist-packages/bcc/__init__.py", line 397, in load_func
(func_name, errstr))

TL;DR. BPF programs of type BPF_PROG_TYPE_SOCKET_FILTER can use bpf_perf_event_output only starting with Linux 5.4.
Which helpers a given BPF program has access to is defined by the get_func_proto member of objects struct bpf_verifier_ops. You can find which bpf_verifier_ops object corresponds to which program type by reading function find_prog_type() and file bpf_types.h. In the case of BPF_PROG_TYPE_SOCKET_FILTER, the corresponding function is sk_filter_func_proto().
If you git blame that function on recent kernel sources, you will get something like the following (you can do the same with GitHub's blame feature):
$ git blame net/core/filter.c
[...]
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6080) static const struct bpf_func_proto *
5e43f899b03a3 (Andrey Ignatov 2018-03-30 15:08:00 -0700 6081) sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6082) {
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6083) switch (func_id) {
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6084) case BPF_FUNC_skb_load_bytes:
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6085) return &bpf_skb_load_bytes_proto;
4e1ec56cdc597 (Daniel Borkmann 2018-05-04 01:08:15 +0200 6086) case BPF_FUNC_skb_load_bytes_relative:
4e1ec56cdc597 (Daniel Borkmann 2018-05-04 01:08:15 +0200 6087) return &bpf_skb_load_bytes_relative_proto;
91b8270f2a4d1 (Chenbo Feng 2017-03-22 17:27:34 -0700 6088) case BPF_FUNC_get_socket_cookie:
91b8270f2a4d1 (Chenbo Feng 2017-03-22 17:27:34 -0700 6089) return &bpf_get_socket_cookie_proto;
6acc5c2910689 (Chenbo Feng 2017-03-22 17:27:35 -0700 6090) case BPF_FUNC_get_socket_uid:
6acc5c2910689 (Chenbo Feng 2017-03-22 17:27:35 -0700 6091) return &bpf_get_socket_uid_proto;
7c4b90d79d0f4 (Allan Zhang 2019-07-23 17:07:24 -0700 6092) case BPF_FUNC_perf_event_output:
7c4b90d79d0f4 (Allan Zhang 2019-07-23 17:07:24 -0700 6093) return &bpf_skb_event_output_proto;
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6094) default:
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6095) return bpf_base_func_proto(func_id);
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6096) }
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6097) }
[...]
As you can see, BPF_FUNC_perf_event_output was only recently added to the list of helpers these BPF programs can call. The commit which added this support, 7c4b90d79d0f4, was merged in Linux v5.4:
$ git describe --contains 7c4b90d79d0f4
v5.4-rc1~131^2~248^2~20

Related

Using both TCP and UDP protocols seem not to work on Ethernet Shield w5100

I'm having a problem using both TCP and UDP in the same sketch. What appears to happen is that if the same socket is reused for UDP after it was in use for TCP, UPD fails to receive data. I was able to reproduce this with the WebServer example. I've added to it a DNS query once in every 10 seconds to query yahoo.com IP address. The DSN queries succeed if I'm not creating any client traffic from the browser. After I query the server over HTTP over TCP, the DSN queries start to fail. DNS queries are implemented in UDP. This is the code that I'm using:
/*
Web Server
A simple web server that shows the value of the analog input pins.
using an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
* Analog inputs attached to pins A0 through A5 (optional)
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
modified 02 Sept 2015
by Arturo Guadalupi
*/
#include <SPI.h>
#include <Ethernet.h>
#include <Dns.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
unsigned long t0;
void setup() {
// You can use Ethernet.init(pin) to configure the CS pin
//Ethernet.init(10); // Most Arduino shields
//Ethernet.init(5); // MKR ETH shield
//Ethernet.init(0); // Teensy 2.0
//Ethernet.init(20); // Teensy++ 2.0
//Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet
//Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Ethernet WebServer Example");
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
// start the server
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
t0 = millis();
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println("Refresh: 5"); // refresh the page automatically every 5 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
}
if (millis() - t0 > 10000)
{
DNSClient dns;
dns.begin(IPAddress(8,8,8,8));
IPAddress yahoo;
if (dns.getHostByName("yahoo.com", yahoo) == 1)
{
Serial.print("Yahoo: ");
Serial.print(yahoo[0]);
Serial.print(".");
Serial.print(yahoo[1]);
Serial.print(".");
Serial.print(yahoo[2]);
Serial.print(".");
Serial.println(yahoo[3]);
}
else
{
Serial.println("Failed to query yahoo.com IP address");
}
t0 = millis();
}
}
Is this a known issue? Can someone please help in identifying the problem in my code, or if there is a workaround for this issue? Can it be a hardware issue? I'm using SunFounder boards, not the original Arduino boards.
Thanks a lot,
Boaz,

Camera bar code scan crash with iPhone 11 and iOS 13

We have code in a Xamarin App using bar code scanning. It has been working successfully for 3 years. We have found an issue with the iPhone 11 pro and its three camera setup.
_captureSession = new AVCaptureSession();
CameraMetaDataDelegate del = null;
AVCaptureDevice captureDevice =
AVCaptureDevice.GetDefaultDevice(AVMediaType.Video);
if (captureDevice != null)
{
var videoInput = AVCaptureDeviceInput.FromDevice(captureDevice, out error);
if (videoInput != null) { _captureSession.AddInput(videoInput); }
else { iApp.Log.Error("Video capture error: " + error.LocalizedDescription); }
var metaDataOutput = new AVCaptureMetadataOutput();
_captureSession.AddOutput(metaDataOutput);
del = new CameraMetaDataDelegate(this, _layer);
metaDataOutput.SetDelegate(del, CoreFoundation.DispatchQueue.MainQueue);
metaDataOutput.MetadataObjectTypes = metaDataOutput.AvailableMetadataObjectTypes;
_videoPreviewLayer = new AVCaptureVideoPreviewLayer(_captureSession) {
Frame = View.Bounds,
Orientation = (AVCaptureVideoOrientation)InterfaceOrientation,
};
View.Layer.AddSublayer(_videoPreviewLayer);
...
We have the the necessary entitlements in the info.plist
<key>NSCameraUsageDescription</key>
<string>Scan Barcodes</string>
It seems to be crashing on the AVCaptureDeviceInput. The "Application would like access to the camera" popup remains on the screen after the crash.
This works on older iPhones. We have not tried on an iPhone 11 non-pro.
Log looks like this
default 17:46:52.725211 -0500 tccd PID[30] is checking access for target PID[933]
default 17:46:52.734801 -0500 mediaserverd Updating configuration of monitor <RBSProcessMonitorConfiguration: 0x10cc25430; id: M30-27; qos: 25> {
predicates = {
<RBSProcessPredicate: 0x103735f30> {
predicate = <RBSCompoundPredicate; <RBSCompoundPredicate; <RBSProcessEUIDPredicate; 501>; <RBSProcessBKSLegacyPredicate: 0x103104870>>; <RBSProcessBundleIdentifierPredicate; com.apple.InCallService>>;
};
}
descriptor = <RBSProcessStateDescriptor: 0x10cc46300; values: 11> {
namespaces = {
com.apple.frontboard.visibility;
}
};
}
default 17:46:52.735816 -0500 mediaserverd BKSApplicationStateMonitor updated with invalid process
default 17:46:52.736059 -0500 runningboardd [daemon<com.apple.mediaserverd>:30] handle lookup could not find a matching process
default 17:46:52.736188 -0500 mediaserverd <<<< FigCaptureClientSessionMonitor >>>> -[FigCaptureClientSessionMonitor _updateClientStateCondition:newValue:]: <private> Updating client with application state "Foregrounded" and layout state "None"
default 17:46:52.736343 -0500 mediaserverd <<<< FigCaptureSession >>>> captureSession_updateRunningCondition: <0x102eddb90> (PID:933): ClientStartedSession:0 Cam/Audio:0/0 bg:0 prewarming:0 int:0 windowed:0 devStolen:0, pressured:0, active:0 shouldRun:0, start:0 stop:0 stopRecordingIfActive:0
default 17:46:52.746798 -0500 mediaserverd Creating remote service object
default 17:46:52.748227 -0500 applecamerad <private>
default 17:46:52.748255 -0500 applecamerad <private>
default 17:46:52.748282 -0500 applecamerad <private>
default 17:46:52.748314 -0500 applecamerad <private>
default 17:46:52.748348 -0500 applecamerad H10ISPFlickerDetectorCreate - HWType = 3; pContext = 0x104c0e830
default 17:46:52.748377 -0500 applecamerad FlickerDetector: ArbiterClient resource access granted=1
default 17:46:52.749880 -0500 mediaserverd 2325: [volm/inpt/0] on device [ type: vhaw; id: 233; addr: 0x109a33d60; hidden: 0; VA strms: { i/238/0x109a34bc0, }; agg dev: [ id: 203; addr: 0x10c38d800; uid: "VAD [vhaw] AggDev 6"; virt strms: { }; phys devs: { [ id: 94; addr: 0x102e1af80; uid: "Hawking"; streams: { i/95/0x102e1b2d0, } ] } ] ]: 1.000000.
default 17:46:52.749914 -0500 mediaserverd 161: Setting Input Volume: 18.000000 dB, Final HW Volume: 18.000000 dB, Final SW Volume: 0.000000 dB
default 17:46:52.749945 -0500 mediaserverd 162: PhysicalDevice UID = "Hawking"
default 17:46:52.750012 -0500 mediaserverd 163: Scope = 1768845428 ("inpt")
default 17:46:52.750041 -0500 mediaserverd 164: Element = 0 ("0")
default 17:46:52.750405 -0500 applecamerad AURemoteIO.cpp:1546:Start: Starting AURemoteIO(0x107008c40)
output client: 1 ch, 0 Hz, Float32, output HW: 1 ch, 0 Hz, Float32
input client: 2 ch, 16000 Hz, Float32, inter, input HW: 2 ch, 16000 Hz, Float32, non-inter
default 17:46:52.750485 -0500 applecamerad AURemoteIO.cpp:1556:Start: work interval port 0x607b
default 17:46:52.751151 -0500 mediaserverd MEDeviceStreamClient.cpp:216:AddRunningClient: AQME device VirtualAudioDevice_Hawking: client starting: <RemoteIOClient#0x10500e600(#0x10500e658); input; CMSession(applecamerad[116])>; running count now 1
default 17:46:52.751186 -0500 mediaserverd 671: Client request to start IO proc ID 0x109a4abc0 on VAD 233.
default 17:46:52.751276 -0500 mediaserverd <<<< FigCaptureSession >>>> captureSession_SetConfiguration: <0x102eddb90> (PID:933): New configuration: <private>
default 17:46:52.751375 -0500 mediaserverd <<<< FigCaptureSession >>>> captureSession_updateRunningCondition: <0x102eddb90> (PID:933): ClientStartedSession:0 Cam/Audio:0/0 bg:0 prewarming:0 int:0 windowed:0 devStolen:0, pressured:0, active:0 shouldRun:0, start:0 stop:0 stopRecordingIfActive:0
default 17:46:52.751608 -0500 mediaserverd 599: Starting IO type 0 on AggregateDevice 203.
default 17:46:52.751655 -0500 mediaserverd HALS_IOContext::StartIOProcID: 206 Hawking (VAD [vhaw] AggDev 6):
default 17:46:52.753329 -0500 mediaserverd starting ProcID 0x21 state: Prewarm: 0 Play: 0 State: Stopped IOProc 0x21: no
default 17:46:52.753407 -0500 mediaserverd HALS_Device::_GetCombinedVolumeScalar: client 0 is not present and has a combined volume scalar is 1.000000
default 17:46:52.753633 -0500 mediaserverd <<<< FigCaptureSession >>>> captureSession_SetConfiguration: <0x102eddb90> (PID:933): New configuration: <private>
default 17:46:52.753700 -0500 CommCenter #I <private> request: <private>.
default 17:46:52.753812 -0500 mediaserverd <<<< FigCaptureSession >>>> captureSession_updateRunningCondition: <0x102eddb90> (PID:933): ClientStartedSession:0 Cam/Audio:1/0 bg:0 prewarming:0 int:0 windowed:0 devStolen:0, pressured:0, active:0 shouldRun:0, start:0 stop:0 stopRecordingIfActive:0
default 17:46:52.753934 -0500 CommCenter #I Received Audio State: <private>
default 17:46:52.753974 -0500 nfcd 00000001 57f02250 -[NFCameraStateMonitor _updateCameraStateValue:]:203 current=0, new=5
default 17:46:52.754014 -0500 mediaserverd 65: :413:: IOProc (AggregateDevice 203, IO type NonNullIOProc) running state is now running (2).
default 17:46:52.754047 -0500 nfcd 00000001 57f02250 -[NFCameraStateMonitor _updateCameraStateValue:]:203 current=5, new=7
default 17:46:52.754078 -0500 nfcd 00000001 57f02250 -[NFCameraStateMonitor _updateCameraStateValue:]:203 current=7, new=15
default 17:46:52.754405 -0500 backboardd Connection removed: IOHIDEventSystemConnection uuid:07F3B331-86A0-445F-ABA7-DDDA546740A7 pid:933 process:MYAPP5 type:Passive entitlements:0x0 caller:BackBoardServices: <redacted> + 384 attributes:{
HighFrequency = 1;
bundleID = "com.MYCOMPANY.mobile.MYAPP.development";
pid = 933;
} inactive:0 events:102 mask:0x800
default 17:46:52.754543 -0500 backboardd HIDAnalytics Unregister Send event com.apple.hid.queueUsage
default 17:46:52.755359 -0500 SpringBoard Workspace connection invalidated for <FBWorkspaceServer: 0x2822ce040>
default 17:46:52.755514 -0500 SpringBoard [application<com.MYCOMPANY.mobile.MYAPP.development>:933] Now flagged as pending exit for reason: workspace client connection invalidated
default 17:46:52.755776 -0500 SpringBoard Updating configuration of monitor <RBSProcessMonitorConfiguration: 0x2823ed600; id: M57-6; qos: 25> {
predicates = {
<RBSProcessPredicate: 0x283a521b0> {
predicate = <RBSCompoundPredicate; <RBSCompoundPredicate; <RBSProcessEUIDPredicate; 501>; <RBSProcessBKSLegacyPredicate: 0x283a40340>>; <RBSProcessBundleIdentifierPredicate; com.apple.springboard>>;
};
<RBSProcessPredicate: 0x283a5c2e0> {
predicate = <RBSCompoundPredicate; <RBSCompoundPredicate; <RBSProcessEUIDPredicate; 501>; <RBSProcessBKSLegacyPredicate: 0x283a40340>>; <RBSProcessBundleIdentifierPredicate; com.apple.MailCompositionService>>;
};
<RBSProcessPredicate: 0x283a5c2d0> {
predicate = <RBSCompoundPredicate; <RBSProcessBundleIdentifierPredicate; com.apple.ScreenshotServicesService>; <RBSCompoundPredicate; <RBSProcessEUIDPredicate; 501>; <RBSProcessBKSLegacyPredicate: 0x283a40340>>>;
};
<RBSProcessPredicate: 0x283a5d2e0> {
predicate = <RBSCompoundPredicate; <RBSCompou<…>
default 17:46:52.755823 -0500 SpringBoard connection invalidated
default 17:46:52.755869 -0500 SpringBoard connection invalidated
default 17:46:52.756102 -0500 CommCenter Client [<private>] disconnected (conn=0x101590a20), client list size 35
default 17:46:52.756159 -0500 locationd #Spi, Connection invalidated for process <private>
Not sure if it is another permissions issue, or using the wrong AV API, or need another preliminary step. Perhaps a race condition that should delay until camera responds available?
Junior Jiang's suggestion led me down the path to getting the iPhone 11 pro bar code scanning. First it really is necessary to check the authorization status, which used to fire on the first request before. Once this is established, then the camera will work. The second problem is that, at least in Xamarin C#, I could not assign the list of AvailableMetaDataObjectTypes. There is an earlier Stack Overflow which directs to use that list: Stack Overflow Xcode 9/Swift 4 AVCaptureMetadataOutput setMetadataObjectTypes use availableMetadataObjectTypes
But now the solution was to explicitly state which ones to use.
_captureSession = new AVCaptureSession();
CameraMetaDataDelegate del = null;
var authStatus = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);
AVCaptureDevice captureDevice = null;
// check authorization status
if (authStatus == AVAuthorizationStatus.Authorized)
{
captureDevice = AVCaptureDevice.GetDefaultDevice(AVMediaType.Video); // update for iOS 13
}
else if (authStatus == AVAuthorizationStatus.NotDetermined)
{
AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (granted) =>
{
if (!granted)
{
Log.Error("ViewDidLoadBase ScanLayer RequestAccessForMediaType not granted!");
}
else
{
Log.Error("ViewDidLoadBase ScanLayer RequestAccessForMediaType granted!");
}
});
}
else
{
Log.Error("Not Authorized! Status: " + authStatus.ToString());
}
if (captureDevice != null)
{
var videoInput = AVCaptureDeviceInput.FromDevice(captureDevice, out error);
if (videoInput != null)
{
_captureSession.AddInput(videoInput);
}
else
{
Log.Error("Video capture error: " + error.LocalizedDescription);
}
var metaDataOutput = new AVCaptureMetadataOutput();
_captureSession.AddOutput(metaDataOutput);
del = new CameraMetaDataDelegate(this, _layer);
metaDataOutput.SetDelegate(del, CoreFoundation.DispatchQueue.MainQueue);
//metaDataOutput.MetadataObjectTypes = metaDataOutput.AvailableMetadataObjectTypes;
metaDataOutput.MetadataObjectTypes = AVMetadataObjectType.QRCode | AVMetadataObjectType.Code128Code | AVMetadataObjectType.UPCECode | AVMetadataObjectType.EAN13Code ;
_videoPreviewLayer = new AVCaptureVideoPreviewLayer(_captureSession) {
Frame = View.Bounds,
Orientation = (AVCaptureVideoOrientation)InterfaceOrientation,
};
View.Layer.AddSublayer(_videoPreviewLayer);

Setting device permission from driver code fails

I want to access I2C device driver nodes from user space in a linux kernel 3.10.14.
I added i2c-dev in the kernel configuration and got the /dev/i2c-* device nodes. However they have permission
$ ls -l /dev/i2c-*
crw------- root root 89, 1 2014-08-21 20:00 i2c-1
In drivers/i2c/i2c-dev.c I added the callback
static char *i2c_dev_devnode(struct device *dev, umode_t *mode)
{
if (!mode)
return NULL;
if (MAJOR(dev->devt) == I2C_MAJOR)
*mode = 0666;
return NULL;
}
and in the same file I added the callback to the device class struct:
static int __init i2c_dev_init(void)
{
...
i2c_dev_class = class_create(THIS_MODULE, "i2c-dev");
...
/* set access rights */
i2c_dev_class->devnode = i2c_dev_devnode;
...
}
However the access rights of the device node remain
crw------- root root 89, 1 2014-08-21 20:00 i2c-1
There is no /lib/udev/rules.d or /etc/udev/rules.d
I would appreciate any suggestions what might go wrong here.
I am also interested in ideas how to test this issue.
You might try the following. This works at least with kernel 4.9.56.
static int my_uevent(struct device *dev, struct kobj_uevent_env *env)
{
add_uevent_var(env, "DEVMODE=%#o", 0666);
return 0;
}
static int __init i2c_dev_init(void)
{
...
i2c_dev_class = class_create(THIS_MODULE, "i2c-dev");
...
/* set access rights */
i2c_dev_class->dev_uevent = my_uevent;
...
}
I understand the return value of devnode callback function shall not be "NULL" but device node name.
So,
Change your functions return value from "NULL" to devname. Refer the code:
----------------------patch--------------------
diff --git a/drivers/i2c/i2c-dev.c b/drivers/i2c/i2c-dev.c
index 6f638bb..35a42c6 100644
--- a/drivers/i2c/i2c-dev.c
+++ b/drivers/i2c/i2c-dev.c
## -614,6 +614,14 ## static int i2cdev_notifier_call(struct notifier_block *nb, unsigned long action,
.notifier_call = i2cdev_notifier_call,
};
+static char *i2c_dev_devnode(struct device *dev, umode_t *mode)
+{
+ printk("\n\n****%s: %d\n\n",__func__,__LINE__);
+ if (mode != NULL)
+ *mode = 0666;
+ return kasprintf(GFP_KERNEL, "i2cr/%s", dev_name(dev));;
+}
+
/* ------------------------------------------------------------------------- */
/*
## -636,7 +644,12 ## static int __init i2c_dev_init(void)
goto out_unreg_chrdev;
}
i2c_dev_class->dev_groups = i2c_groups;
+ /* set access rights */
+ printk(KERN_INFO "i2c setting devnode\n");
+ i2c_dev_class->devnode = i2c_dev_devnode;
+
+
/* Keep track of adapters which will be added or removed later */
res = bus_register_notifier(&i2c_bus_type, &i2cdev_notifier);
if (res)
Results:
Without applying this patch:
root#x86-generic-64:~# ls -l /dev/i2c-*
crw------- 1 root root 89, 0 Nov 1 13:47 /dev/i2c-0
crw------- 1 root root 89, 1 Nov 1 13:47 /dev/i2c-1
With patch:
root#x86-generic-64:~# ls -l /dev/i2cr/*
crw-rw-rw- 1 root root 89, 0 Nov 1 13:38 /dev/i2cr/i2c-0
crw-rw-rw- 1 root root 89, 1 Nov 1 13:38 /dev/i2cr/i2c-1
Setting up device node is responsibility of udev. So we need to use correct udev rule. Further init.rc approach will fail if driver is loaded after boot time for example in case it is a loadable module. Your distribution might be using another way of supporting hotplug so we need to consult documentation about that distro.

Can mobilesubstrate hook this?

I want to hook a function called png_handle_IHDR declared locally in the ImageIO framework. I used MobileSafari as the filter. But while calling the original function, mobilesafari crashes. Upon inspection of the NSLog, i get this:
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: dlopen ImageIO success!
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: Zeroing of nlist success!
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: method name successfully assigned!
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: nlist SUCCESS! nlsetting..
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: nlset success! Hooking..
Jun 5 17:21:09 unknown MobileSafari[553] <Warning>: Png IHDR handle hooking!
Jun 5 17:21:09 unknown UIKitApplication:com.apple.mobilesafari[0x819][553] <Notice>: libpng error: Invalid IHDR chunk
Jun 5 17:21:09 unknown ReportCrash[554] <Notice>: Formulating crash report for process MobileSafari[553]
Jun 5 17:21:09 unknown com.apple.launchd[1] <Warning>: (UIKitApplication:com.apple.mobilesafari[0x819]) Job appears to have crashed: Abort trap: 6
Jun 5 17:21:09 unknown SpringBoard[530] <Warning>: Application 'Safari' exited abnormally with signal 6: Abort trap: 6
I immediately gathered that its very likely that I got the function prototype of the png_handle_IHDR wrong. The following is my code in the tweak:
#import <CoreFoundation/CoreFoundation.h>
#include <substrate.h>
#define ImageIO "/System/Library/Frameworks/ImageIO.framework/ImageIO"
void (*png_handle_IHDR)();
MSHook(void, png_handle_IHDR){
NSLog(#"Png IHDR handle hooking!\n");
_png_handle_IHDR(); //crashed here!!
NSLog(#"Png IHDR handle hooking finished!\n");
}
template <typename Type_>
static void nlset(Type_ &function, struct nlist *nl, size_t index) {
struct nlist &name(nl[index]);
uintptr_t value(name.n_value);
if ((name.n_desc & N_ARM_THUMB_DEF) != 0)
value |= 0x00000001;
function = reinterpret_cast<Type_>(value);
}
MSInitialize {
if (dlopen(ImageIO, RTLD_LAZY | RTLD_NOLOAD)!=NULL)
{
NSLog(#"dlopen ImageIO success!\n");
struct nlist nl[2];
bzero(&nl, sizeof(nl));
NSLog(#"Zeroing of nlist success!\n");
nl[0].n_un.n_name = (char*) "_png_handle_IHDR";
NSLog(#"method name successfully assigned!\n");
nlist(ImageIO,nl);
NSLog(#"nlist SUCCESS! nlsetting..\n");
nlset(png_handle_IHDR, nl, 0);
NSLog(#"nlset success! Hooking..\n");
MSHookFunction(png_handle_IHDR,MSHake(png_handle_IHDR));
}
}
My makefile is as such:
include theos/makefiles/common.mk
TWEAK_NAME = privateFunctionTest
privateFunctionTest_FILES = Tweak.xm
include $(THEOS_MAKE_PATH)/tweak.mk
privateFunctionTest_FRAMEWORKS = UIKit ImageIO CoreGraphics Foundation CoreFoundation
Edit: The question is, is knowing the original function arguments necessary for a successful hook? If yes, is getting the function prototype from the disassembly the only way? There is no definition of this in any of the SDK headers. Thanks.
Ok, I decompiled the function and get the function prototype guessed by the decompiler. As long as the parameters and return type broadly matched e.g. bool : int, unsigned int : int, it still works without killing the execution. So this works:
int *png_handle_IHDR(int a1, int a2, int a3);
MSHook(int, png_handle_IHDR, int a1, int a2, int a3){
NSLog(#"png_handle_IHDR(%d,%d,%d)", a1,a2,a3);
int val = _png_handle_IHDR(a1,a2,a3);
NSLog(#"Png IHDR handle hooking finished, returning %d as result!", val);
return val;
}

mmap brokes after strdup

I tried the following configuration with mmap:
open file (file is over 2 kB)
request statistics from file *f_file*
map file (file is smaller than a page, offset page 0, size is expected size)
verify values of *f_footer* in the map *f_fpage*
usage strdup
Code:
union{
...
struct {
char *f_fname;
struct clog_footer *f_footer;
char *f_fpage;
size_t f_size;
} f_ring; /* circular log file */
char *f_fname; /* Name use for Files|Pipes|TTYs. */
} f_un;
...
struct clog_footer {
uint32_t cf_magic;
};
...
1995 f->f_file = open(p+1, O_RDWR, 0 );
1996 if (f->f_file == -1) {
2000 }
2001 if (fstat(f->f_file,&sb)<0) {
2006 }
2014 f->f_un.f_ring.f_fpage = mmap(NULL,sb.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,f->f_file,0);
2015 if (f->f_un.f_ring.f_fpage == MAP_FAILED) {
2020 }
2021 f->f_un.f_ring.f_footer = (struct clog_footer*)(f->f_un.f_ring.f_fpage + sb.st_size-sizeof(struct clog_footer));
2022 if (memcmp(&(f->f_un.f_ring.f_footer->cf_magic),MAGIC_CONST,4)!=0) {
2029 }
2031 f->f_un.f_fname = strdup (p+1);
...
I used read/write, file is filled with zero's up to 2 Kb. I parametrized mmap with file size and zero page size, but mmap fails to map the file.
Should the file to map have additional properties?
Is "0" a acceptable parameter as offset in mmap, once i want to map the file from beginning?