Enum initializer as const - vala

Are vala enums not integer based? This example generates a "c" compile error. Not a big deal, but would like to understand why.
const int INT_UNINITIALIZED = 999;
public enum ScopeTypes {
/*OSS:Fix:GLib requires a default value, set GLOBALS = 0
(VSCodeDbgSvr.exe:31979): GLib-GObject-CRITICAL **: g_param_spec_enum: assertion 'g_enum_get_value (enum_class, default_value) != NULL' failed*/
NONE = INT_UNINITIALIZED,
GLOBALS = 0,
ARGUMENTS,
LOCALS,
EXCEPTIONS,
TOT_SCOPE_TYPES;
//Vala enums may have methods:
public bool is_global() {
return (this == GLOBALS || this == EXCEPTIONS);
}
public bool is_function() {
return (this == ARGUMENTS || this == LOCALS);
}
public bool is_valid() {
return (this != NONE);
}
}
The compile output:
> Executing task: /opt/vala/bin/valac helloworld.vala class1.vala --pkg libvala-0.40 -X -I/opt/vala/include/vala-0.40 -X -O0 --vapidir=/opt/vala/share/vala/vapi --debug --save-temps -o helloworld.exe <
/media/george/SharedData/Projects/Vala/Examples/playground-2/helloworld.c:82:21: error: ‘INT_UNINITIALIZED’ undeclared here (not in a function)
SCOPE_TYPES_NONE = INT_UNINITIALIZED,
^~~~~~~~~~~~~~~~~
error: cc exited with status 256
Compilation failed: 1 error(s), 1 warning(s)
The terminal process terminated with exit code: 1

The relevant part of the error message is:
error: ‘INT_UNINITIALIZED’ undeclared here (not in a function)
The C compiler is complaining that it can not find the declaration of your constant. So it is not a type problem at all.
It is a scope / ordering problem.
If you compile the code with valac -C you get a .c file that looks something like this:
typedef enum {
SCOPE_TYPES_NONE = INT_UNINITIALIZED,
SCOPE_TYPES_GLOBALS = 0,
SCOPE_TYPES_ARGUMENTS,
SCOPE_TYPES_LOCALS,
SCOPE_TYPES_EXCEPTIONS,
SCOPE_TYPES_TOT_SCOPE_TYPES
} ScopeTypes;
#define INT_UNINITIALIZED 999
Note how the Vala compiler has reordered the code to declare the enum first and the constant later.
Since in C the order of declarations in a file is important this can not compile.
I would consider this to be a compiler bug and you may want to report this to the GNOME bugtracker (product Vala).

Related

How to pass to Frida a .ts file which depends on another .ts

