Finding dylib version using dlopen - dylib

Is there a way to find the version of a dylib using its path? I am looking for something that accepts the same arguments as dlopen. I have looked at NSVersionOfRunTimeLibrary, but from my reading of the documentation it looks like it gets the version of the current dylib, not the one specified in the path.
Thank you

Run otool -L on it, and it will show its actually version. I choose libSystem.B as it has different version in the 10.4 and 10.5 SDKs:
$ otool -L /Developer/SDKs/MacOSX10.4u.sdk/usr/lib/libSystem.B.dylib
/Developer/SDKs/MacOSX10.4u.sdk/usr/lib/libSystem.B.dylib:
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.3.11)
/usr/lib/system/libmathCommon.A.dylib (compatibility version 1.0.0, current version 220.0.0)
$ otool -L /Developer/SDKs/MacOSX10.5.sdk/usr/lib/libSystem.B.dylib
/Developer/SDKs/MacOSX10.5.sdk/usr/lib/libSystem.B.dylib:
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 111.1.4)
/usr/lib/system/libmathCommon.A.dylib (compatibility version 1.0.0, current version 292.4.0)
(see how the first one has 88.3.11 version, while the second has 111.1.4). This example also shows that not all libraries are symbolic links to files with the version number in them:
$ ll /Developer/SDKs/MacOSX10.*.sdk/usr/lib/libSystem.B.dylib
-rwxr-xr-x 1 root wheel 749K May 15 2009 /Developer/SDKs/MacOSX10.4u.sdk/usr/lib/libSystem.B.dylib
-rwxr-xr-x 1 root wheel 670K May 15 2009 /Developer/SDKs/MacOSX10.5.sdk/usr/lib/libSystem.B.dylib
-rwxr-xr-x 1 root wheel 901K Sep 25 00:21 /Developer/SDKs/MacOSX10.6.sdk/usr/lib/libSystem.B.dylib
Here, the files don't have the version number in their name.
EDIT: a second solution is to use NSVersionOfRunTimeLibrary in a test program, in which you force load the library you want to check. Create a program libversion from the following C source:
#include <stdio.h>
#include <mach-o/dyld.h>
int main (int argc, char **argv)
{
printf ("%x\n", NSVersionOfRunTimeLibrary (argv[1]));
return 0;
}
Then, you call it like that:
$ DYLD_INSERT_LIBRARIES=/usr/lib/libpam.2.dylib ./a.out libpam.2.dylib
30000
(here, the version number is printed as hexadecimal, but you can adapt to your needs.)

You can check the source code of NSVersionOfRunTimeLibrary here:
http://www.opensource.apple.com/source/dyld/dyld-132.13/src/dyldAPIsInLibSystem.cpp
Based on that you can create your own version which replaces if(names_match(install_name, libraryName) == TRUE) with if(strcmp(_dyld_get_image_name(i), libraryName) == 0)
That will fix the issue that the original expected the library name without full path, the edited version expects the full path, but it'll still search in the loaded dylibs.
#include <mach-o/dyld.h>
int32_t
library_version(const char* libraryName)
{
unsigned long i, j, n;
struct load_command *load_commands, *lc;
struct dylib_command *dl;
const struct mach_header *mh;
n = _dyld_image_count();
for(i = 0; i < n; i++){
mh = _dyld_get_image_header(i);
if(mh->filetype != MH_DYLIB)
continue;
load_commands = (struct load_command *)
#if __LP64__
((char *)mh + sizeof(struct mach_header_64));
#else
((char *)mh + sizeof(struct mach_header));
#endif
lc = load_commands;
for(j = 0; j < mh->ncmds; j++){
if(lc->cmd == LC_ID_DYLIB){
dl = (struct dylib_command *)lc;
if(strcmp(_dyld_get_image_name(i), libraryName) == 0)
return(dl->dylib.current_version);
}
lc = (struct load_command *)((char *)lc + lc->cmdsize);
}
}
return(-1);
}

Related

