2013年11月9日星期六

Install eclipse in linux

sudo apt-get install eclipse eclipse-jdt eclipse-pde eclipse-platform eclipse-rcp eclipse-cdt g++


Support C/C++: eclipse-cdt g++

2013年11月1日星期五

Download Java SDK for ubuntu

For Oracle-JDK,
 
Step1)
Remove the OpenJDK
sudo apt-get purge openjdk*
 
Step2)
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
 
Step3)
Step3a) For JAVA8, sudo apt-get install oracle-java8-installer
Step3b) For JAVA7, sudo apt-get install oracle-java7-installer
Step3c) For JAVA6, sudo apt-get install oracle-java6-installer   
 
__________________________________________________________________________
For Open-JDK, 
 
$ sudo add-apt-repository "deb http://archive.canonical.com/ lucid partner"
$ sudo apt-get update
$ sudo apt-get install openjdk-6-jdk
 
 
openjdk-6-jdk 
openjdk-7-jdk

2013年10月30日星期三

Resize VirtualBox disk size

Suppose we are using Windows as the Host

Step 1) List hard disk drive
Open the command prompt and enter:
cd "C:\Program Files\Oracle\VirtualBox\"
vboxmanage list hdds

you will see something like this:
UUID: 5ebf0266-4e9e-4b7e-b9f6-6d67514919c3
Parent UUID: base
Format: VDI
Location: /VBOX/Windows XP/Windows XP.vdi
State: inaccessible
Type: normal
Usage: Windows XP (x86) (UUID: c90339ab-edb1-4b30-890b-ea7153b6cf4b)

Step 2) Determine the file is ended with VDI or VMDK extension.
If it is VDI, goto step 3a.
If it is VMDK, goto step 3b.

Step 3a) Resize the disk using UUID <- Recommended

Using the above as an example:
50000 = 50GB

VBoxManage modifyhd 5ebf0266-4e9e-4b7e-b9f6-6d67514919c3 --resize 50000

Step 3b) Resize the disk size by selecting UUID <- Recommended

Using the above as an example:
50000 = 50GB

VBoxManage clonehd 5ebf0266-4e9e-4b7e-b9f6-6d67514919c3 "c:\temp\clone.vdi" --format VDI
VBoxManage modifyhd "c:\temp\clone.vdi" --resize 50000
VBoxManage clonehd "c:\temp\clone.vdi" "NEW_HARK_DISK_DEST" --format VMDK

Attach the re-sized disk in VirtualBox.


Step 4)
Use GParted to expand the partition.

After verify the disk is working properly,
the original disk and also the "c:\temp\clone.vdi" one can be deleted safely.

2013年8月22日星期四

Encounter "UUID is duplicate" message after moving the VirtualBox image file

C:\Program Files\Oracle\VirtualBox> VBoxManage internalcommands sethduuid "E:\VirtualBox VMs\centos\centos.vdi"


2013年8月19日星期一

GRUB2 general configuration

grub-mkconfig, default is output to stdout

Valid keys are in the /etc/default/grub

--------------------------------------------------------

Manually add the menu entry)

1) Adding extra custom menu entries to the end of the list can be done by editing /etc/grub.d/40_custom
Alternatively, in/etc/grub.d folder, create the file XX_whichos where XX is the number. It is used to indicate the ordering of the menuitem.

2) After the file is edited, make it executable.
sudo chmod +x /etc/grub.d/XX_whichos

3) Execute "update-grub2" command

The updated grub.cfg will be placed at /boot/grub/ folder

=====================================================
For traditional partition,

Windows 7 entry (first harddisk, 2nd primary partition)

menuentry ‘Windows 7′ {
set root=’(hd0,msdos2)’
chainloader +1
}

=====================================================
For EFI,

menuentry "Windows 7" {
insmod part_gpt
insmod fat
insmod search_fs_uuid
insmod chain
search --fs-uuid --no-floppy --set=root 080F-E6DA
chainloader (${root})/efi/Microsoft/Boot/bootmgfw.efi
}

UUID can be obtained from blkid

=====================================================


2013年8月18日星期日

ncat usage


quota from "http://nmap.org/ncat/guide/ncat-usage.html":


Main usage:

