Casting struct ProcessSerialNumber to UnsafePointer<Void> - macos

I have a ProcessSerialNumber and want to create a NSAppleEventDescriptor from it, the same way as shown in issue 14 of objc.io. However the constructor expects an UnsafePointer<Void>.
let psn = ProcessSerialNumber(highLongOfPSN: UInt32(0), lowLongOfPSN: UInt32(kCurrentProcess))
let target = NSAppleEventDescriptor(
descriptorType: typeProcessSerialNumber,
bytes: &psn, // <-- this fails
length: sizeof(ProcessSerialNumber)
)
What am I missing to convert it correctly?

Yet another glorious swift error message failure, the real problem is that typeProcessSerialNumber is an Int and the initializer expects a DescType. Use:
let target = NSAppleEventDescriptor(descriptorType: DescType(typeProcessSerialNumber), bytes:&psn, length:sizeof(ProcessSerialNumber))

Related

bpf_prog_test_run() causes unexpected packet data

I try to perform a test run for an XDP BPF program. The BPF program uses the bpf_xdp_adjust_meta() helper, to adjust the meta data.
I tried:
to run bpf_prog_test_run()
to run bpf_prog_test_run_xattr()
1. bpf_prog_test_run()
(The first time I tried my bpf program's debug messages told me that adjusting the data_meta field failed.) Now it can adjust the data_meta, but the iph.ihl field is apparently not set to 5.
2. bpf_prog_test_xattr()
This always returns -1, so something failed.
The Code
packet:
struct ipv4_packet pkt_v4 = {
.eth.h_proto = __bpf_constant_htons(ETH_P_IP),
.iph.ihl = 5,
.iph.daddr = __bpf_constant_htonl(33554442),
.iph.saddr = __bpf_constant_htonl(50331658),
.iph.protocol = IPPROTO_TCP,
.iph.tot_len = __bpf_constant_htons(MAGIC_BYTES),
.tcp.urg_ptr = 123,
.tcp.doff = 5,
};
test attribute:
__u32 size, retval, duration;
char data_out[128];
struct xdp_md ctx_in, ctx_out;
struct bpf_prog_test_run_attr test_attr = {
.prog_fd = prog_fd,
.repeat = 100,
.data_in = &pkt_v4,
.data_size_in = sizeof(&pkt_v4),
.data_out = &data_out,
.data_size_out = sizeof(data_out),
.ctx_in = &ctx_in,
.ctx_size_in = sizeof(ctx_in),
.ctx_out = &ctx_out,
.ctx_size_out = sizeof(ctx_out),
.retval = &retval,
.duration = &duration,
};
test execution:
bpf_prog_test_run(main_prog_fd, 1, &pkt_v4, sizeof(pkt_v4), &data_out, &size, &retval, &duration) -> iph.ihl field is 0.
bpf_prog_test_run_xattr(&test_attr) -> returns -1.
Note
The program was already successfully attached to the hook point of a real network interface and ran as intended. I just replaced the code that attaches the program to the hook point with the above code for testing.
The struct ipv4_packet pkt_v4 was not packed.
When I replace __packed with __attribute__ ((__packed__)) it works.
For information what happens without packing, see for example this question.
Basically the compiler adds padding bytes which leads to the fields in the packet being in different places than expected.

How to create object from repeated type protobuf

What I am looking for is a function that returns the message of a repeated field
I know there is Reflection::AddMessage which has the return type that I want but I do not want to add a message, just return an object of that message.
Here is an example of what I am trying to do let's say I have in the .proto file a message:
message Bar{
uint32 t x = 1;
uint64 t y = 2;
}
message Foo{
repeated Bar myMessage = 1;
}
I am using reflection to iterate through the Foo message and I want to be able to do something like this:
Message* Msg = createMessage(refl->FooMsg, FieldDesc)
I know there is also GetRepeatedMessage but that requires index.
First of all when the protobuf compiler generates the code for compiling you get an accessor function in the interface. The are functions mutable_nameOf_message() which returns the entire repeated field which is a std::vector in c++, or mutable_nameOf_message( index ) which gives you the specified element.
Now if you do not want to use Bar then you d'not need too.
message ArrayOfBar
{
repeated Bar arrayOfBar = 0;
message Bar{
uint32 t x = 1;
uint64 t y = 2;
}
}
If thats what you have hade in mind you could also be do something like this.
std::vector<Bar> arrayOfBars;
But that idea needs refinement because of the internal specifics of the Protobuf. Some unwanted behavior might occur with something like that.

AbsoluteTime type not imported into Swift

The Swift compiler seems very confused when trying to use the AbsoluteTime type for IOKit HID code.
This block compiles and runs fine, printing "UnsignedWide".
import IOKit.hid
var event = IOHIDEventStruct()
let timestamp = event.timestamp
let lo: UInt32 = timestamp.lo
let hi: UInt32 = timestamp.hi
let newTime = event.timestamp.dynamicType.init(lo: lo, hi: hi)
event.timestamp = newTime
print(timestamp.dynamicType)
This, however, does not compile.
let time1: AbsoluteTime = event.timestamp
"error: use of undeclared type 'AbsoluteTime'"
This also does not compile.
let wide1: UnsignedWide = event.timestamp
"error: use of undeclared type 'UnsignedWide'"
This fails to compile as well, but that's expected.
let uint: UInt64 = event.timestamp
"error: cannot convert value of type 'AbsoluteTime' (aka 'UnsignedWide') to specified type 'UInt64'"
So since Swift clearly knows that UnsignedWide is a struct with two UInt32 fields, I figured I'd try just defining my own struct with those qualities, but this fails as well.
struct UnsignedWide {
let lo: UInt32
let hi: UInt32
}
typealias AbsoluteTime = UnsignedWide
let time2: AbsoluteTime = event.timestamp
let wide2: UnsignedWide = event.timestamp
"error: cannot convert value of type 'AbsoluteTime' (aka 'UnsignedWide') to specified type 'AbsoluteTime' (aka 'UnsignedWide')"
"error: cannot convert value of type 'AbsoluteTime' (aka 'UnsignedWide') to specified type 'UnsignedWide'"
This works, at least.
let time3: AbsoluteTime = unsafeBitCast(event.timestamp, AbsoluteTime.self)
I'd rather not do that though, and I can only create AbsoluteTime variables with this ugliness.
let AbsoluteTime = event.timestamp.dynamicType
let time4 = AbsoluteTime.init(lo: lo, hi: hi)
Unfortunately, that doesn't let me use AbsoluteTime as a type in functions or struct or anything like that, so that doesn't really solve my problem.
This is the case with Xcode 7.3 and the Xcode 7.3.1 GM.
Anyone know of a solution?
Use Darwin.UnsignedWide which is aliased by AbsoluteTime
E.g.:
This compiles:
import Darwin
public protocol CurrentAbsoluteTimeProvider: class {
func currentAbsoluteTime() -> Darwin.AbsoluteTime
}
This fails to compile:
import Darwin
public protocol CurrentAbsoluteTimeProvider: class {
func currentAbsoluteTime() -> AbsoluteTime
}
I've added this file to my library that uses IOKit: https://github.com/avito-tech/Mixbox/blob/e3a5991f61dd2a36e13193e67ca69743f5bb62c7/Frameworks/Foundation/CurrentAbsoluteTimeProvider/AbsoluteTime/AbsoluteTime.swift
By the way, our company is developing a Swift library for working with IOKit. Permalink: https://github.com/avito-tech/Mixbox/tree/e3a5991f61dd2a36e13193e67ca69743f5bb62c7/Frameworks/IoKit

unable to use optional int "possibleNumber" in optional binding

I'm new to Swift and is trying to learn the concept of optional binding. I have came up with the following code:
let possibleNumber = Int("123")
possibleNumber.dynamicType
if let actualNumber = Int(possibleNumber){
print("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
print("\(possibleNumber) could not be converted to an int")
}
Xcode playground output error message:
value of optional type "int?" not unwrapped, did you mean to use "!" or "?"
However, when I added the "!" to if let actualNumber = Int(possibleNumber!){
let possibleNumber = Int("123")
possibleNumber.dynamicType
if let actualNumber = Int(possibleNumber!){
print("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
print("\(possibleNumber) could not be converted to an int")
}
Xcode display another error message:
initialiser for conditional binding must have Optional type, not int
Why is this happening?
The result of
let possibleNumber = Int("123")
is an optional Int - Int?
Then you're trying to create another Int with
Int(possibleNumber)
which does not work because the initializer expects a non-optional type.
The error message is related to the initializer rather than to the optional binding.
Try this to get the same error message.
let possibleNumber = Int("123")
let x = Int(possibleNumber)
In your second example when you initialize an Int with an implicit unwrapped Int! argument you get a non-optional Int and the compiler complains about the missing optional.
In the if let construct
if let actualNumber = Int(possibleNumber!){
print("\(possibleNumber) has an integer value of \(actualNumber)")
}
you don't need to use the Int initializer. You simply need to write
if let actualNumber = possibleNumber {
print("\(possibleNumber) has an integer value of \(actualNumber)")
}
Now Swift will try to unwrap possibleNumber. If the operation does succeed the unwrapped value is put inside actualNumber and the THEN block executed.

Convert String "10.20" to Double and then to Int at once in Swift 2.0

I'm trying to convert the String "10.20" to Int without converting it to Double before.
I want to get the value: 10
At the moment what is working is:
let valueString = "10.20"
let valueInt = Int(Double(valueString)!)
print(valueInt)
But, is there any better way to do it?
I was trying first to do it with this command but was returning nil:
let valueString = "10.20"
let valueInt = Int(valueString)
print(valueInt)
Thanks!
You could just put an extension on the Int type that makes it StringLiteralConvertable, producing the expected result via a Float cast behind the scenes.

Resources