(Linux Style) Ioctl code, Hard to understand - device-driver

I'm using infini** chip.
In their Basic Code, every [XXX_ioctl].c code It has below code at upper parts.
(XXX means the driver I want to use. )
typedef void (*PFUNCTION)(void);
#define FUNCTION_COUNT 5
struct IoctlInterface {
uint8_t count;
PFUNCTION functionArray[FUNCTION_COUNT]; //function pointer array
} __STATIC const XxxInterface = {
FUNCTION_COUNT,
{
(PFUNCTION) IFX_XXX_Open,
(PFUNCTION) IFX_XXX_Close,
(PFUNCTION) IFX_XXX_Ioctl,
(PFUNCTION) IFX_XXX_CancleIO,
(PFUNCTION) IFX_XXX_DriverInit,
}
};
I know that struct IoctlInterface has member array[5], which return type is function pointer.
But, what is the following means?
__STATIC const XxxInterface = {
FUNCTION_COUNT,
{
(PFUNCTION) IFX_XXX_Open,
(PFUNCTION) IFX_XXX_Close,
(PFUNCTION) IFX_XXX_Ioctl,
(PFUNCTION) IFX_XXX_CancleIO,
(PFUNCTION) IFX_XXX_DriverInit,
}
};
Thanks ahead.
※ If this post violates the technical secrets of the chip, I will delete it immediately.

I think you probably need to read up a little bit more about C. However, in this part you are simply declaring a (probably) global (probably) static variable called XxxInterface of type IoctlInterface and filling in the members of the struct.
__STATIC const XxxInterface = {
FUNCTION_COUNT,
{
(PFUNCTION) IFX_XXX_Open,
(PFUNCTION) IFX_XXX_Close,
(PFUNCTION) IFX_XXX_Ioctl,
(PFUNCTION) IFX_XXX_CancleIO,
(PFUNCTION) IFX_XXX_DriverInit,
}
};

Related

USDC smart contract on polygon revoked all my approve request

Simple. I'm trying to interact with USDC in my Dapp.
async function approveUSDC() {
try {
const USDCContractAdress = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";
const USDCContractAbi = [
"function approve(address spender, uint256 amount) public",
];
const address = "0x644F303448a1d14Fa24Bf18200Dd41790f6B9920"; //BGGExchange Contract
const amount = 50000000000000000000n ;
const USDCContract = new ethers.Contract(USDCContractAdress, USDCContractAbi, provider);
const result = await USDCContract.connect(signer).approve(address, amount);
console.log(result);
} catch (error) {
console.log(error);
}
}
Everytime I call the approve function on the USDC smart contract of polygon, the transaction return as revoked. I'm baffled please help.

Testing sharp with memfs error: [Error: Input file is missing]

I had trouble testing my code that implement sharp and memfs. I has codes that download image and cropping it to certain dimension. I use sharp to achieve the cropping. When it comes testing, I use jest and memfs. My test code has 2 parts:
Download a image and save to mock volume/fileSystem that created with memfs.
Cropping the downloaded image to certain dimension with sharp.
Part 1 worked perfectly, was able to download image to the fake volume and asserted with jest (exist in the fake volume).
But part 2 gave me error:[Error: Input file is missing].
const sizeToCrop = {
width: 378,
height: 538,
left: 422,
top: 0,
};
sharp(`./downloadedImage.jpg`)
.extract(sizeToCrop)
.toFile(`./CroppedImage.jpg`)
.then(() => {
console.log(`resolve!`);
})
.catch((err: Error) => {
console.log(err);
return Promise.reject();
});
// Error message: [Error: Input file is missing]
But when I test it with real volume. It worked fine.
Anyone has idea how to solve this?
Thank you.
After some inspirations from here, here and here.
It is because sharp is not accessing memfs' faked file system, it is accessing the actual fs' file system, which ./donwloadedImage.jpg to not exist. Hence, in order to make sharp use memfs, it has to be mocked. And extract and toFile functions need to be mocked as well(for chaining function call):
// Inside code.test.ts
jest.mock('sharp', () => {
const sharp = jest.requireActual('sharp');
const { vol } = require('memfs');
let inputFilePath: string;
let sizeToCrop: any;
let outputFilePath: string;
const toFile = async (writePath: string): Promise<any> => {
outputFilePath = writePath;
try {
return await starCropping();
} catch (error) {
console.log(`Error in mocked toFile()`, error);
}
};
const extract = (dimensionSize: string): any => {
sizeToCrop = dimensionSize;
return { toFile };
};
const mockSharp = (readPath: string): any => {
inputFilePath = readPath;
return { extract };
};
async function starCropping(): Promise<void> {
try {
const inputFile = vol.readFileSync(inputFilePath);
const imageBuffer = await sharp(inputFile).extract(sizeToCrop).toBuffer();
vol.writeFileSync(outputFilePath, imageBuffer);
} catch (error) {
console.log(`Error in mocked sharp module`, error);
return Promise.reject();
}
}
return mockSharp;
});