Ncat always operates in one of two basic modes: connect mode and listen mode. In connect mode, Ncat initiates a connection (or sends UDP data) to a service that is listening somewhere. For those familiar with socket programming, connect mode is like using the connect function. In listen mode, Ncat waits for an incoming connection (or data receipt), like using the bind and listen functions. You can think of connect mode as client mode and listen mode as server mode.

Connect mode:
ncat <host> [<port>]

Listen mode:
ncat -l [<host>] [<port>]

In listen mode, <host> controls the address on which Ncat listens; if you omit it, Ncat will bind to all local interfaces (INADDR_ANY). If the port number is omitted, Ncat uses its default port 31337.Typically only privileged (root) users may bind to a port number lower than 1024. A listening TCP server normally accepts only one connection and will exit after the client disconnects. Combined with the --keep-open option, Ncat accepts multiple concurrent connections up to the connection limit. With --keep-open (or -k for short), the server receives everything sent by any of its clients, and anything the server sends is sent to all of them. A UDP server will communicate with only one client (the first one to send it data), because in UDP there is no list of “connected” clients.

Ncat can use TCP, UDP, SCTP, SSL, IPv4, IPv6, and various combinations of these. TCP over IPv4 is the default.

-------------------------------------------------------------------------

File transfer using ncat:

input file on host1
output file on host2

Transfer a file, receiver listens
host2$ ncat -l > outputfile
host1$ ncat --send-only host2 < inputfile

Transfer a file, sender listens
host1$ ncat -l --send-only < inputfile
host2$ ncat host1 > outputfile


Transfer a bundle of files

host2$ ncat -l | tar xzv
host1$ tar czv <files> | ncat --send-only host2


---------------------------------------------------------------------------


Example. Running a command with --sh-exec
ncat -l --sh-exec "echo `pwd`"

Example. Ncat as mail client

$ ncat -C mail.example.com 25
220 mail.example.com ESMTP
HELO client.example.com
250 mail.example.com Hello client.example.com
MAIL FROM:a@example.com
250 OK
RCPT TO:b@example.com
250 Accepted
DATA
354 Enter message, ending with "." on a line by itself
From: a@example.com
To: b@example.com
Subject: Greetings from Ncat

Hello. This short message is being sent by Ncat.
.
250 OK
QUIT
221 mail.example.com closing connection

2013年8月16日星期五

Compress / Extract Files using tar Command

tar.bz2 file:
Compress:
tar -jcvf archive_name.tar.bz2 directory_to_compress

Extract:
tar -jxvf archive_name.tar.bz2
tar -jxvf archive_name.tar.bz2 -C /tmp/extract_here/

------------------------------------------------------------------------

tar.gz file:
Compress:
:tar -cvzf archive_name.tar.gz directory_to_compress/

Extract:
tar -zxvf archive_name.tar.gz
tar -zxvf archive_name.tar.gz -C /tmp/extract_here/

------------------------------------------------------------------------

tar file:
Compress:
tar -cvf archive_name.tar directory_to_compress
Extract:
tar -xvf archive_name.tar
tar -xvf archive_name.tar -C /tmp/extract_here/

------------------------------------------------------------------------

tar.xz file:
Compress:
tar -cvJf archive_name.tar.xz
Extract:
tar -xvJf archive_name.tar.xz
tar -xvJf archive_name.tar.xz -C /tmp/extract_here/

2013年8月15日星期四

Setup COM port in VirtualBox (Host: XUbuntu, Guest: Windows XP)

In VirtualBox Setting,
Port Number: COM1
IRQ: 4
I/O Port: 0x3F8
Port Mode: Host Device
Port/File Path: /dev/ttyS0

If encounter read/write permission error,
add the current Linux account to:
'dialout' Group

In xubuntu, System Administrator > 'Edit Group...' , add current user to the 'dialup' group

Check serial port in Linux:
dmesg | grep tty
If the screen shows out ttyS0, it means COM1

FYI,
as previous 'dialout' group account stated,
ls -l /dev/ttyS0 can view the COM1 permission group.

Executing background task while running SSH

nohup ./whatever > /dev/null 2>&1 &

Enable / Lock root account in Linux

Lock root account in Linux:
sudo passwd -l root

Enable root account in Linux:
sudo passwd root


2013年8月1日星期四

Effective C++ notes (Rule 1 - Rule 10)

Rule 1: View C++ as a federation of language

