Category Archives: Object-oriented languages

Privates exposed

We’re all tempted, right… But don’t do it. Just don’t.

Access modifiers, as we all know, are fundamental part of object oriented languages. When used correctly, they help to provide clear interfaces for classes by data encapsulation and allow carefree development of software using various APIs. When you see a private (or protected) method, you think there’s a good reason why the one who implemented the class decided to do so. If for some reason you do need to go further than the public API allows you to, you usually find a valid workaround – and even then you question if there is a better way to achieve what you are trying to accomplish.

However, in some extremely rare cases you might find yourself in a situation where there is no workaround and without access to some protected/private method you are facing a wall. Or the possible workaround costs you hours or even weeks more work when with the access you could be done in just few minutes. What to do? Well, it’s up to you, but if you really want to take the easy (but risky) path, you can, since there really are no such things as protected or private. An access modifier is more than a recommendation though and you should think not twice but N times before dismissing one.

You have been warned

Accessing private bits in C++ is a bit tricky. The method I’d recommend is to get the address of, i.e. pointer to the function in question. You might need to calculate the offset from e.g. the class pointer, but this can be done by ye olde trial-and-error method. You may also consider trying #ifdef hacks, but those could drive you crazy with all the other errors they might cause.

In other languages, namely those that support the magicks of reflection (Java and C# for instance), things can be far more simple. For example, in (Android) Java you access and invoke a private method as follows:

Method method = SomeClass.class.getDeclaredMethod("methodName");
method.setAccessible(true);
SomeClass someClass = new SomeClass();
method.invoke(someClass);

The constructors and members are accessible in a similar fashion. See Class and Method classes for more information.

Note that  even though your code accessing and invoking private methods works now, you cannot rely it to work in the future. If – and often times when – the code you’re referencing and the private method signature changes, your code will throw a NoSuchMethodException. Therefore, it’s a no-brainer to surround the code with try-catch. But what then? What do you do when an exception is thrown and you’ve caught it. Albeit this is from programming 101, I’m gonna say it: Handle the exception gracefully; Your application has to perform even when your hack of access violation trickery doesn’t! Same goes regardless of what your weapon (language) of choice is.

I warned you

 

Case Android Bluetooth socket

I was working on a cross-platform peer web project called Thali. Furthermore, I was in charge of the native Android layer of the project (see Thali Android Connector Library). We had had issues (in addition to number of other problems) with failing Bluetooth sockets, namely in the connection process.

We noticed that many reported better results using a workaround that they used to create a socket with a specified port. One uses BluetoothDevice class to construct BluetoothSocket instances. However, using the publicly available methods (read: the methods intended to be used) to create sockets one cannot define the port – instead the port is decided for you. If you really want to define the port yourself, there is a way: Use reflection to invoke the method with which you can define the port. And it’s not even protected/private, just cannot be called directly:

// bluetoothDevice is an instance of BluetoothDevice class
Method method = bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
BluetoothSocket bluetoothSocket = (BluetoothSocket) method.invoke(bluetoothDevice, 1); // 1 is the port number

This solution didn’t work for us since Thali project uses insecure RFCOMM sockets vs. the secure ones and the method for constructing insecure sockets with a specified port number is neither public nor available. Thus, to accomplish the same effect as the aforementioned code snippet, one has to access the private constructor of the BluetoothSocket class. So I created a helper method which allows you to construct both secure and insecure BluetoothSocket instances with the desired channel/port (see BluetoothUtils class in Thali Android Connectivity Library project):

public static BluetoothSocket createBluetoothSocketToServiceRecord(
        BluetoothDevice bluetoothDevice, UUID serviceRecordUuid, int channelOrPort, boolean secure) {
    Constructor[] bluetoothSocketConstructors = BluetoothSocket.class.getDeclaredConstructors();
    Constructor bluetoothSocketConstructor = null;

    for (Constructor constructor : bluetoothSocketConstructors) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        boolean takesBluetoothDevice = false;
        boolean takesParcelUuid = false;

        for (Class<?> parameterType : parameterTypes) {
            if (parameterType.equals(BluetoothDevice.class)) {
                takesBluetoothDevice = true;
            } else if (parameterType.equals(ParcelUuid.class)) {
                takesParcelUuid = true;
            }
        }

        if (takesBluetoothDevice && takesParcelUuid) {
            // We found the right constructor
            bluetoothSocketConstructor = constructor;
            break;
        }
    }

    // This is the constructor we should now have:
    // BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, BluetoothDevice device,
    //      int port, ParcelUuid uuid) throws IOException

    // Create the parameters for the constructor
    Object[] parameters = new Object[] {
            Integer.valueOf(1), // BluetoothSocket.TYPE_RFCOMM
            Integer.valueOf(-1),
            Boolean.valueOf(secure),
            Boolean.valueOf(secure),
            bluetoothDevice,
            Integer.valueOf(channelOrPort),
            new ParcelUuid(serviceRecordUuid)
    };

    bluetoothSocketConstructor.setAccessible(true);
    BluetoothSocket bluetoothSocket = null;

    try {
        bluetoothSocket = (BluetoothSocket)bluetoothSocketConstructor.newInstance(parameters);
        Log.d(TAG, "createBluetoothSocketToServiceRecord: Socket created with channel/port " + channelOrPort);
    } catch (Exception e) {
        Log.e(TAG, "createBluetoothSocketToServiceRecord: Failed to create a new Bluetooth socket instance: " + e.getMessage(), e);
    }

    return bluetoothSocket;
}

What good did it do?

None. Jacksh*t! It did no good at all as far as I can tell.

“Paskaaks se mitään teki.”

The hack didn’t solve our problems. Turns out the problem was elsewhere and fault of my own (I’ll let you in on a secret, if you haven’t realized it by now: I’m not a guru. I’m not a master programmer. I’m your average software developer and, if anything, I’m lazy enough to find quick, clean solutions to problems that usually work.) That said, the hack might have provided useful on earlier versions of Android, but the possible platform issue was most likely fixed on Lollipop and newer. With the hack the Bluetooth socket worked as well as without the trickery and when it was bound to fail it did so regardless.

So as final words I give you…

Reasons why NOT to access protected/private stuff

  1. 99.9 times out of 100, there’s really no need – work around it!
  2. Given that whoever wrote the code is not a complete tool, made it inaccessible for a reason.
  3. Your hack won’t most probably be sustainable. It will break. Just see. Unless, of course, no one will eveeeeer touch the code you’re referencing.
  4. As per the aforementioned – you have to keep maintaining your code constantly to make sure it stays up-to-date with the code you are referencing.
  5. You’re just asking for trouble.
  6. Go to 1.
Run away
The recommended action