How to invoke Method in native IOS to send data to Flutter?

I need to send some data from the native IOS side to the dart side. I am using Channel Method to invoke the method from IOS side but I am getting noting:
Flutter Side:
static const platform = const MethodChannel('samples.flutter.dev/battery');
platform.setMethodCallHandler(myUtilsHandler); // I am calling it in initState
Future<dynamic> myUtilsHandler(MethodCall methodCall) async {
print("myUtilsHandler");
switch (methodCall.method) {
case "someMethod":
print(json.decode(methodCall.arguments));
break;
case 'someMethod2':
print("someMethod2");
break;
default:
print("default");
}
}
Native IOS side:
let controller: FlutterViewController = window?.rootViewController as! FlutterViewController
let batteryChannel = FlutterMethodChannel(name: "samples.flutter.dev/battery",binaryMessenger: controller.binaryMessenger)
batteryChannel.invokeMethod("someMethod", arguments: "someValue")
Note: the other way around is working fine!
I have tested.
In general , use FlutterMethodChannel instance call invokeMethod.
Now I show some test codes based batteryChannel demo.
In AppDelegate add one property
//didFinishLaunchingWithOptions methods
var batteryChannel : FlutterMethodChannel!
batteryChannel = FlutterMethodChannel.init(name: "samples.flutter.dev/battery", binaryMessenger: controller.binaryMessenger)
private func receiveBatteryLevel(result: FlutterResult) {
let device = UIDevice.current;
device.isBatteryMonitoringEnabled = true;
//test send message
sendMessageToFlutter()
if (device.batteryState == UIDevice.BatteryState.unknown) {
result(FlutterError.init(code: "UNAVAILABLE",
message: "Battery info unavailable",
details: nil));
} else {
result(Int(device.batteryLevel * 100));
}
}
private func sendMessageToFlutter(){
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
self.batteryChannel.invokeMethod("nativeCallSomeFlutterMethod", arguments: nil)
}
}
Now in flutter side , also based batteryChannel demo
class _MyHomePageState extends State<MyHomePage> {
static const platform = const MethodChannel('samples.flutter.dev/battery');
void initState(){
super.initState();
platform.setMethodCallHandler((call) {
print("init state setMethodCallHandler ${call.method}");
});
}
}
after you click Get Battery Level button, 2seconds later ,you can see
init state setMethodCallHandler nativeCallSomeFlutterMethod
Since Dart 2.18, you can also call Objective-C and Swift code directly using Dart's Foreign Function Interface (FFI).
More info: https://medium.com/dartlang/dart-2-18-f4b3101f146c

How can I check if std::io::Cursor has unconsumed data?