view as 4 sub language
a) C
b) Object-oriented C
c) Template C++
d) STL

C++ Looks like 4 "sub-language" merge to form a language.
They are different => we should understand each "sub-language" behavior.

------------------------------------------------------

Rule 2: consts, enums and inlines to #define

Use: consts replace define
easy for symbol table look up, debug made easy, const = 1 copy only
class:

class c
{
static const int a = 5;
};

For some of old compilers:
In header:
class c
{
static const int v1;
}

In source:
const int c::v1 = 1;

Use enum:
class c
{
enum {v1 = 1};
int i[v1];
}
//can be found in template metprogramming

Use: template<typename T>
inline void CallWithMax(const T& a, const T& b)
{
f(a>b?a:b);
}

not:
#define CALL_WITH_MAX(a,b) f((a)>b()?(a):(b))

-------------------------------------------------------------

Rule 3: Use const whenever possible

char greeting[] = "Hello";
char* p = greeting; //non-const pointer, non-const data
const char* p = greeting; //non-const pointer, const data
char* const p = greeting; //const pointer, non-const data
const char* const p = greeting; //const pointer, const data

In other words,
const located at: (left)*, const data
const located at: *(right), const pointer

void f1(const Widget* pw);
is as same as
void f2(Widget const * pw);

iterator
const_iterator //cannot change value

logical-constness
mutable,prevent "bitwise-constness"

operator[] overload:
merge const operator[] and operator[]:
const cha& operator[] (std::size_t position)const
{
return text[position];
}
char& operator[](std::size_t position)
{
return
const_cast<char&>(
static_cast<const TextBlock&>(*this)[posiiton];
)
}

-------------------------------------------------------------

Rule 4: Make sure that objects are initialized before they are used

ABEntry::ABEntry(const str::string& name, const std::string& address)
{
theName = name;
theAddress = address;
}
//Call theName, theAddress assignment

ABEntry::ABEntry():theName(),theAddress(),numTimesConsulted(0)
{
}
//call theName, theAddress constructor (run faster!)

static -> singleton design pattern, initialize and reference only one time.

-------------------------------------------------------------

Rule 5: Know what functions C++ silently writes and calls

class Empty
{
public:
Empty(){...}
Empty(const Empty& rhs){...}
~Empty(){...}
Empty& operator=(const Empty& rhs){...}
};

cannot compile (generate implicate copy assignment) if the class has following conditions:
For the below cases, we must declare the copy constructor and assignment explicitly.
1) Reference
2) Const
3) base class copy assignment = private

-------------------------------------------------------------

Rule 6: Explicitly disallow the use of compiler-generated functions you do not want

1) Mark it as private
2) Do not implement it, declare only.

Private, derived from below class (Boost library - noncopyable class)

class Uncopyable
{
protected:
Uncopyable(){}
~Uncopyable(){}
private:
Uncopyable(const Uncopyable&);
Uncopyable& operator=(const Uncopyable&);
}

class HomeForSale : private Uncopyable
{

}

-------------------------------------------------------------

Rule 7: Declare destructors virtual in polymorphic base classes

If the class is suppose not to be polymorphic, don't declare the class as virtual destructor.

-------------------------------------------------------------

Rule 8: Prevent exceptions from leaving destructor

The exception leave to outside world <- may cause undefined behavior / exit at earlier stage.
solution: explicit declare a function to let the user explicit "close" it.
The user call the "close" function with try{} catch{} case,
Equivalent:
Because the class has given the chance for the user explicit handle the exception, but the user didn't.
It is not the fault made by the class.

class cla
{
private:
//......

bool closed;

void close()
{
//.....
closed = true;
}

~cla::cla()
{
if(!closed)
{
try
{
close();
}
catch()
{
//catch exception, log
}
}
}
};

-------------------------------------------------------------

Rule 9: Never call virtual functions during construction or destruction

-------------------------------------------------------------

Rule 10: Have assignment operators return a reference to *this

because x=y=z=15;
equivalent x=(y=(z=15));

also apply in +=, -=, *=...etc operator.
Widget& operator+=(const Widget& rhs)
{
//....
return *this;
}

Widget& operator=(int rhs)
{
//...
return *this;
}

2013年7月31日星期三

C++ private inheritance

Quote from "http://www.cprogramming.com/tutorial/private.html",