I have following .ts files
core.ts
interface Signature {
args: string[];
ret?: string;
}
const subject = 'hook'
const now = () => (new Date()).getTime()
const readable = (type: string, arg: NativePointer) => (type === 'char *' ? arg.readUtf8String() : arg)
export function hook(mod: string | null, symbol: string, signature: Signature) {
const p = Module.findExportByName(mod, symbol)
if (!p) throw new Error(`Function ${mod || 'global'}!${symbol} not found`)
const range = Process.findRangeByAddress(p)
if (!range?.protection.includes('x')) throw new Error('Invalid symbol, expected a function but received a data pointer')
const id = p.toString()
const lib = mod || Process.getModuleByAddress(p)!.name
const listener = Interceptor.attach(p, {
onEnter(args) {
const time = now()
const pretty = signature.args.map((type, i) => readable(type, args[i]))
const backtrace = Thread.backtrace(this.context, Backtracer.ACCURATE)
.map(DebugSymbol.fromAddress).filter(e => e.name)
this.backtrace = backtrace
send({
subject,
event: 'call',
args: pretty,
lib,
symbol,
backtrace,
time
})
},
onLeave(retVal) {
if (!signature.ret) return
const time = now()
const ret = readable(signature.ret, retVal)
send({
subject,
event: 'return',
lib,
symbol,
time,
backtrace: this.backtrace,
ret
})
}
})
return listener
}
sql-hooks.ts
// import { hook } from './core'
const { hook } = require('./core.ts')
ObjC.schedule(ObjC.mainQueue, function () {
enable()
});
function enable() {
console.log('enabled')
hook('libsqlite3.dylib', 'sqlite3_open', { args: ['char *', 'int'], ret: 'int' })
hook('libsqlite3.dylib', 'sqlite3_prepare_v2', { args: ['pointer', 'char *', 'int', 'pointer', 'pointer'] })
hook('libsqlite3.dylib', 'sqlite3_bind_int', { args: ['pointer', 'int', 'int'] })
hook('libsqlite3.dylib', 'sqlite3_bind_null', { args: ['pointer', 'int'] })
hook('libsqlite3.dylib', 'sqlite3_bind_text', { args: ['pointer', 'int', 'char *', 'int', 'pointer'] })
}
Then I used following command to connect these two files
frida-compile '/path/to/sql-hooks.ts' -o out.ts
Finally I used following command to actually use out.ts
frida -U -F -l '/path/to/out.ts'
But unfortunately I get this error
out.ts:1:1 - error TS1127: Invalid character.
out.ts:2:6 - error TS2304: Cannot find name 'sql'.
out.ts:2:10 - error TS2552: Cannot find name 'hooks'. Did you mean 'hook'?
out.ts:3:6 - error TS2304: Cannot find name 'sql'.
out.ts:3:10 - error TS2552: Cannot find name 'hooks'. Did you mean 'hook'?
out.ts:4:1 - error TS1127: Invalid character.
out.ts:5:11 - error TS1005: ';' expected.
out.ts:5:12 - error TS2695: Left side of comma operator is unused and has no side effects.
out.ts:5:20 - error TS1005: ';' expected.
out.ts:5:21 - error TS2695: Left side of comma operator is unused and has no side effects.
out.ts:5:48 - error TS1005: ';' expected.
out.ts:5:49 - error TS2695: Left side of comma operator is unused and has no side effects.
out.ts:5:105 - error TS1005: ';' expected.
out.ts:5:106 - error TS2695: Left side of comma operator is unused and has no side effects.
out.ts:5:130 - error TS1005: ';' expected.
out.ts:5:131 - error TS2695: Left side of comma operator is unused and has no side effects.
out.ts:5:144 - error TS1005: ';' expected.
out.ts:6:1 - error TS1127: Invalid character.
What am I doing wrong?
I bumped into a frida-compile example (from oleavr) and I found out I was doing a couple of things wrong. In particular I took a look at the agent folder and at the package.json scripts region.
I'm going to mention two files: sql-hooks.ts (which is my main.ts) and core.ts (which is my module.ts); both of them are inside the same folder.
I changed first line of sql-hooks.ts from
const { hook } = require('./core.ts')
to
import { hook } from './core.js'
Notice I imported core.ts as a .js
Then I used following command to connect sql-hooks.ts and core.ts
frida-compile '/path/to/sql-hooks.ts' -o out.js
Notice output extension is .js
And that's it, everything's gonna work fine.

Cannot compile AudioKit 4.2.2

