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.

Saturday, May 19, 2012

prototype vs __proto__ or proto Javascript

JavaScript prototype concept ,like closure, is very critical for efficient programming.
ECMA Script specification defines object type as collection of properties.

Each object has an internal property [[prototype]] which is the basis for all the prototype buzz in java script world. Internal property  means a.prototype (a is an object) is undefined.

function chandu(){

}

above declaration creates an object with the following properties

[[prototype]] ::: built in function prototype object
[[construct]]
[[call]]
[[class]] ::: Function
prototype ::: {constructor:chandu}
...

 As you can see we have two prototype properties
(i) [[prototype]] --- this is the object which is searched for when we try to access a property on any object if that property does not exist in the object.

(ii) prototype --- exists only for function objects.This is assigned to [[prototype]] property of any object created using the above function as constructor.
-this object is constructed using the express new Object() where Object is the built in constructor function.
-Object.prototype = the built in Object Prototype Object whose [[prototype]] ==null.This is where the prototype chain ends.

var a = new chandu();

-a is now an object created using chandu() as constructor function
-a's [[prototype]]  now holds the object referred to by the prototype(not the internal one) property of the chandu.
- there is no prototype own property in 'a' like what we had for chandu function object.

a.x  will first see if there is any property in 'a'.If not present it will search in the object referred by [[prototype]] property  of 'a'.


Lets see how the prototype chain looks for 'a'

p1 = a[[prototype]]
p2 = p[[prototype]]
p2 is the built in Object prototype object
p2[[prototype]]=null

Inheritance is achieved through the [[prototype]] internal property.And every ECMA object has this internal property.

Tuesday, May 15, 2012

Obfuscate JavaScript

https://developers.google.com/closure/compiler/docs/overview
Advanced options
https://developers.google.com/closure/compiler/docs/api-tutorial3#export

What is the Closure Compiler?

The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.
The Closure Compiler has been integrated with Page Speed, which makes it easier to evaluate the performance gains you can get by using the compiler.

How can I use the Closure Compiler?

You can use the Closure Compiler as:


  • An open source Java application that you can run from the command line.
  • A simple web application.
  • A RESTful API.
  • To get started with the compiler, see "How do I start" to the right.

    What are the benefits of using Closure Compiler?

    • Efficiency. The Closure Compiler reduces the size of your JavaScript files and makes them more efficient, helping your application to load faster and reducing your bandwidth needs.
    • Code checking. The Closure Compiler provides warnings for illegal JavaScript and warnings for potentially dangerous operations, helping you to produce JavaScript that is less buggy and easier to maintain.

    javascript : with Statement Considered Harmful


    Mynotes :

    with(obj) , adds the current object to the start of the current execution context's scope.
    with(obj){
      x=10;
    y=10;
    z=10;
    }
     if  the obj does not have a variable x as its property, x will be searched through the rest of the objects in scope and set if any x is found.
     Only if you are sure obj has x use with .

     Code A will rightly assign 11 to propery x of the object passed.
     However Code B will assign 11 to the global variable which is not intended.

    Things are trivial here but i tried to emphasize what 'with' can do if not properly understood and used.

    Code A
     <script>
                var x =10;
                with({x:10}){
                        x=11;
                }
                alert(x);
        </script>

     Code B
     <script>
                var x =10;
                with({y:10}){
                        x=11;
                }
                alert(x);
        </script>

     

    with Statement Considered Harmful

    April 11, 2006 at 7:52 am by Douglas Crockford | In Development | 64 Comments JavaScript’s with statement was intended to provide a shorthand for writing recurring accesses to objects. So instead of writing
    ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing = true;
    ooo.eee.oo.ah_ah.ting.tang.walla.walla.bang = true;
    You can write
    with (ooo.eee.oo.ah_ah.ting.tang.walla.walla) {
        bing = true;
        bang = true;
    }
    That looks a lot nicer. Except for one thing. There is no way that you can tell by looking at the code which bing and bang will get modifed. Will ooo.eee.oo.ah_ah.ting.tang.walla.walla be modified? Or will the global variables bing and bang get clobbered? It is impossible to know for sure.
    The with statement adds the members of an object to the current scope. Only if there is a bing in ooo.eee.oo.ah_ah.ting.tang.walla.walla will ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing be accessed.
    If you can’t read a program and be confident that you know what it is going to do, you can’t have confidence that it is going to work correctly. For this reason, the with statement should be avoided.
    Fortunately, JavaScript also provides a better alternative. We can simply define a var.
    var o = ooo.eee.oo.ah_ah.ting.tang.walla.walla;
    o.bing = true;
    o.bang = true;
    
    Now there is no ambiguity. We can have confidence that it is ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing and ooo.eee.oo.ah_ah.ting.tang.walla.walla.bang that are being set, and not some hapless variables.

    nice crockford articles

    http://www.crockford.com/javascript/