Private inheritance does not model an is-a relationship in the same way that public inheritance does. Instead, private inheritance refers to the idea of being "implemented in terms of a". The key difference is that whereas public inheritance provides a common interface between two classes, private inheritance does not--rather, it makes all of the public functions of the parent class private in the child class. This means that they can be used in order to implement the child class without being accessible to the outside world. 

The syntax for private inheritance is almost exactly the same as for public inheritance:
class obj : private implementationDetailOfObj


This sort of thing might be useful for times when you want to disallow certain parts of a class's functionality. For instance, if you were creating a list of unique elements, you might want to implement it in terms of an STL list, but you wouldn't want to allow anyone to use the normal list add function, which might allow anyone to add non-unique elements to the list. You might think that you could override the method to accomplish the same thing. Unfortunately, this would only work if the method were virtual, and someone could still perform a cast to get around this attempt at preventing the use of the add function. 

Of course, there is often another way to reuse code when your goal is to implement one class in terms of another class: inclusion. The idea of inclusion is that when you want to implement one class in terms of a second, you can often make the second class a private field of the first class and just make the appropriate method calls. This also solves the problem of preventing access to the functions of that class that you don't want to expose as part of your class's public interface (just as private inheritance does). Inclusion is also nice because it is conceptually simple to include multiple classes as members of another. In general, if you can, it is best to favor inclusion over private inheritance because of its simplicity. 

So why would you ever want to use private inheritance? Sometimes it turns out that the class that you wish to implement your own class in terms of relies on overriding virtual functions for its implementation. For instance, you might have a class that provides a framework for a game and virtual functions that are called to draw the player sprites at appropriate locations and times. Unfortunately, to take advantage of this class, you need to overload those functions to build in your own features. You could do this by publicly inheriting the class, but then you expose all of those newly inherited functions as part of your own interface, probably not what you really wanted to do. 

For instance, the following class provides some functionality that we might find useful, but it relies on virtual functions to determine parts of what it does:
class taxAdvisor
{
    public:
    int computeTaxes ()
    {
        // perform lots of fancy math using the getIncome and
        // computeDeductions functions
    }
    virtual int getIncome ();
    virtual computeDeductions ();
};
Any subclass of tax advisor that wishes to change the computations of taxes based on income of deductions would need to override the getIncome and computeDeductions functions. Unfortunately, we can't use inclusion in this case because that wouldn't let us override those functions. We actually need to inherit from taxAdvisor. But if our goal is just to implement a class in terms of taxAdvisor, then private inheritance is the right way to go. (Maybe we don't want getIncome to be public!) 

If you need this kind of functionality, then private inheritance is the only solution to the problem!

Summary

  • Private inheritance models the "is implemented in terms of a" relationship, rather than the is-a relationship that is modeled by public inheritance.
  • Private inheritance results in all public functions of a class being inherited as private functions
  • Private inheritance should be used sparingly, but can be necessary when you need to override a virtual function

class A 
{
public:
    int x;
protected:
    int y;
private:
    int z;
};

class B : public A
{
    // x is public
    // y is protected
    // z is not accessible from B
};

class C : protected A
{
    // x is protected
    // y is protected
    // z is not accessible from C
};

class D : private A
{
    // x is private
    // y is private
    // z is not accessible from D
};

2013年7月30日星期二

Win32 Disassembler - OllyDbg / Windows, Linux or Mac OS X hosted multi-processor disassembler - IDA Pro

OllyDbg

32-bit assembler level analysing debugger for Microsoft® Windows®


IDA Pro

Windows, Linux or Mac OS X hosted multi-processor disassembler

LeakDiag Usage

LeakDiag Usage


Detect and help to analyze memory leak

Default Installation Path: C:\LeakDiag

1) Select Application
2) Select Memory allocators
3) Press [Start]
4) Wait...Press [Log]

Load the symbol file:
Tools > Option > Symbol Search Path



2013年7月28日星期日

BusyBox Default Function List

$ busybox
BusyBox v1.18.0 (2010-12-01 19:10:28 CET) multi-call binary.
Copyright (C) 1998-2009 Erik Andersen, Rob Landley, Denys Vlasenko
and others. Licensed under GPLv2.
See source distribution for full notice.