I am writing a low-level network app that deals with TCP sockets where I often need to process binary data streams. When some data is available, I read it into u8 array, then wrap into std::io::Cursor<&[u8]> and then pass it to handlers. In a handler, I often need to know if there is some more data in the Cursor or not.
Imagine that the handle function receives data and then processes it in chunks using the handle_chunk function. For simplicity, assume that chunk size is fixed at 10 bytes; if the data size is not divisible by 10, it's an error. This simple logic can be implemented in the following way:
fn handle(mut data: Cursor<&[u8]>) {
while !data.empty() {
if let Err(err) = handle_chunk(&mut data) {
eprintln!("Error while handling data: {}", err);
}
}
}
fn handle_chunk(data: &mut Cursor<&[u8]>) -> Result<(), String> {
// Returns Err("unexpected EOF".to_string()) if chunk is incomplete
// ...
}
However, Cursor does not have an empty() method or any other method capable of telling if there is more data to process. The working solution that I could come up with is:
fn handle(data: Cursor<&[u8]>) {
let data = data.into_inner();
let len = data.len();
let mut data = Cursor::new(data);
while (data.position() as usize) < len - 1 {
if let Err(err) = handle_chunk(&mut data) {
eprintln!("Error while handling data: {}", err);
}
}
}
This looks hacky and inelegant though. Is there a better solution? Maybe there is a different tool in the Rust standard library that fits here better than Cursor?
Your code can be simplified by using Cursor::get_ref to avoid breaking up the input and putting it back together:
fn handle(mut data: Cursor<&[u8]>) {
let len = data.get_ref().len();
while (data.position() as usize) < len - 1 {
if let Err(err) = handle_chunk(&mut data) {
eprintln!("Error while handling data: {}", err);
}
}
}
Now, you haven't shown any code that requires a Cursor. Many times, people think it's needed to convert a &[u8] to something that implements Read, but it's not. Read is implemented for &'a [u8]:
use std::io::Read;
fn handle(mut data: &[u8]) {
while !data.is_empty() {
if let Err(err) = handle_chunk(&mut data) {
eprintln!("Error while handling data: {}", err);
}
}
}
fn handle_chunk<R: Read>(mut data: R) -> Result<(), String> {
let mut b = [0; 10];
data.read_exact(&mut b).unwrap();
println!("Chunk: {:?}", b);
Ok(())
}
fn main() {
let d: Vec<u8> = (0..20).collect();
handle(&d)
}
By having mut data: &[u8] and using &mut data, the code will update the slice variable in place to advance it forward. We can't easily go backward though.
an empty() method
Rust style indicates that an empty method would be a verb — this would remove data (if it were possible). The method you want should be called is_empty, as seen on slices.

How do I load and return a .png file in a function call in ActionScript 3?

ActionScript does not seem to support loading a png synchronously. I have tried loading it asynchronously, but then there is the problem of making your function wait for the load to finish. I cannot accomplish this. I have tried calling both setInterval and setTimout in a while loop, and breaking when the load is complete, but I get some very mysterious behavior. For the function parameter, I pass a function called doNothing that is just an empty function. When I run, setInterval or setTimeout gets over and over, very quickly. They do not wait the time provided before calling again. Also, doNothing never gets called.
Here's my code:
private function getData(extension:String):Bitmap
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onComplete);
loader.contentLoaderInfo.addEventListener(ErrorEvent.ERROR, onComplete);
loader.load(new URLRequest(baseDir + extension));
while (bitmap == null)
{
var test:Number = setInterval(doNothing, 1000);
}
var ret:Bitmap = bitmap;
bitmap = null;
return ret;
}
function onComplete(event:Event):void
{
bitmap = Bitmap(LoaderInfo(event.target).content);
}
function doNothing():void
{
trace("did nothing");
}
while loop is not good here since it will cause your client to freeze (and 15 seconds of freezing will throw an error)
Suggested Implementation:
private var loader:Loader;
private var onSuccess:Function;
// onSuccess = function (bitmap:Bitmap) : void
// onFail = function (e:ErrorEvent) : void
private function getData(extension:String, onSuccess:Function, onFail:Function):void
{
this.onSucess = onSuccess;
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onFail);
loader.contentLoaderInfo.addEventListener(ErrorEvent.ERROR, onFail);
loader.load(new URLRequest(baseDir + extension));
}
private function onComplete(event:Event):void
{
bitmap = Bitmap(LoaderInfo(event.target).content);
onSuccess.call(null, bitmap);
dispose();
}
private function dispose():void
{
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onFail);
loader.contentLoaderInfo.removeEventListener(ErrorEvent.ERROR, onFail);
this.loader = null;
this.onSuccess = null;
}

Resources