C++17 refuses to compile example if constexpr giving expected ‘(’ before ‘constexpr’

I am trying out this text-book example of using if constexpr and I am getting error expected ‘(’ before ‘constexpr’ when compiling.
I am compiling with g++ -std=c++17 test.cpp so the version should support it. Visual Studio Code understands this and hints that this expression will be compiled to number 120 (correct).
#include <iostream>
using std::cout;
using std::endl;
template <int N>
constexpr int fun() {
if constexpr (N <= 1) {
return 1;
} else {
return N * fun<N - 1>();
}
}
int main(int argc, char** argv) {
cout << fun<5>() << endl;
return 0;
}
This code should compile error-free
You need a more recent version of GCC. Version 7 and up support this. See:
https://en.cppreference.com/w/cpp/compiler_support#cpp17
(Search for "constexpr if".)
So upgrade your GCC version. If you're on Ubuntu, you can add the Toolchain PPA to install the latest available GCC version:
https://launchpad.net/~ubuntu-toolchain-r/+archive/ubuntu/test

How to get diskutil info output in a cocoa application

Is there a way to programmatically get the same information that diskutil info / | grep "Free Space" gives you? (For obvious reasons I'd rather have a better way to do this than just parsing the result of that command.)
Currently I'm using statfs; however, it was brought to my attention that the space this reports is not always accurate, because OS X also places temporary files such as Time Machine snapshots on the drive. These files automatically get deleted if space is running out, and the OS does not report the usage of these files. In other words, statfs often gives a lower number of free space than diskutil info or looking at the disk information in Finder.
You can use popen(3):
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *f;
char info[256];
f = popen("/usr/sbin/diskutil info /", "r");
if (f == NULL) {
perror("Failed to run diskutil");
exit(0);
}
while (fgets(info, sizeof(info), f) != NULL) {
printf("%s", info);
}
pclose(f);
return 0;
}
EDIT
Sorry, I didn't read the question carefully. You can also use the Disk Arbitration Framework. There's also some sample code that might be helpful (FSMegaInfo).
UPDATE
I took a look at the output from otool -L $(which diskutil) and it seems that it's using a private framework called DiskManagement.framework. After looking at the output from class-dump I saw there's a volumeFreeSpaceForDisk:error: method. So the sizes I got from diskutil -info / and FSMegaInfo FSGetVolumeInfo / and my tool were:
diskutil: 427031642112 Bytes
my tool: volumeFreeSpaceForDisk: 427031642112
FSMegaInfo: freeBytes = 427031642112 (397 GB)
I also observed that the sizes differ (with a few KB) every time I ran one of the tools and also that diskutil is dividing by 1000 and FSMegaInfo is dividing by 1024, so the size in GB will be always different (same reason as with df -h and df -H and diskutil - base 10 and base 2).
Here's my sample tool:
#import <Foundation/Foundation.h>
#import "DiskManagement.h"
#import <DiskArbitration/DADisk.h>
int main(int argc, char *argv[])
{
int err;
const char * bsdName = "disk0s2";
DASessionRef session;
DADiskRef disk;
CFDictionaryRef descDict;
session = NULL;
disk = NULL;
descDict = NULL;
if (err == 0) {session = DASessionCreate(NULL); if (session == NULL) {err = EINVAL;}}
if (err == 0) {disk = DADiskCreateFromBSDName(NULL, session, bsdName); if (disk == NULL) {err = EINVAL;}}
if (err == 0) {descDict = DADiskCopyDescription(disk); if (descDict == NULL) {err = EINVAL;}}
DMManager *dmMan = [DMManager sharedManager];
NSLog(#"blockSizeForDisk: %#", [dmMan blockSizeForDisk:disk error:nil]);
NSLog(#"totalSizeForDisk: %#", [dmMan totalSizeForDisk:disk error:nil]);
NSLog(#"volumeTotalSizeForDisk: %#", [dmMan volumeTotalSizeForDisk:disk error:nil]);
NSLog(#"volumeFreeSpaceForDisk: %#", [dmMan volumeFreeSpaceForDisk:disk error:nil]);
return 0;
}
You can obtain the DiskManagement.h by running class-dump /System/Library/PrivateFrameworks/DiskManagement.framework/Versions/Current/DiskManagement > DiskManagement.h and you can link to that framework by including the private frameworks path using -F/System/Library/PrivateFrameworks/ and add -framework.
Compile:
clang -g tool.m -F/System/Library/PrivateFrameworks/ -framework Foundation -framework DiskArbitration -framework DiskManagement -o tool
UPDATE2:
You can also take a look here and here. If the FSMegaInfo sample is not working for you, then you can just stat the /Volumes/.MobileBackups and subtract it's size from what you get from statfs("/", &stats).

How to get dylib version information which are in a directory

I wanted to get the dylib version. I've a dylib path for which I wanted to get the version number.
I've tried "otool -L" command and it's giving me the proper output but as per the requirements I can't use it, since I've 100 of dylib in a directory for which I wanted to get the version information and I can't run "otool" command for each dylib through NSTask and NSPipe.
I've also found the NSVersionOfLinkTimeLibrary() function to get the dylib version, but as per the documentation NSVersionOfLinkTimeLibrary returns the version number for linked libraries and not for other dylib.
Any help on this would be helpful.
Thanks.
Omkar
I've solved it by writing my own dylib parser. Below is the code snippet
- (int64_t)getDylibVersion :(NSString *)dylibPth
{
const char* strFilePath = [dylibPth UTF8String];
FILE* fileHandle = fopen(strFilePath, "rb");
struct mach_header mh;
if(fileHandle)
{
size_t bytesRead = fread(&mh, 1, sizeof(mh), fileHandle);
if(bytesRead == sizeof(mh))
{
if((mh.magic == MH_MAGIC_64 || mh.magic == MH_MAGIC) && mh.filetype == MH_DYLIB)
{
for(int j = 0; j < mh.ncmds; j++)
{
union
{
struct load_command lc;
struct dylib_command dc;
} load_command;
if (sizeof(load_command.lc) != fread(&load_command.lc, 1, sizeof(load_command.lc), fileHandle))
goto fail;
switch (load_command.lc.cmd)
{
case LC_SEGMENT:
break;
case LC_UUID:
break;
case LC_DYLD_INFO_ONLY:
break;
case LC_SYMTAB:
break;
case LC_LOAD_DYLIB:
break;
case LC_ID_DYLIB:
{
if (sizeof(load_command) - sizeof(load_command.lc) != fread(&load_command.lc + 1, 1, sizeof(load_command) - sizeof(load_command.lc), dylib_handle))
goto fail;
fclose(fileHandle);
return(load_command.dc.dylib.current_version);
}
default:
break;
}
if (0 != fseek(fileHandle, load_command.lc.cmdsize - sizeof(load_command.lc), SEEK_CUR))
goto fail;
}
}
}
}
fail:
fclose(fileHandle);
return (-1);
}
Note that Mach-O dylib version numbers are encoded as 32-bit unsigned integers, with the major version in the high 16 bits, the minor version in bits 8 through 15, and the patch level in the low 8 bits:
uint32_t version = …;
uint32_t major = version >> 16;
uint32_t minor = (version >> 8) & 0xff;
uint32_t revision = version & 0xff;
Note also that the above code will only work for "thin" binaries. "Fat," multi-architecture binaries start with a fat header, which you'll need to negotiate first to find the slice for your desired architecture. Moreover, the above only works with architectures of the running architecture's endianness.
The way I see it, you have 2 options.
Load each dylib into your process and lookup the Mach-O headers on each, looking for the version numbers. The documentation should be complete and thorough enough to get you started.
Open each dylib as a normal file, and read and parse the Mach-O headers yourself. This avoid having to load each dylib into the process, but it does mean you need to then either parse the Mach-O binary format yourself, or find a library that can do it for you (I don't know of any off the top of my head).

Building release version of a project with Android NDK r6

I am compiling helloworld example of Android NDK r6b using cygwin and Windows Vista. I have noticed that the following code takes between 14 and 20 mseconds on my Android phone (it has an 800mhz CPU Qualcomm MSM7227T chipset, with hardware floating point support):
float *v1, *v2, *v3, tot;
int num = 50000;
v1 = new float[num];
v2 = new float[num];
v3 = new float[num];
// Initialize vectors. RandomEqualREAL() returns a floating point number in a specified range.
for ( int i = 0; i < num; i++ )
{
v1[i] = RandomEqualREAL( -10.0f, 10.0f );
if (v1[i] == 0.0f) v1[i] = 1.0f;
v2[i] = RandomEqualREAL( -10.0f, 10.0f );
if (v2[i] == 0.0f) v2[i] = 1.0f;
}
clock_t start = clock() / (CLOCKS_PER_SEC / 1000);
tot = 0.0f;
for ( int k = 0; k < 1000; k++)
{
for ( int i = 0; i < num; i++ )
{
v3[i] = v1[i] / (v2[i]);
tot += v3[i];
}
}
clock_t end = clock() / (CLOCKS_PER_SEC / 1000);
printf("time %f\n", tot, (end-start)/1000.0f);
On my 2.4ghz notebook it takes .45 msec (timings taken when the system is full of other programs running, like Chrome, 2/3 ides, .pdf opens etc...). I wonder if the helloworld application is builded as a release version. I noticed that g++ get called with
-msoft-float.
Does this means that it is using floating point emulations?
What command line options i need to use in order to build an optimized version of the program? How to specify those options?
This is how g++ get called.:
/cygdrive/d/android/android-ndk-r6b/toolchains/arm-linux-androideabi-4.4.3/prebu
ilt/windows/bin/arm-linux-androideabi-g++ -MMD -MP -MF D:/android/workspace/hell
oworld/obj/local/armeabi/objs/ndkfoo/ndkfoo.o.d.org -fpic -ffunction-sections -f
unwind-tables -fstack-protector -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_
5E__ -D__ARM_ARCH_5TE__ -Wno-psabi -march=armv5te -mtune=xscale -msoft-float -f
no-exceptions -fno-rtti -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -f
inline-limit=64 -ID:/android/workspace/helloworld/jni/boost -ID:/android/workspa
ce/helloworld/jni/../../mylib/jni -ID:/android/android-ndk-r6b/sources/cxx-stl/g
nu-libstdc++/include -ID:/android/android-ndk-r6b/sources/cxx-stl/gnu-libstdc++/
libs/armeabi/include -ID:/android/workspace/helloworld/jni -DANDROID -Wa,--noex
ecstack -fexceptions -frtti -O2 -DNDEBUG -g -ID:/android/android-ndk-r6b/plat
forms/android-9/arch-arm/usr/include -c D:/android/workspace/helloworld/jni/ndk
foo.cpp -o D:/android/workspace/helloworld/obj/local/armeabi/objs/ndkfoo/ndkfoo.
o && ( if [ -f "D:/android/workspace/helloworld/obj/local/armeabi/objs/ndkfoo/nd
kfoo.o.d.org" ]; then awk -f /cygdrive/d/android/android-ndk-r6b/build/awk/conve
rt-deps-to-cygwin.awk D:/android/workspace/helloworld/obj/local/armeabi/objs/ndk
foo/ndkfoo.o.d.org > D:/android/workspace/helloworld/obj/local/armeabi/objs/ndkf
oo/ndkfoo.o.d && rm -f D:/android/workspace/helloworld/obj/local/armeabi/objs/nd
kfoo/ndkfoo.o.d.org; fi )
Prebuilt : libstdc++.a <= <NDK>/sources/cxx-stl/gnu-libstdc++/libs/armeabi
/
cp -f /cygdrive/d/android/android-ndk-r6b/sources/cxx-stl/gnu-libstdc++/libs/arm
eabi/libstdc++.a /cygdrive/d/android/workspace/helloworld/obj/local/armeabi/libs
tdc++.a
SharedLibrary : libndkfoo.so
/cygdrive/d/android/android-ndk-r6b/toolchains/arm-linux-androideabi-4.4.3/prebu
ilt/windows/bin/arm-linux-androideabi-g++ -Wl,-soname,libndkfoo.so -shared --sys
root=D:/android/android-ndk-r6b/platforms/android-9/arch-arm D:/android/workspac
e/helloworld/obj/local/armeabi/objs/ndkfoo/ndkfoo.o D:/android/workspace/hellow
orld/obj/local/armeabi/libstdc++.a D:/android/android-ndk-r6b/toolchains/arm-lin
ux-androideabi-4.4.3/prebuilt/windows/bin/../lib/gcc/arm-linux-androideabi/4.4.3
/libgcc.a -Wl,--no-undefined -Wl,-z,noexecstack -lc -lm -lsupc++ -o D:/androi
d/workspace/helloworld/obj/local/armeabi/libndkfoo.so
Install : libndkfoo.so => libs/armeabi/libndkfoo.so
mkdir -p /cygdrive/d/android/workspace/helloworld/libs/armeabi
install -p /cygdrive/d/android/workspace/helloworld/obj/local/armeabi/libndkfoo.
so /cygdrive/d/android/workspace/helloworld/libs/armeabi/libndkfoo.so
/cygdrive/d/android/android-ndk-r6b/toolchains/arm-linux-androideabi-4.4.3/prebu
ilt/windows/bin/arm-linux-androideabi-strip --strip-unneeded D:/android/workspac
e/helloworld/libs/armeabi/libndkfoo.so
Edit.
I have run the commnad adb shell cat /proc/cpuinfo. This is the result:
Processor : ARMv6-compatible processor rev 5 (v6l)
BogoMIPS : 532.48
Features : swp half thumb fastmult vfp edsp java
CPU implementer : 0x41
CPU architecture: 6TEJ
CPU variant : 0x1
CPU part : 0xb36
CPU revision : 5
Hardware : GELATO Global board (LGE LGP690)
Revision : 0000
Serial : 0000000000000000
I don't understand what swp, half thumb fastmult vfp edsp and java means, but i don't like that 'vfp'!! Does it means virtual-floating points? That processor should have a floating point unit...
You are right, -msoft-float is a synonym for -mfloat-abi=soft (see list of gcc ARM options) and means floating point emulation.
For hardware floating point the following flags can be used:
LOCAL_CFLAGS += -march=armv6 -marm -mfloat-abi=softfp -mfpu=vfp
To see what floating point unit you really have on your device you can check the output of adb shell cat /proc/cpuinfo command. Some units are compatible with another: vfp < vfpv3-d16 < vfpv3 < neon - so if you have vfpv3, then vfp also works for you.
Also you might want to add the line
APP_OPTIM := release
into your Application.mk file. This setting overrides automatic 'debug' mode for native part of application if the manifest sets android:debuggable to 'true'
But even with all these settings NDK will put -march=armv5te -mtune=xscale -msoft-float into the beginning of compiler options. And this behavior can not be changed without modifications in NDK sources (these options are hardcoded in file $NDKROOT\toolchains\arm-linux-androideabi-4.4.3\setup.mk).

Boost serialization: archive "unsupported version" exception

I've got the exception "unsupported version" when I try to deserialize through a text archive some data previously serialized with a upper version of Boost (1.46 to serialize and 1.38 to deserialize)...is there a way to downgrade (in the code) the serialization?
Something like "set_library_version"?
See the Error read binary archive, created by old Boost version mail archive post about the serialization error.
It says that the code below does the job:
void load_override(version_type & t, int version){
library_version_type lvt = this->get_library_version();
if (boost::archive::library_version_type(7) < lvt){
this->detail_common_iarchive::load_override(t, version);
}
else
if (boost::archive::library_version_type(6) < lvt){
uint_least16_t x = 0;
* this->This() >> x;
t = boost::archive::version_type(x);
}
else
if (boost::archive::library_version_type(3) == lvt ||
boost::archive::library_version_type(5) == lvt){
#pragma message("CTMS fix for serialization bug (lack of backwards compatibility) introduced by Boost 1.45.")
// Up to 255 versions
unsigned char x = 0;
* this->This() >> x;
t = version_type(x);
}
else{
unsigned int x = 0;
* this->This() >> x;
t = boost::archive::version_type(x);
}
}
Using text_archive ... I had a recent issue with this also.
I recently upgraded boost from 1.67 to 1.72 on Windows, generated some data on Windows. When I ran the data on my Linux environment which is still on Boost 1.67, it throws not supported.
The header for 1.67 looked like this
22 serialization::archive 16
and 1.72 looked like
22 serialization::archive 17
I changed 17 to 16 and it was happy for my use case.