Usage: busybox [function] [arguments]...
   or: busybox --list[-full]
   or: function [arguments]...

 BusyBox is a multi-call binary that combines many common Unix
 utilities into a single executable.  Most people will create a
 link to busybox for each function they wish to use and BusyBox
 will act like whatever it was invoked as.

Currently defined functions:
 [, [[, acpid, add-shell, addgroup, adduser, adjtimex, ar, arp, arping,
 awk, base64, basename, bbconfig, beep, blkid, blockdev, bootchartd,
 brctl, bunzip2, bzcat, bzip2, cal, cat, catv, chat, chattr, chgrp,
 chmod, chown, chpasswd, chpst, chroot, chrt, chvt, cksum, clear, cmp,
 comm, conspy, cp, cpio, crond, crontab, cryptpw, cttyhack, cut, date,
 dc, dd, deallocvt, delgroup, deluser, depmod, devfsd, devmem, df,
 dhcprelay, diff, dirname, dmesg, dnsd, dnsdomainname, dos2unix, dpkg,
 dpkg-deb, du, dumpkmap, dumpleases, echo, ed, egrep, eject, env,
 envdir, envuidgid, ether-wake, expand, expr, fakeidentd, false, fbset,
 fbsplash, fdflush, fdformat, fdisk, fgconsole, fgrep, find, findfs,
 flash_eraseall, flash_lock, flash_unlock, flashcp, flock, fold, free,
 freeramdisk, fsck, fsck.minix, fsync, ftpd, ftpget, ftpput, fuser,
 getopt, getty, grep, gunzip, gzip, halt, hd, hdparm, head, hexdump,
 hostid, hostname, httpd, hush, hwclock, id, ifconfig, ifdown,
 ifenslave, ifplugd, ifup, inetd, init, inotifyd, insmod, install,
 ionice, iostat, ip, ipaddr, ipcalc, ipcrm, ipcs, iplink, iproute,
 iprule, iptunnel, kbd_mode, kill, killall, killall5, klogd, last,
 length, less, linux32, linux64, linuxrc, ln, loadfont, loadkmap,
 logger, login, logname, logread, losetup, lpd, lpq, lpr, ls, lsattr,
 lsmod, lspci, lsusb, lzcat, lzma, lzop, lzopcat, makedevs, makemime,
 man, md5sum, mdev, mesg, microcom, mkdir, mkdosfs, mke2fs, mkfifo,
 mkfs.ext2, mkfs.minix, mkfs.reiser, mkfs.vfat, mknod, mkpasswd, mkswap,
 mktemp, modinfo, modprobe, more, mount, mountpoint, mpstat, msh, mt,
 mv, nameif, nanddump, nandwrite, nbd-client, nc, netstat, nice, nmeter,
 nohup, nslookup, ntpd, od, openvt, passwd, patch, pgrep, pidof, ping,
 ping6, pipe_progress, pivot_root, pkill, pmap, popmaildir, poweroff,
 powertop, printenv, printf, ps, pscan, pwd, raidautorun, rdate, rdev,
 readahead, readlink, readprofile, realpath, reboot, reformime,
 remove-shell, renice, reset, resize, rev, rfkill, rm, rmdir, rmmod,
 route, rpm, rpm2cpio, rtcwake, run-parts, runlevel, runsv, runsvdir,
 rx, script, scriptreplay, sed, sendmail, seq, setarch, setconsole,
 setfont, setkeycodes, setlogcons, setsid, setuidgid, sh, sha1sum,
 sha256sum, sha512sum, showkey, slattach, sleep, smemcap, softlimit,
 sort, split, start-stop-daemon, stat, strings, stty, su, sulogin, sum,
 sv, svlogd, swapoff, swapon, switch_root, sync, sysctl, syslogd, tac,
 tail, tar, taskset, tcpsvd, tee, telnet, telnetd, test, tftp, tftpd,
 time, timeout, top, touch, tr, traceroute, traceroute6, true, tty,
 ttysize, tunctl, tune2fs, ubiattach, ubidetach, udhcpc, udhcpd, udpsvd,
 umount, uname, uncompress, unexpand, uniq, unix2dos, unlzma, unlzop,
 unxz, unzip, uptime, usleep, uudecode, uuencode, vconfig, vi, vlock,
 volname, wall, watch, watchdog, wc, wget, which, who, whoami, xargs,
 xz, xzcat, yes, zcat, zcip

click here for the command usage manual :)