I've just downloaded AudioKit most recent version (4.2.2). When I ran the build_frameworks.sh I get the following error:
[AVAudioUnit?]' has no member 'compactMap'
return _effectsChain.compactMap { $0 }
^~~~~~~~~~~~~ ~~~~~~~~~~
/Users/sky/Desktop/AudioKit-4.2.2/AudioKit/Common/Nodes/Mixing/Mixer/AKMixer.swift:40:19: error: value of type '[AKNode?]' has no member 'compactMap'
self.init(inputs.compactMap { $0 })
^~~~~~ ~~~~~~~~~~
/Users/sky/Desktop/AudioKit-4.2.2/AudioKit/Common/Internals/AudioKitHelpers.swift:22:16: error: cannot invoke 'index' with an argument list of type '(Self.Index, offsetBy: Int)'
return index(startIndex, offsetBy: offset)
^
/Users/sky/Desktop/AudioKit-4.2.2/AudioKit/Common/Internals/AudioKitHelpers.swift:22:16: note: expected an argument list of type '(Self.Index, offsetBy: Self.IndexDistance)'
return index(startIndex, offsetBy: offset)
^
/Users/sky/Desktop/AudioKit-4.2.2/AudioKit/Common/Internals/CoreAudio/AudioUnit+Helpers.swift:101:29: error: missing argument for parameter 'capacity' in call
data.deallocate()
^
capacity: <#Int#>
Swift.UnsafeMutablePointer:273:17: note: 'deallocate(capacity:)' declared here
public func deallocate(capacity: Int)
^
/Users/sky/Desktop/AudioKit-4.2.2/AudioKit/Common/Nodes/Effects/Reverb/Convolution/AKConvolution.swift:144:41: error: missing argument for parameter 'capacity' in call
theData?.deallocate()
^
capacity: <#Int#>
Swift.UnsafeMutablePointer:273:17: note: 'deallocate(capacity:)' declared here
public func deallocate(capacity: Int)
^
/Users/sky/Desktop/AudioKit-4.2.2/AudioKit/Common/Nodes/Playback/Phase-Locked Vocoder/AKPhaseLockedVocoder.swift:226:41: error: missing argument for parameter 'capacity' in call
theData?.deallocate()
^
capacity: <#Int#>
Swift.UnsafeMutablePointer:273:17: note: 'deallocate(capacity:)' declared here
public func deallocate(capacity: Int)
^
/Users/sky/Desktop/AudioKit-4.2.2/AudioKit/Common/Nodes/Effects/AudioKit Operation-Based Effect/AKOperationEffect.swift:28:17: error: value of type '[NSNumber]' has no member 'compactMap'
$0.compactMap { $0.doubleValue }
^~ ~~~~~~~~~~
I tried to copy the AudioKit source code into the project I was testing: AudioKit's HelloWorld project. In this case I have the following error on XCode:
/Users/sky/Desktop/AudioKit-4.2.2/AudioKit/Common/Internals/AudioUnit Host/AKAudioUnitManager.swift:140:16: Value of type '[AVAudioUnit?]' has no member 'compactMap'
The error is thrown on source code file AKAudioUnitManager.swift on the method below:
private var linkedEffects: [AVAudioUnit] {
return _effectsChain.compactMap { $0 }
}
Also, playground is not working even with compiled framework.
I use MacOS Sierra, XCode 9.2, Swift 4, iOS 9.2.
Thanks!

Swift 3 CVaListPointer Type Conflict

I am integrating with a C library - liblinphone. It has the following typedef and function I need to call from my Swift 3 iOS app.
typedef void (*OrtpLogFunc)(const char *domain,
int lev,
const char *fmt,
va_list args);
void linphone_core_set_log_handler(OrtpLogFunc logfunc);
It appears that Swift is interpreting va_list differently when compiling for the simulator than when compiling for a device.
Here is the Swift code that uses the C function and
This compiles only when the target is the Device:
class MyClass {
func setupLogging() {
linphone_core_set_log_handler(my_callback)
}
}
func my_callback(_ domain: Optional<UnsafePointer<Int8>>,
level: OrtpLogLevel,
format: Optional<UnsafePointer<Int8>>,
args: CVaListPointer?) { // NOTE: Optional CVAListPointer
// do some logging
}
This compiles only when the target is the Simulator:
class MyClass {
func setupLogging() {
linphone_core_set_log_handler(my_callback)
}
}
func my_callback(_ domain: Optional<UnsafePointer<Int8>>,
level: OrtpLogLevel,
format: Optional<UnsafePointer<Int8>>,
args: CVaListPointer) { // NOTE: CVAListPointer is NOT optional
// do some logging
}
When I run on the device, logging works, so it appears that using the optional CVaListPoint? is the safest, so how do I get this to compile for the simulator.
The first version only compiles and runs on a device but issues this compiler error when targeting the simulator:
Swift Compiler Error
C function pointer signature
'(Optional<UnsafePointer<Int8>>, OrtpLogLevel,
Optional<UnsafePointer<Int8>>, CVaListPointer?) -> ()'
is not compatible with expected type 'OrtpLogFunc' (aka
'#convention(c)
(Optional<UnsafePointer<Int8>>, OrtpLogLevel,
Optional<UnsafePointer<Int8>>, CVaListPointer) -> ()')
The second version only compiles when targeting the simulator, but when targeting a device, it issues this error:
Swift Compiler Error
Cannot convert value of type
'(Optional<UnsafePointer<Int8>>, OrtpLogLevel,
Optional<UnsafePointer<Int8>>, CVaListPointer) -> ()'
to expected argument type 'OrtpLogFunc!'
Is there some way I can force the simulator to accept this function without changing the C headers?
Or, is there something I can do in Swift to make this work?
You'd better send a bug report to Apple or swift.org as soon as possible.
And, until this issue will be fixed, this sort of coding would be a workaround:
let my_callback: OrtpLogFunc = {domain, level, format, _args in
let args: CVaListPointer? = _args
// do some logging
}

