Friday, April 4, 2014

Java Dynamic Proxy

Java's Dynamic proxy is a way for programmers to dynamically generate proxy classes that wrap the class to proxy.

Here is the decompiled code of a dynamic proxy class generated , doSomething is the method of a class one wanted to proxy. This proxy method call InvocationHandler.invoke.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0
  extends Proxy
  implements AnInterface
{
  private static Method m3;
  private static Method m2;
  private static Method m0;
  private static Method m1;
 
  public $Proxy0(InvocationHandler paramInvocationHandler)
  {
    super(paramInvocationHandler);
  }
 
  public final void doSomething()
  {
    try
    {
      this.h.invoke(this, m3, null);
      return;
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
 
  public final String toString()
  {
    try
    {
      return (String)this.h.invoke(this, m2, null);
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
 
  public final int hashCode()
  {
    try
    {
      return ((Integer)this.h.invoke(this, m0, null)).intValue();
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
 
  public final boolean equals(Object paramObject)
  {
    try
    {
      return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
 
  static
  {
    try
    {
      m3 = Class.forName("AnInterface").getMethod("doSomething", new Class[0]);
      m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
      m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
      m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
      return;
    }
    catch (NoSuchMethodException localNoSuchMethodException)
    {
      throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
    }
    catch (ClassNotFoundException localClassNotFoundException)
    {
      throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
    }
  }



Monday, August 26, 2013

Node.js fs.watchFile error EventEmitter memory leak detected . Max listeners

This happens when fs.WatchFile is called on the same file multiple times.
Explaination
fs module contains a local object "statWatchers" {} to track files being watched.
So when fs.watchFile('fileX') is called a new statWatcher object is created if one does not exits and stored it in the "statWatchers" object against the file name. If there is already a statWatcher object associated with this file, it is returned.
statWatcher["fileX"] = new statWatcher();
And then calls addListener('change', listener) on the statWatcher object associated with this file.
Incase fs.watchFile is called for 11 times on "fileX", it will result in calling addListener on the statWatcher for event "change" 11 times.
EventEmitter throws an error if tried to add more than 11 listeners for the same event.

object.__proto__ and the prototype , Javascript

Everything in javascript is object.
And every object, it may be a function/ {} / new Object() , in javascript has an internal property called [[proto]].

[[proto]] is the very reason for prototype inheritance in javascript.

This internal property is exposed to the programmer through proto. This is a non standard.
Not all JS environments support this.

How does an object we create using constructor functions gets its [[proto]]?

Only objects whose [[class]] is "Function" gets the property 'prototype'. What it means is that every function declared when executed by the JS engine, it creates an object. Its [[class]] is set to "Function" and a property "prototype" is attached to this function object. By default this prototype is an object with one property "constructor" pointing to the function object.

When the above function is invoked as part of new operator like new constructorFn() , the JS engine creates an object , its [[class]] property set to "Object" and [[proto]] property set to the object pointed to by the [[proto]] of the constructor function.

Since this new created object is of class "Object" , it does not have the "prototype" property.
But has __proto__ pointing to the object as explained above

In nutshell, proto exists is in every object.

Prototype exists, by default, only in objects whose [[class]] is 'Function'.What this means is only functions (created via function statement , function expression , Function constructor fn) will have this property.

require in nodejs

Assuming this is the first time the module is being required.

For example ,

var x = require('file1.js');
contents of file1.js;
====================
module.exports = '123'

When the above statement is executed, a 'Module' object is created.
Module constructor function is provided below,

function Module(id, parent) {
    this.id = id;
    this.exports = {}; // the exports property which is actually return on require
    this.parent = parent;
    if (parent && parent.children) {
        parent.children.push(this);
    }

    this.filename = null;
    this.loaded = false;
    this.children = [];
}

As you see each module object has a property with name 'exports'.
This is what is eventually returned as part of require.

Next step of require is to wrap the contents of file1.js into an anonymous function like below :

(function (exports, require, module, __filename, __dirname) { 
    //contents from file1.js
    module.exports = '123;
});

And the above anonymous function is invoked the following way, module here refers to the Module Object created earlier.

(function (exports, require, module, __filename, __dirname) { 
    //contents from file1.js
    module.exports = '123;
}) (module.exports,require, module, "path_to_file1.js","directory of the file1.js");

As we can see inside the function , exports formal argument refers to module.exports.
In essence its a convenience provided to the module programmer.

However this convenience need to be exercised with care.
In any case if trying to assign a new object to exports ensure we do it this way.

exports = module.exports = {};

If we do it following way wrong way, module.exports will still be pointing to the object created as part of module instance.

exports = {};

As as result adding anything to the above exports object will have no effect to module.exports object and nothing will be exported or returned as part of require.

Monday, August 27, 2012

java spurious wakeups

What are spurious wakeups ?
In java , a thread t is put into waitset of an object 'a' by calling a.wait();
To be selected to be removed from a's waitset , there should be a call to a.notify / a.notifyAll from another thread.This is an example for explicit wake up(Which most programmers are aware of and think that this is the only possible way to wake up a waiting thread).

Note from JLS :
 An internal action by the implementation. Implementations are permitted, although not encouraged, to perform "spurious wake-ups", that is, to remove threads from wait sets and thus enable resumption without explicit instructions to do so.
Notice that this provision necessitates the Java coding practice of using wait only within loops that terminate only when some logical condition that the thread is waiting for holds.

 What it means ?
JVM implementation are given flexibility to wakeup a thread even when there is no explicit calls to either notify or notifyAll.Such wakeups, which are possible , are called spurious wakeups.

Consider the following code , for simplicity sake removed try catch blocks:

void method(){
  synchronized(a){
      if(cond / buffer empty){
         a.wait() ;
         //do some task asuming buffer is not empty.
      }
  }
}

In JVM where spurious wakeups are possible, consider the the case when the thread t is woke up spuriously , the following task assuming that buffer is not empty might break the program.

We have written the code assuming that there are no spurious wakeups allowed.Our code is sure to break in environments where such wakeups are allowed.Our code is not guarded.

So when writing code that waits guard your programs against spurious wakeups,

void method(){
  synchronized(a){
      while(cond / buffer empty){
         a.wait() ;
      }
      //do some task asuming buffer is not empty.
  }
}

In the above code, even when a thread is spuriously woke up, if the condition is  not met we are gonna wait again guarding us against spurious wakeups.

Tuesday, August 7, 2012

java security - AccessController dopriviledged

I see it as a straight lift of the unix feature setuid.

Source : Wiki
When an executable file has been given the setuid attribute, normal users on the system who have permission to execute this file gain the privileges of the user who owns the file within the created process.

For example the passwd executable.
Inorder for any user to change password one has to get access to the password file and modify its contents corresponding to this user.And its not feasible to give any user write permissions to the password file.

Solution :
A passwd executable owned by root is assigned setuid attribute and this is trusted code.Any non-root user who wants to change is password invokes 'passwd' executable.A process is spawned with its effective userid 'root' as the passwd executable has its setuid set.

Same is the case with AccessController.doPriviledged.


This is my trusted code and have given it permissions to change a file named 'security.txt'

class Trusted{
    public static void  modify(){
         //code to access and modify security.txt file
   }
}

UntrustedCode with no FilePermissions but need to modify security.txt

class UnTrusted {
 public static void modifythroughuntrusted(){
        Trusted.modify();
    }
}

When the above UnTrustedCode is executed there is a security exception raised.Let us examine the call stack,

UnTrusted.modifythroughuntrusted ---> Trusted. modify  ---> FilerelatedOperation which calls securitymanager to look if the current thread of execution has the required permissions to do so.

check 1 )  Trusted. modify ---> has file permission --- true
check 1 )  Trusted. modify ---> has file permission --- false

Hence we receive SecurityException.

Modify the code TrustedClass code 

class Trusted{
    public static void  modify(){
        AccessController.doPriviledged( new PriviledgedAction(){
           public void run(){
                   //code to access and modify security.txt file
          }
       }
   }
}

After this modification  the unTrustedCode will be able to modify the security.txt file, though it does not have the required filepermission.

Let us examine the call stack again

UnTrusted.modifythroughuntrusted ---> Trusted. modify  ---> FilerelatedOperation which calls securitymanager to look if the current thread of execution has the required permissions to do so.

check 1 )  Trusted. modify ---> has file permission --- true & this is marked priviledged so will not check the further callstack for permission and returns, allowing the code to proceed further.
 
---look this section for additions ---

Tuesday, June 5, 2012

JavaBeans Introspection

Java Bean are plain old java classes defined as per the patterns laid out by JavaBean Specification.

For an instance, consider the following class.It is a Java Bean with a property 'name';Similar conventions will be used to declare methods and events in Java Bean.

There is fat document that specifies guidelines on how to write compliant java beans.

public class MyJavaBean implements Serializable{
  private String name;
  public String getName(){

 }

 public void setName(){

 }

}

Java Bean came into existence with a sole purpose of allowing software component development, a reusable component.

Reflection is a way for a java programmer to reflect  a class definition programatically.Evey loaded class is associated with an object of type Class in the heap. class 'Class' has got methods that allow one to derive the methods , variables present in a class definition.

Introspection is for java Bean.There is a class 'Introspector' in java.beans package that given a java bean class will fetch JavaBeanInfo object with information like properties, method, events for given java bean class.

In essence it uses reflection api and the guidelines laid out by javabean spec to fetch the above information.