solcover fail to generate test coverage with my simple add contract

I want to use solcover to generate test coverage of my contract.
https://github.com/JoinColony/solcover
I test it with the simple one:
contract Add {
function Add() {
}
function sum(uint x, uint y) returns (uint) {
return (x+y);
}
}
And here is my test code:
contract('Add', function(accounts) {
it("should return 5 when add 2 and 3", function() {
var add = Add.deployed();
return add.sum.call(2,3).then(function(res){
assert.equal(res.valueOf(), 5, "add result is 5");
});
});
});
But there are some errs when compile it.
Add.sol:2:1: Warning: Source file does not specify required compiler version!Consider adding "pragma solidity ^0.4.6
contract Add {
^
Spanning multiple lines.
Compilation failed. See above.
fs.js:549
Then i add compile version like this:
pragma solidity ^0.4.6;
contract Add {
function Add() {
}
function sum(uint x, uint y) returns (uint) {
return (x+y);
}
}
And now it pass the compile. But this time I got the error:
cp: no such file or directory: ./../originalContracts/Migrations.sol
rm: no such file or directory: ./allFiredEvents
Compiling Add.sol...
Contract: Add
✓ should return 5 when add 2 and 3
1 passing (15s)
fs.js:549
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT: no such file or directory, open './allFiredEvents'
at Error (native)
at Object.fs.openSync (fs.js:549:18)
at Object.fs.readFileSync (fs.js:397:15)
at Object.<anonymous> (/Users/maiffany/graduate/mytest/solcover/runCoveredTests.js:60:13)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
And in the runCoveredTests.js I found this:
55:shell.cp("./../originalContracts/Migrations.sol",./../contracts/Migrations.sol");
56:
57:shell.rm('./allFiredEvents'); //Delete previous results
58:shell.exec('truffle test --network coverage');
59:
60:events = fs.readFileSync('./allFiredEvents').toString().split('\n')
I guess maybe it is this command that generate file "allFiredEvents". So i try this in my command line:
truffle test --network coverage
Compiling Add.sol...
Contract: Add
✓ should return 5 when add 2 and 3
1 passing (24s)
But i still can't find the file "allFiredEvents".
So where did i get wrong?

undefined reference to `soup_session_new'

I am trying to make a get request in vala following this: https://wiki.gnome.org/Vala/LibSoupSample. I do exactly what it says and the compiler throws this:
Connection.vala.c:(.text+0x76): undefined reference to `soup_session_new'
collect2: ld returned 1 exit status
error: cc exited with status 256
Compilation failed: 1 error(s), 0 warning(s)
And this is the result from pkg-config --libs --cflags libsoup-2.4
-pthread -I/usr/include/libsoup-2.4 -I/usr/include/libxml2 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -lsoup-2.4 -lgio-2.0 -lgobject-2.0 -lglib-2.0
I have vala 0.20.1. runing on elementaryos (the newest stable version). Any ideas?
I had the same issue earlier today. It seems like the example is out of date. It's no longer called soup_session_new, the reference is now soup_session_sync_new. Use new Soup.SessionSync () and it should work.
Here's a working example:
using Soup;
int main (string[] args) {
string url = "http://google.com";
stdout.printf ("Getting data from %s\n", url);
var session = new Soup.SessionSync ();
var message = new Soup.Message ("GET", url);
session.send_message (message);
stdout.write (message.response_body.data);
return 0;
}

Resources