Friday, November 30, 2018
Understanding Events in C#
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class TransactionEventArgs : EventArgs
{
private int _transactionAmount;
// "Credited": deposit
// "Debited" : withdraw
private string _transactionType;
public TransactionEventArgs(int amt, string type)
{
this._transactionAmount = amt;
this._transactionType = type;
}
public int TranactionAmount
{
get
{
return _transactionAmount;
}
}
public string TranactionType
{
get
{
return _transactionType;
}
}
}
/*like:
public delegate void EventHandler(object sender, EventArgs e);
*/
public delegate void TransactionHandler(object sender, TransactionEventArgs e);
class Account
{
//like:
//public event EventHandler Click;
//
//the TransactionMade event and its TransactionHandler delegate(s)
public event TransactionHandler TransactionMade; // Event Definition
public int BalanceAmount;
public Account(int amount)
{
this.BalanceAmount = amount;
}
//publisher invokes a event
public void Debit(int debitAmount)
{
if (debitAmount < BalanceAmount)
{
BalanceAmount = BalanceAmount - debitAmount;
TransactionEventArgs e = new TransactionEventArgs(debitAmount, "Debited");
OnTransactionMade(e); // Debit transaction made
}
}
public void Credit(int creditAmount)
{
BalanceAmount = BalanceAmount + creditAmount;
TransactionEventArgs e = new TransactionEventArgs(creditAmount, "Credited");
OnTransactionMade(e); // Credit transaction made
}
protected virtual void OnTransactionMade(TransactionEventArgs e)
{
if (TransactionMade != null)
{
TransactionMade(this, e); // Raise the event
}
}
}
class TestMyEvent
{
private static void SendNotification(object sender, TransactionEventArgs e)
{
Console.WriteLine(
"Your Account is {0} for ${1} ",
e.TranactionType,
e.TranactionAmount);
}
private static void Main()
{
Account MyAccount = new Account(10000);
//like: this.button1.Click += new System.EventHandler(this.button1_Click);
//
//note: the += operator of event will subscribe the event append a delegate
MyAccount.TransactionMade += new TransactionHandler(SendNotification);
MyAccount.Credit(500);
Console.WriteLine("Your Current Balance is : " + MyAccount.BalanceAmount);
Console.ReadLine();
}
}
Tuesday, July 3, 2018
_NT_SYMBOL_PATH and extra
.sympath to view current setting
.sympath+ to add path:
.sympath+ C:\Chromium\debug_v8_02\v8\out.gn\ia32.debug\
// .srcpath C:\Chromium\debug_v8_02\v8\src
// bp d8_exe!main
db poi(poi(argv)+4)
00685050 43 3a 5c 43 68 72 6f 6d-69 75 6d 5c 64 65 62 75 C:\Chromium\debu 00685060 67 5f 76 38 5f 30 32 5c-69 6e 73 74 61 6e 63 65 g_v8_02\instance 00685070 30 31 5c 31 2e 6a 73 00-fd fd fd fd ab ab ab ab 01\1.js.........
Tuesday, June 19, 2018
build_and_debug_v8_on_windows
Setting up environment
/*VS2013 Requirements:
- at least 8.5 GB disk space;If your windows has been updated to October 2013, you can delete some not used files in winsxs to free up disk space: apply "Clean up system files" button from windows disk cleanup utility(to run it with system adiminister, view its path through windows task mgr, then right click it and select run as admin).
- for the express installer, select the installer for Windows Desktop instead of Windows(the later can be used to create windows store app).
- To install vs2013 express, I make my win7 genenuine first by input the product key W4TGB-8HFJV-QB794-P6MDG-XWGF6 found in my disk packer and machine sticker
- VS 2013 will use dnet 4.5.1 first, so better remove your old install(to check version of installed dnet, check HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP)
VS2017 Requirements:
- at least 30 GB disk space
Install git(if has no installation in your system)
From https://git-scm.com/downloads download and install git.Install VS /*2015|*/2017(if has no installation in your system)
Depending on the system, may needing to install dnet 4.6 first.Install VS(do not change default install path for VS), making sure the installer has installed Debug Interface Access (DIA) SDK(msdia*.dll), vcvarsall.bat, (and the Universal CRT?).
Install and config depot_tools
V8 uses part of a toolchain named depot_tools for Chromium project, Download depot_tools.zip and extract it(to C:\Chromium\depot_tools), then adds it to PATH. At the same time, add two new env var into your system:DEPOT_TOOLS_WIN_TOOLCHAIN=0 //If you are a non-googler you need to set DEPOT_TOOLS_WIN_TOOLCHAIN=0 GYP_MSVS_VERSION=2017 //windows is not using GN but GYP for Ninja?From a cmd.exe shell, run the command `gclient`, it will install all the bits needed to work with the code, including msysgit and python; After running gclient, open a new command prompt and type "where python" and confirm that python.bat comes ahead of python.exe (adjust PATH to let python.bat being searched first).
Install windows sdk
Windows sdk must be installed at default dir; and Debugging Tools For Windows must be selected(building v8 requires windows sdk, so if you only installed `Debugging Tools For Windows`, remove it)After installing, windbg may be found at following locations:
C:\Program Files (ia32)\Windows Kits // C:\Program Files (x86)\Windows Kits C:\Program Files (ia32)\Microsoft SDKs\Windows Kits
Building and use V8
Get source code
Go into the directory where you want to download the V8 source into and execute the following in your terminal/shell:- cd /d C:\Chromium\debug_v8_02
- fetch v8
Running: 'C:\depot_tools\win_tools-2_7_6_bin\python\bin\python.exe' 'C:\depot_tools\gclient.py' root Running: 'C:\depot_tools\win_tools-2_7_6_bin\python\bin\python.exe' 'C:\depot_tools\gclient.py' config --spec 'solutions = [ { "url": "https://chromium.googlesource.com/v8/v8.git", "managed": False, "name": "v8", "deps_file": "DEPS", "custom_deps": {}, }, ] ' C:\Chromium\depot_tools\win_tools-2_7_6_bin\python\bin\python.exe C:\Chromium\depot_tools\gclient.py sync --with_branch_heads ...
build debug_v8_02
prepare build file for ninja: cd /d C:\Chromium\debug_v8_02\v8 && python tools/dev/v8gen.py ia32.debugmodify config file C:\Chromium\debug_v8_02\v8\out.gn\ia32.debug\args.gn :
#ia32.debug x64.release ... is_debug = true target_cpu = "x86" v8_enable_backtrace = true v8_enable_slow_dchecks = true v8_optimized_debug = false" ninja -C out.gn/ia32.debug " and produce the product d8.
check if v8 works: C:\Chromium\debug_v8_02\v8\out.gn\ia32.debug\d8.exe C:\Chromium\debug_v8_02\instance01\1.js
debug d8:
- windbg with C:\Chromium\debug_v8_02\v8\out.gn\ia32.debug\d8.exe C:\Chromium\debug_v8_02\instance01\1.js
- set symbols: .sympath+ C:\Chromium\debug_v8_02\v8\out.gn\ia32.debug\
- set srcpath: .srcpath C:\Chromium\debug_v8_02\v8\src
- bp d8_exe!main
- let windbg run and break
- db poi(poi(argv))
0068501c 43 3a 5c 43 68 72 6f 6d-69 75 6d 5c 64 65 62 75 C:\Chromium\debu 0068502c 67 5f 76 38 5f 30 32 5c-76 38 5c 6f 75 74 2e 67 g_v8_02\v8\out.g 0068503c 6e 5c 69 61 33 32 2e 64-65 62 75 67 5c 64 38 2e n\ia32.debug\d8.
- db poi(poi(argv)+4)
00685050 43 3a 5c 43 68 72 6f 6d-69 75 6d 5c 64 65 62 75 C:\Chromium\debu 00685060 67 5f 76 38 5f 30 32 5c-69 6e 73 74 61 6e 63 65 g_v8_02\instance 00685070 30 31 5c 31 2e 6a 73 00-fd fd fd fd ab ab ab ab 01\1.js.........
Friday, June 15, 2018
googletest
Locate GTEST_ROOT
after you (git) clone google test from master, your dir contains both google test and google mock. googletest is google's suggestion.
GTEST_ROOT may looks like ..\googletest-master\googletest
Locate gtest.sln or makefile to work on
googletest provides build files for some popular build systems: msvc/ for Visual Studio, xcode/ for Mac Xcode, make/ for GNU make, codegear/ for Borland C++ Builder, and the autotools script (deprecated) and CMakeLists.txt for CMake (recommended). In my case, it's under msvc\2010 .
test a project or build target
Created ConsoleApplication1 under the sln, its dir is msvc\ConsoleApplication1.
copy code for the target's int main() func form the project gtest_main.
config the tgt's runtime to "Multi-threaded Debug (/MTd)" //same as gtest
add dependency to gtest(note: in vs2017, add it from project properties menu), and add C:\Temp\Tasks\googletest\test2\googletest-master\googletest\msvc\2010\gtest\Win32-Debug as additional lib dir.
add testing code:
TEST(dummy_case, dummy_test) { //use EXPECT_* when you want the test to continue to reveal more errors after the assertion failure, //and use ASSERT_* when continuing after failure doesn't make sense. EXPECT_EQ(3, 3); ASSERT_EQ(3, 3); }
For a c++ class tester
we can create c++ class tester(fixture) public on ::testing::Test; the fixture's tests can use TEST_F.
For each test defined with TEST_F(cls_name,test_name), Google Test will:
Create a fresh test fixture named cls_name at runtime Immediately initialize it via SetUp() Run the test Clean up by calling TearDown() Delete the test fixture. Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests.
further readings
https://github.com/google/googletest/blob/master/googletest/docs/primer.md
Tuesday, May 15, 2018
Windows_Protocols__2017_Dec_01_cfb
2 Structures
2.1 Compound File Sector Numbers and Types
Each sector, except for the header, is identified by a nonnegative, 32-bit sector number. The following sector numbers above 0xFFFFFFFA are reserved and MUST NOT be used to identify the location of a sector in a compound file.
Followings are definitions of SectIDs:
#define SID_MAXREG (0xfffffffa) #define SID_FUTURE ((SectID)(SID_MAXREG + 1)) #define SID_MSAT_SECTOR ((SectID)(SID_MAXREG + 2)) #define SID_SAT_SECTOR ((SectID)(SID_MAXREG + 3)) #define SID_END_OF_CHAIN ((SectID)(SID_MAXREG + 4)) #define SID_UNUSED_SECTOR ((SectID)(SID_MAXREG + 5)) /* [MS-CFB] or [MS-CFB] errata 2.9 Compound File Size Limits: ...4,096 bytes/sector x MAXREGSECT (0xFFFFFFFA) sectors... so SID_MAXREG is also a special ID. */ #define SID_IS_SPECIAL(sid) ((SectID)(sid) >= SID_MAXREG)
The following list contains the types of sectors that are allowed in a compound file:
Header: A single sector with fields that are needed to read the other structures of the compound file.For version 4 compound files, the header size (512 bytes) is less than the sector size (4,096 bytes), so the remaining part of the header (3,584 bytes) MUST be filled with all zeroes. We can take head_size as equals with sect_size. FAT: Sector Allocation Table(OpenOffice: SAT). DIFAT: Used to locate FAT sectors in the compound file(OpenOffice: MSAT). Mini FAT: FAT for short streams(OpenOffice: SSAT). Directory: User-defined Data: Unallocated Free: Range Lock:A single sector that is used to manage concurrent access to the compound file. This sector must cover file offset 0x7FFFFFFF(OpenOffice:Not used).
2.6 Compound File Directory Sectors
2.6.1 Compound File Directory Entry
The valid values for a stream ID, which are used in the Child ID, Right Sibling ID, and Left Sibling ID fields, are 0 through MAXREGSID (excluding).Directory Entry Name (64 bytes): storage and stream names are limited to 32 UTF-16 code points, including the terminating null character. When locating an object in the compound file except for the root storage, the directory entry name is compared by using a special case-insensitive uppercase mapping, described in Red-Black Tree. The following characters are illegal and MUST NOT be part of the name: '/', '\', ':', '!'. Directory Entry Name Length (2 bytes): This field MUST match the length of the Directory Entry Name Unicode string in bytes. The length MUST be a multiple of 2 and include the terminating null character in the count. A secured parser shall not use this field. Object Type (offset 66, 0x42): This field MUST be 0x00, 0x01, 0x02, or 0x05, depending on the actual type of object. All other values are not valid: 0 for Unknown or unallocated; 1 for Storage Object; 2 for Stream Object; 5 for Root Storage Object. Color Flag (offset 67, 0x43): This field MUST be 0x00 (red) or 0x01 (black). Left Sibling ID(offset 68, 0x44): This field contains the stream ID of the left sibling. If there is no left sibling, the field MUST be set to NOSTREAM (0xFFFFFFFF). Right Sibling ID (offset 72, 0x48): Child ID (offset 76, 0x4C): This field contains the stream ID of a child object. If there is no child object, the field MUST be set to NOSTREAM (0xFFFFFFFF). CLSID (offset 80, 0x50): This field contains an object class GUID(can be used as a parameter to start applications.), if this entry is a storage or root storage. If no object class GUID is set on this object, the field MUST be set to all zeroes. State Bits (offset 96, 0x60): This field contains the user-defined flags if this entry is a storage object or root storage object. If no state bits are set on the object, this field MUST be set to all zeroes. Creation Time(8 bytes):Modified Time (8 bytes): Starting Sector Location (offset 116, 0x74): This field contains the first sector location if this is a stream object. For a root storage object, this field MUST contain the first sector of the mini stream, if the mini stream exists. Stream Size (8 bytes): Streams whose size is less than the Cutoff value exist in the mini stream. Parsers must trust Stream Size to decide it's mini or standard stream, while maintains a size telling the size figured out through sector chain of this stream.
2.6.4 Red-Black Tree
According rbtree, followings are true:The root storage object MUST always be black. wo consecutive nodes MUST NOT both be red.(if one node is red, it's left/right must be black) The left sibling MUST always be less than the right sibling. (root object has const name, its name don't compare; root object has no left and right)
This sorting relationship is defined as follows:
A node that has a shorter name is less than a node that has a longer name. For each UTF-16 code point, convert to uppercase by using the Unicode Default Case Conversion Algorithm
Wednesday, May 2, 2018
review_RRSP_deduction_of_TaxYear2014
How to check if your RRSP contributions deducted from your income? This article discuss it with example of tax year 2014.
As we know, RRSP deduction is MIN(deduction_limit, contributions_of_the_year), normally, deduction_limit is larger than contributions_of_the_year, so we simply query from 2014 Assessment's Schedule 7 at line 245 which is added from:
- your PRPP contributions made from March 4, 2014, to December 31, 2014
- your PRPP contributions made from January 1, 2015, to March 2, 2015
From 2014 Notice of Assessment, you will see `Deductions from total income` is the same as line 245. If you decide that `Deductions from total income` and line 245 happen to be the same. We can get back to 2014 Assessment's RRSP deduction at line 208 and recheck it.
Saturday, April 21, 2018
Excel数组公式

我们想对上面选择区域进行求和,发现求和结果竟然是0, 这显然不对;
调查到不对的原因是选择区域是文本,对这些区域用右键菜单转换成数值格式,发现左上角还是箭头,说明转化不成功;
网上有一些教程说可以用别的方式批量转文本为数值,比如用数据菜单中的分列功能, 我没有尝试,现在用Excel数组公式来解决这个问题:
1. 选中用来存sum的结果的单元格;
2. 生成公式模版如下
3. 在公式编辑栏中改公式为
=SUM(VALUE(起始单元格:N138))
4. 按CTRL+SHIFT+ENTER结束, 注意这会告诉EXCEL这是有数组为参数的公式(按完快捷键它会显示为下面的形式:
=SUM(VALUE(N123:N138))
Thursday, April 19, 2018
config apache: allow PHP code in HTML files
Thursday, April 12, 2018
SublimeSSH
This tutorial will teach you how to set up Sublime Text to edit files in ssh server.
Config Sublime
1. Open Sublime Text and hit “ctrl + `”. This will show console. Copy and paste the Python code from packagecontrol.io or as following
import urllib.request,os,hashlib; h = '6f4c264a24d933ce70df5dedcf1dcaee' + 'ebe013ee18cced0ef93d5f746d80ef60'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)into the console terminal and hit enter.
2. Hit “ctrl + shift + p” to bring up the package manager. Search for "Install Package" and select it.
3. Check we are in installing package context and search and hit for rsub (a client to connect to the proxy app at ssh server). on succ, will print:
[rsub] Server running on localhost:52698
If already installed rsub, everytime Sublime starts, this message showed.
Installing ssh client
I suggest installing Xshell ( select English when decide language ).
Following is a saved login config:
Login to and config ssh server
Install rsub:
sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate sudo chmod a+x /usr/local/bin/rsub
Test
Consider you are in /var/www/html of your ssh server and want send file jsdo.html to Sublime:
sudo rsub jsdo.html
Use Sublime to edit this file and save, at ssh server, you will see the file changed after saved from Sublime.
Enjoy!
SSH Tunnel
There are two ways to create an SSH tunnel, local and remote port forwarding (there's also dynamic forwarding, but we won't cover that here).
local port forwarding
forwarding to remote server
Imagine you’re on a private network which doesn’t allow connections to a specific server. Let’s say you’re at work and imgur.com is being blocked. To get around this we can create a tunnel through ssh server which isn’t on our network and thus can access Imgur.
$ ssh -L 9000:imgur.com:80 user@example.com //local port is targeting at imgur.com's port 80 with help of ssh server user@example.com .
Now open your browser and go to http://localhost:9000 , nobody is going to see what sites you’re visiting, they’ll only see an SSH connection to your server.
forwarding to ssh server
ssh -L 9000:localhost:5432 user@example.com
For here, the tunnel is localhost:9000 and ssh_server:5432; for easy maintain, local port and ssh port can be the same. the ssh_server can accept multiple connections at same port.
Remote port forwarding
Say that you’re developing a Rails application on your local machine, and you’d like to show it to a friend. Unfortunately your ISP didn’t provide you with a public IP address, so it’s not possible to connect to your machine directly from the internet.
Sometimes this can be solved by configuring NAT (Network Address Translation) on your router, but this doesn’t always work, and it requires you to change the configuration on your router, which isn’t always desirable. This solution also doesn’t work when you don’t have admin access on your network.
To fix this problem you need to have another computer, it can be any server on the internet or your company We’ll tell SSH to make a tunnel that opens up a new port on the server, and connects it to a port on your machine:
$ ssh -R 9000:localhost:3000 user@example.comThe syntax here is very similar to local port forwarding, with a single change of -L for -R. First you need to specify the port on which th remote server will listen, which in this case is 9000, and next follows localhost for your local machine, and the local port, which in this case is 3000.
There is one more thing you need to do to enable this. SSH doesn’t by default allow remote hosts to forwarded ports. To enable this open /etc/ssh/sshd_config and add the following line somewhere in that config file.
GatewayPorts yes
Make sure you add it only once!
$ sudo vim /etc/ssh/sshd_config
And restart SSH
$ sudo service ssh restart
For more info, refer to https://blog.trackets.com/2014/05/17/ssh-tunnel-local-and-remote-port-forwarding-explained-with-examples.html
Sunday, April 8, 2018
schwab
ESPP
A ESPP invest period is often 6 months, each month an amount is invested.
When the company buys the shares for you, you do not owe any taxes. You are exercising your rights under the ESPP. You have bought some stock. So far so good.
When you sell the stock, the discount that you received when you bought the stock is generally considered additional compensation to you, so you have to pay taxes on it as regular income.
If you hold the stock for less than a year before you sell it, any gains will be considered compensation and taxed as such. If you hold the shares for more than one year, any profit will be taxed at the usually lower capital gains rate.
For me, espp shares are often sold Feb or Aug after the 15th day.
Stock options
http://eac.schwab.com -> Accounts -> History -> Equity Awards website -> My Equity Awards -> History and Statements -> Date Range = All:
sell 205 ESPP shares
- Subscription: Date = 08/15/2017; FMV = $36.81
- Purchase: Date = 02/14/2014; FMV = 48.38; Price = MIN(Subscription FMV,Purchase FMV) * 0.85 = 31.2885
- Sale: Date = 02/20/2018; Price = $48.95
- capital gain = (48.38 - 31.2885) * 205 = 3503.76 USD = 3503.76 * 1.2562 cad = 4401.42 cad
- Taxes are deducted by two pay rolls's ESP-ER(02/28/2018 and 03/15/2018), each time with gain 2200.71
- My personal fed-tax rate is 26%, my personal prov-tax rate is 14.7%: 2200.71 * 0.407 = 895.69.
- As Sale Price, 48.95, is not equal with 48.38, so should further report tax gain when file tax.
sell 196 OPTIONs
- Award Names : 00002066 00003118
- Shares: 26 170
- Award Price: $3.735 $8.43
- Sale Price: $24.191
- Sale Date: 07/23/2014
- Award Date: 01/28/2009; 02/10/2010
- Exercise Cost = 3.735 * 26 + 8.43 * 170 = 97.11 + 1433.1 = 1530.21
- Taxes: 894.34
- Gross Proceeds: 196 * 24.191 - possible commissions and fees = 4741.436 - 9.046 = 4,732.39
- assume capital gain = 4,732.39 - 1530.21 = 3202.18, taxable gains = 3202.18 * 1/2 = 1601.09
- //taxable gains is 50% if span years.
- then tax rate = 894.34 / 1601.09 = 55.9%
- Net Proceeds = 2,307.84 = Gross Proceeds - Taxes - Exercise Cost = 4,732.39 - 1530.21 - 894.34
RSU
An example of an RSU grant is the easiest way to understand the concept. Let's say Sue works for ABC Corp and was awarded 300 RSUs on May 1, 2011.
50 award will vest every 6 months. Sue's first batch of 50 units of restricted stock vested on November 1, 2011. ABC was trading at $10 and Sue's employer sold 23 shares(46%) and remitted the withholding tax to CRA. Sue's second batch of 50 units of restricted stock vested on May 1, 2012. ABC was trading at $12 and Sue's employer again sold 23 shares and remitted the withholding tax to CRA. In both cases, her employer included $500 and $600 in employment income and $230 and $276 in income tax deducted in Sue's T4 for 2011 and 2012 respectively(so sue pay income tax for $270 and $324, for year 2011 and 2012).
On May 15, 2012, ABC hit $15 and Sue sold the 54 shares of ABC Corp that she holds. Sue's adjusted cost base is $11 (27 shares acquired at $10 and 27 shares acquired at $12). Since she sold for $15, her capital gains are $216, which she would declare when filing her 2012 tax return in Schedule 3, if no deduction from paychecks | payrolls.
RSU is too complex for tax, later never consider RSU.
Tuesday, March 27, 2018
An example of MBR
[511-512](1fe~1ff): 55 AA
[447-510] 1BE - 1FD : partition table
partition 1(0x0):
.bt0 = 0x80 = Active
/* .bt1 = disk_hdr_idx = 01
.bt2&0x3f = sector_id = 01
((.bt2&0xc0) >> 6) + (.bt3 << 2) = cylinder_idx = 0
.bt4: file system id( NTFS = 0x07 )
.dw8: sector_addr = 0x38// byte_addr = 0x7000
partition 2(0x1):
.bt0 = 0 = not Active/*
disk_hdr_idx = 0
sector_id = 1
cylinder_idx = 1023*/
file system id = 0f = extend partition
.dw8: 42911400 // byte_addr = 42911400 * 512 = 0x51D8D5000 ,
//extend partition can have its own partition table, it's 0x51D8D51be here
//here we only have one logic partition inside, it's D:
D.Active = false
D.byte_addr = 0x7000
//byte_addr is relative, the abs byte_addr is 0x51D8Dc000, at this addr we can find the (logic) partition's boot record
Tuesday, March 13, 2018
evaluation of VMAttack IDA plugin
My evaluation for this plugin is: it's too young but promising.
I firstly introduce the plugin, then evaluate it from two aspects: Automated and Manual Analysis.
Introduction
VMAttack is an IDA plugin which generates and analyses trace log of PE. If trace is not validly produced, the plugin is useless.
Trace generation is automatic and upon completion it will produce a success notification in IDAs output window.
Traversed paths will be colored in a shade of blue, where a darker shade represents a higher number of traversals. We can get a global distribution of traced code with a glance.
Initially it shows system and customer calls and args, this is useful when the PE has explicit function boundaries and give gross view. VMAttack can STEP over system funcs while extract args, which save sapce for trace.
As the best way to understand this plugin is to practice it, so I also collected ALL the tools and writed installer( install.bat ) for praticing.
The demo samps include the obfuscated binary and source binary of an add function:
addvm_3AE2BABAA4920BEF3E466F34B0075FFB.exe addvm_B4E34E39CFDD13E65D070E9FB9717620.vmp.exe
They are available at https://github.com/anatolikalysch/VMAttack/tree/master/Example/addvmp . In the team discuss, I send an email titled as 'decode vmprotect is possible?', that email tell constuction of that vmp sample detailed, debug it with my mimic program, then practice VMAttack after perform install.bat. by this way it's easy to understand this plugin, in this way, we can better evaluate it.
Automated Analysis
Automated Analysis extract useful informations from the trace log automatically or semi-automatically. It includes Input / Output Analysis, Clustering Analysis, Grading Snalysis, Dynamic Trace Optimization, Static deobfuscate.
Input / Output Analysis
The input/output analysis could provide leads as to how the input arguments of the VM function are used and whether there is a connection between function input and function output.
evaluation: for realworld samples, connection between function input and output can be exposed, but not obviously, not very clear.
Clustering Analysis
If a group of insts executed more than one time, they may be taken as cluster. For example, if Cluster Heuristic Threshold set as 3, then if an address is encountered more than twice, it's taken as start of a cluster.
evaluation:Clustering is a good feature, it can folder and reduce trace by a lot, especially Greedy Clustering option is set. VMAttack can quickly remove unnecessary clusters. It can also rollback wrongly removed clusters. If basic block detection was not deactivated in the settings, the clusters themselves are additionally subdivided into basic blocks.The basic block description is a good summary, further more, instructions whose computations are simply overridden are not displayed, which is good feature of in-block deobfuscation.
Grading Analysis
Each inst, block of insts, cluster of insts has different importance. The grade of an inst is affected by Memory usage Importance, Clustering Importance, Input/Output Importance, and so on.
At the end of the grading analysis the now graded trace will be presented in the grading viewer. The trace can now be filtered either by double clicking a grade or via context menu where the user will be prompted to input the grade threshold to display.
evaluation:Clustering Analysis is useful. For example, if you decide Input/Output Analysis is very very important, then inst having largest grade should be the inst do the add op on two adders.
Dynamic Trace Optimization
Dynamic Trace Optimizations which make the trace easier to read.
evaluation:Foldering constants, Folding not used operand are good feature of deobfuscations.
Static deobfuscate
The static deobfuscate function tries to statically determine the instructions that will be executed by the byte code in the provided virtual machine function. The semi-automatic version of this analysis tries to determine all necessary values(later will introduce the values) automatically.
evaluation:refer to the Manual Analysis version of Static deobfuscate for the evaluation.
Manual Analysis
most Manual Analysis features are depending on following VM Context model:
- Code Start - the byte code start, vm_insts, exactly vm_insts_start
- Code End - the byte code end, vm_insts_end
- VM Addr - the start address of the virtual machine function(Protect Func, for short, pf);
- Base Addr - the base address of the jump table(the dispatch table, or , insts_engine), for vmp:
.vmp0:00404339 8A 06 mov al, [esi] .vmp0:0040433B 0F B6 C0 movzx eax, al ; op code .vmp0:0040433E 83 C6 01 add esi, 1 .vmp0:00404341 FF 24 85 9C 43 40 00 jmp dword ptr ds:inst_engines[eax*4]
There are three ways to decide VM Context:
- by the Settings menu entry
- by Manual_Analysis->VM_Context's 'find statically' or 'find dynamically' entry.
Following are so called Manual Analysis features:
- Find VM Function(Protect Func, pf) Input Parameter, the plugin will print "BABE5 , OFFSET WORD_40489A , AFFE1 “, BABE5 and AFFE1 are passed from Protected Func(pdf), WORD_40489A are vm_insts.
evaluation: useful - Find VM Function Output Parameter, for the demo sample addvmp:
.text:0040102E ; .text:00401000 .text:0040102E ; .text:00401000 55 push ebp .text:0040102E ; .text:00401001 89 E5 mov ebp, esp .text:0040102E ; .text:00401003 8B 55 08 mov edx, [ebp+arg_0] .text:0040102E ; .text:00401006 8B 45 0C mov eax, [ebp+arg_4] .text:0040102E ; .text:00401009 01 D0 add eax, edx .text:0040102E ; .text:0040100B 5D pop ebp .text:0040102E ; .text:0040100C C3 retn edi:0 eax:16ABC6 //affected ebp:28FF88 esp:28FF60 edx:AFFE1 //affected ebx:7EFDE000 esi:0 ecx:76728E8A
evaluation: very useful - Find Virtual Reg to Reg mapping, for the demo sample addvmp:
.vmp0:0040432C 89 E5 mov ebp, esp ; vms_top .vmp0:0040432E 81 EC C0 00 00 00 sub esp, 0C0h ; vmd , vm data, virtual registers edi:28FF3C eax:28FF58 ebp:28FF4C edx:28FF50 ebx:28FF44 esi:28FF48 ecx:28FF54
evaluation: not checked, I will not trust this feature - Follow Virtual Register: This provides a manual interface to the register tracking functionality.
evaluation: not useful, will not use this feature - The address count reads in a trace and returns in IDAs output window the ratio: (Address (disasm): frequency of occurrence)
evaluation: not useful; except when used as counter of condition breakpoint
Except for previous features, the plugin provide an "Deobfuscate from..." menu, it seems it try to deobfuscate vm byte code, but I believe this feature is not realized.
decode_vmprotect_blog
It may sound weird that I say decoding vmprotect instead of emulating it. Considering a packer as simple as UPX, we take it as archiver and decompress it; well, SOMETIMES, for vmprotect samples, decoding is also an option.
Last week I was asked to give an evaluation of IDA plugin VMAttack( https://github.com/anatolikalysch/VMAttack ), under this project there is a vmprotect sample addvm.vmp (md5 = B4E34E39CFDD13E65D070E9FB9717620 ); by analysing it, I found decoding vmprotect sample is possible when:
- The protector is weakly obfuscating the sample.
- can find ProtectedFunc(s).
- can find ProtectFunc(s)
With condition 1, WE can easily find ProtectedFunc(s) and ProtectFunc(s). After found ProtectFunc, vm inst stubs can also be found, group of vm insts then can be decoded and restored one by one to its ProtectedFunc( note: ProtectedFunc is inplaced protected ).
fundamentals of vmprotect
There are researchers in the internet researching vmprotect, by following them, one may become a vmprotecter, or we have option to analyse it ourself.
If you have analysed vmprotect, or you wanna follow internet researchers, simply skip this section.
Given a program, vmprotect can protect many funcs|slices of the code. For here, I am assuming there is only one ProtectedFunc, for short, pdf:
.text:0040102E ; .text:00401000
.text:0040102E ; .text:00401000 55 push ebp
.text:0040102E ; .text:00401001 89 E5 mov ebp, esp
.text:0040102E ; .text:00401003 8B 55 08 mov edx, [ebp+arg_0]
.text:0040102E ; .text:00401006 8B 45 0C mov eax, [ebp+arg_4]
.text:0040102E ; .text:00401009 01 D0 add eax, edx
.text:0040102E ; .text:0040100B 5D pop ebp
.text:0040102E ; .text:0040100C C3 retn
.text:0040102E ; .text:0040100C sub_401000 endp
protection is performed in an inplace-hack way. inplace-hack begins with an inline hook which hook to protect func caller(pfc). the values of changed remain bytes(here, 8 bytes) are explained by ProtectFunc (for short, pf):
.text:00401000 E9 F2 38 00 00 jmp pfc
.text:00401005 00 00 00 00 pdf_remains dd 0
.text:00401009 4F 0D 1D db 4Fh, 0Dh, 1Dh
.text:0040100C 2E db 2Eh
pfc simply push vm insts and call pf:
004048F7 pfc:
.vmp0:004048F7 68 9A 48 40 00 push offset vm_insts
.vmp0:004048FC E8 13 FA FF FF call ProtectFunc
.vmp0:004048FC ; ---------------------------------------------------------------------------
.vmp0:00404901
pf firstly accept CPU registers(if you research into the pf, you found it's not saving them, but accepting them, by push then pop to data slots), then set stack, data, then run vm insts one by one:
.vmp0:00404314 ProtectFunc proc near
.vmp0:00404314 arg0_insts_at_40489A= dword ptr 4
.vmp0:00404314 50 push eax
.vmp0:00404315 51 push ecx
.vmp0:00404316 52 push edx
.vmp0:00404317 55 push ebp
.vmp0:00404318 56 push esi
.vmp0:00404319 53 push ebx
.vmp0:0040431A 9C pushf
.vmp0:0040431B 57 push edi ;
.vmp0:0040431C 57 push edi
.vmp0:0040431D FF 35 05 10 40 00 push pdf_remains
.vmp0:00404323 68 00 00 00 00 push 0 ; next inst(here is the first) offset, some said the 0 here will be imagebase fixup, it's reasonable but I am not sure.
.vmp0:00404328 8B 74 24 30 mov esi, [esp+2Ch+arg0_insts_at_40489A] ; insts
.vmp0:0040432C 89 E5 mov ebp, esp ; vms_top
.vmp0:0040432E 81 EC C0 00 00 00 sub esp, 0C0h ; vmd num of bytes
.vmp0:00404334 89 E7 mov edi, esp ; vmd
.vmp0:00404336
.vmp0:00404336 loc404336_inst_to_next:
.vmp0:00404336 03 75 00 add esi, [ebp+0]
.vmp0:00404339
.vmp0:00404339 loc404339_query_inst_engine:
.vmp0:00404339 8A 06 mov al, [esi]
.vmp0:0040433B 0F B6 C0 movzx eax, al ; op code
.vmp0:0040433E 83 C6 01 add esi, 1
.vmp0:00404341 FF 24 85 9C 43 40 00 jmp dword ptr ds:inst_engines[eax*4]
...
protected inst 0(push ebp):
vm inst 0
vm inst 1
...
vm inst i
protected inst 1(mov ebp, esp):
vm inst i+1
vm inst i+2
...
details of vmprotect
I have created minic source code to tell the details of vmprotect, the minic is not full support of all vm insts, but made small and suitable for this sample. the mimic contains following modules:
- vm stack
- vm data
- vm insts
- vm context
- vmp
Also, a windbg trace log will be attached, debugging the source code and refering the windbg log, one may understand vmprotect better.
AT LAST , VERY IMPORTANT, IF VM INSTS INSIDE FOLLOWING MIMIC SRCS CAN BE IDENTIFIED, WE CAN THEN FULLY DECODE THIS PDF(PROTECTED FUNC):
pdf_401000_push_ebp();
pdf_401001_mov_ebp_esp();
pdf_401003_mov_edx_adder0();
pdf_401006_mov_eax_adder1();
pdf_401009_add_eax_edx();
pdf_40100B_pop_ebp();
pdf_40100C_ret();
Thanks.
Sunday, March 4, 2018
tuition_education__and__textbook_amounts
tuition here is regarding job training.
The education amount was a tax credit based on the number of months you spent studying full-time or part-time in a qualifying educational program during the tax year.
If you were eligible for the education amount, you were also eligible for the textbook credit.
residency_status
When preparing your tax return, you may need to refer to other guides, or complete some schedules and other forms that have more detailed information. To get any other documents that you need, go to Previous-year forms and publications listed by number and by title: https://www.canada.ca/en/revenue-agency/services/forms-publications/previous-year-forms-publications/forms-publications-listed-reference-number.html
this document are extracting info mainly from tax package for BC :
https://www.canada.ca/en/revenue-agency/services/forms-publications/previous-year-forms-publications/archived-previous-year-tax-packages/archived-general-income-tax-benefit-package-2013/archived-british-columbia-general-income-tax-benefit-packages-2013.html :
- General Income Tax and Benefit Guide - 2013
- Schedule 1 - Federal Tax
- Schedule 2 - Federal Amounts Transferred From Your Spouse or Common-law Partner
- Schedule 3 - Capital Gains (or Losses) in 2013(For us, we do not invest, or buy sell stocks this year)
- Schedule 5 - Amounts for Spouse or Common-Law Partner and Dependants
- Schedule 6 - Working Income Tax Benefit - British Columbia
-
- Provincial Worksheet
- Form BC428 - British Columbia Tax
- Form BC479 - British Columbia Credits
- Schedule BC(S2) - Provincial Amounts Transferred From Your Spouse or Common-Law Partner
view_stock_option_history
from www.schwab-global.com , found a link tagged as "log in", input user id then entered the logged-in state.
from the left top drop-list, select Equity Awards Center.
At Equity Awards Center, select My Equity Awards's History_and_Statements tab.
Monday, February 19, 2018
install_lamp
install apache2
apt-get update apt-get install -y apache2 open web brower: http://172.17.71.216 //if can't open this page, use `service apache2 restart` then retry
install php
- apt-get install -y php5 libapache2-mod-php5
- vim /var/www/html/test.php with
<?php phpinfo(); ?>
- test http://172.17.71.216/test.php
maintain apache
clear log
service apache2 stop rm -rf /var/log/apache2/* touch error.log && touch access.log && touch other_vhosts_access.log chmod 777 error.log && chmod 777 access.log && chmod 777 other_vhosts_access.log service apache2 start
install_or_upgrade_npm
ls -l | grep "^d*"| wc -l //count for folders
curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash -
apt-get install nodejs
//nodejs is the newest!
ls -l | grep "^d*"| wc -l //count for folders
npm -v
//5.6.0
/*
if npm is not the version you want, use
npm install npm@latest -g // npm install npm@ver -g
///updated to 5.6.0
*/
int your prj folder:
npm init
name:
(default)
ver:use the smallest and let it update
1.0.0
description:
npm init javascript-obfuscator, zxxu
git repository:
https://github.com/javascript-obfuscator/javascript-obfuscator
//If you want to depend on the package from your own module, using something like Node.js' require, then you want to install locally. This is npm install's default behavior.
//npm install --save-dev javascript-obfuscator
npm install javascript-obfuscator
FortigatePortForwarding
//refer http://cookbook.fortinet.com/using-virtual-ips-configure-port-forwarding-54/
Go to Policy & Objects > Virtual IPs > Create New > Virtual IP:
name = js_deobfu_statistics
External IP Address/Range = 172.17.71.216
Mapped IP Address/Range = 192.168.1.12
Enable Port Forwarding and add a VIP for TCP port 80
Adding VIPs to a VIP group//as we may add 21, 22 mappings
Go to Policy & Objects > Virtual IPs > Create New > Virtual IP Group.
in this example, webservers group. Under Members, include all VIPs(js_deobfu_statistics) previously created.
Go to Policy and Objects . IPv4 Policy and create a security policy allowing access to a server behind the firewall:
name = PortForwarding
Outgoing Interface = internal
Source = all
Destination Address = webservers
NAT = disabled // so that the server sees the original source addresses of the packets it receives.
Wednesday, February 7, 2018
replace all occurs of "PRJ_DIR" into "PRJ_PATH"
replace all occurs of "PRJ_DIR" into "PRJ_PATH"
grep
-r, --recursive like --directories=recurse
-l, --files-with-matches print only names of FILEs containing matches
grep -rl PRJ_DIR ./ | xargs sed -i 's/PRJ_DIR/PRJ_PATH/g'
Monday, January 29, 2018
ECMA262_2017_ch5
5Notational Conventions
5.1Grammars
5.1.1Context-Free Grammars
A context-free grammar consists of a number of productions. Each production has an abstract symbol called a nonterminal as its left-hand side, and a sequence of zero or more nonterminal and terminal symbols as its right-hand side.
A chain production is a production that has exactly one nonterminal symbol on its right-hand side along with zero or more terminal symbols.
5.1.2The Lexical and RegExp Grammars
A lexical grammar defines a set of productions, starting from the goal symbol InputElementDiv, InputElementTemplateTail, or InputElementRegExp, or InputElementRegExpOrTemplateTail.
A example of InputElementRegExp can be /a_Pattern/flags , refer to A.8 for Pattern, the RegExp Grammars.
InputElementDiv can be spaces, comments, and so on.
An example of InputElementRegExpOrTemplateTail can be
`hello,${expr },it's funny, I like python's """multi_line_str"""`
In the example of InputElementRegExpOrTemplateTail, "}...`" is a InputElementTemplateTail, which terminates this goal symbol.
Input elements other than white space, line terminators, and comments form the terminal symbols for the syntactic grammar for ECMAScript and are called ECMAScript tokens.
A MultiLineComment is simply discarded if it contains no line terminator; but if a MultiLineComment contains one or more line terminators, then it is replaced by a single line terminator, which becomes part of the stream of input elements for the syntactic grammar. Simple white space and single-line comments are discarded and do not appear in the stream of input elements.
Productions of the lexical and RegExp grammars are distinguished by having two colons “::” as separating punctuation.
5.1.3The Numeric String Grammar
Another grammar is used for translating Strings into numeric values. This grammar is similar to the part of the lexical grammar having to do with numeric literals. When found strings literals( begins with '"' or "'" ), the parser enters Numeric String parsing state( when found /a_Pattern/, ecma parser enters RegExp parsing state).
Productions of the numeric string grammar are distinguished by having three colons “:::” as punctuation.
5.1.4The Syntactic Grammar
The syntactic grammar for ECMAScript is given in clauses 11(Lexical Grammar), 12, 13, 14(Functions and Classes), and 15(Scripts and Modules). This grammar has ECMAScript tokens defined by the lexical grammar as its terminal symbols. It defines a set of productions, starting from two alternative goal symbols Script and Module, that describe how sequences of tokens form syntactically correct independent components of ECMAScript programs.
When a stream of code points is to be parsed as an ECMAScript Script or Module, it is first converted to a stream of input elements by repeated application of the lexical grammar; this stream of input elements is then parsed by a single application of the syntactic grammar. The input stream is syntactically in error if the tokens in the stream of input elements cannot be parsed as a single instance of the goal nonterminal (Script or Module), with no tokens left over.
When a parse is successful, it constructs a parse tree, a rooted tree structure in which each node is a Parse Node. Each Parse Node is an instance of a symbol in the grammar; it represents a span of the source text that can be derived from that symbol. The root node of the parse tree, representing the whole of the source text, is an instance of the parser's goal symbol. When a Parse Node is an instance of a nonterminal, it is also an instance of some production that has that nonterminal as its left-hand side. Moreover, it has zero or more children, one for each symbol on the production's right-hand side: each child is a Parse Node that is an instance of the corresponding symbol.
Productions of the syntactic grammar are distinguished by having just one colon “:” as punctuation.
5.1.5Grammar Notation
A production may be parameterized by a subscripted annotation of the form “[parameters]”
StatementList[AliasSuffix1, AliasSuffix2]: ReturnStatement ExpressionStatement is an abbreviation for: StatementList: ReturnStatement ExpressionStatement StatementList_AliasSuffix1: ReturnStatement ExpressionStatement StatementList_AliasSuffix2: ReturnStatement ExpressionStatement StatementList_AliasSuffix1_AliasSuffix2: ReturnStatement ExpressionStatement
References to nonterminals on the right-hand side of a production can also be parameterized. For example:
StatementList: ReturnStatement ExpressionStatement[+In] is equivalent to saying: StatementList: ReturnStatement ExpressionStatement_In and: StatementList: ReturnStatement ExpressionStatement[~In] is equivalent to: StatementList: ReturnStatement ExpressionStatement
Prefixing a parameter name with “?” on a right-hand side nonterminal reference makes that parameter value dependent upon the occurrence of the parameter name on the reference to the current production's left-hand side symbol. For example:
VariableDeclaration[In]: BindingIdentifierInitializer[?In] is an abbreviation for: VariableDeclaration: BindingIdentifierInitializer VariableDeclaration_In: BindingIdentifierInitializer_In
If a right-hand side alternative is prefixed with “[+parameter]” that alternative is only available if the named parameter was used in referencing the production's nonterminal symbol. If a right-hand side alternative is prefixed with “[~parameter]” that alternative is only available if the named parameter was not used in referencing the production's nonterminal symbol. This means that:
StatementList[Return]: [+Return]ReturnStatement ExpressionStatement is an abbreviation for: StatementList: ExpressionStatement StatementList_Return: ReturnStatement ExpressionStatement and that: StatementList[Return]: [~Return]ReturnStatement ExpressionStatement is an abbreviation for: StatementList: ReturnStatement ExpressionStatement StatementList_Return: ExpressionStatement
5.2Algorithm Conventions
some algorithms, called abstract operations, are named and written in parameterized functional form so that they may be referenced by name from within other algorithms. Calls to abstract operations return Completion Records.
Calls to abstract operations return Completion Records. Abstract operations referenced using the functional application style and the method application style that are prefixed by ? indicate that ReturnIfAbrupt should be applied to the resulting Completion Record. For example, ? operationName() is equivalent to ReturnIfAbrupt(operationName()). Similarly, ? someValue.operationName() is equivalent to ReturnIfAbrupt(someValue.operationName()).
The prefix ! is used to indicate that an abstract operation will never return an abrupt completion and that the resulting Completion Record's value field should be used in place of the return value of the operation. For example, “Let val be ! operationName()” is equivalent to the following algorithm steps:
Let val be operationName(). Assert: val is never an abrupt completion. If val is a Completion Record, let val be val.[[Value]].
Mathematical operations such as addition, subtraction, negation, multiplication, division, and the mathematical functions defined later in this clause should always be understood as computing exact mathematical results on mathematical real numbers, which unless otherwise noted do not include infinities and do not include a negative zero that is distinguished from positive zero. Algorithms in this standard that model floating-point arithmetic include explicit steps, where necessary, to handle infinities and signed zero and to perform rounding. If a mathematical operation or function is applied to a floating-point number, it should be understood as being applied to the exact mathematical value represented by that floating-point number; such a floating-point number must be finite, and if it is +0 or -0 then the corresponding mathematical value is simply 0.
When impl, it's a need to diff an mathematical operations from operations in this standard(modeling floating-point arithmetic).
The mathematical function floor(x) produces the largest integer (closest to positive infinity) that is not larger than x.
floor(x) = x-(x modulo 1).
5.3Static Semantic Rules
Context-free grammars are not sufficiently powerful to express all the rules that define whether a stream of input elements form a valid ECMAScript Script or Module. In some situations additional rules are needed that may be expressed using either ECMAScript algorithm conventions. Such rules are always associated with a production of a grammar and are called the static semantics of the production.
Static Semantic Rules have names and typically are defined using an algorithm. Named Static Semantic Rules are associated with grammar productions and a production that has multiple alternative definitions will typically have for each alternative a distinct algorithm for each applicable named static semantic rule.
A special kind of static semantic rule is an Early Error Rule. Early error rules define early error conditions (see clause 16) that are associated with specific grammar productions. Evaluation of most early error rules are not explicitly invoked within the algorithms of this specification. A conforming implementation must, prior to the first evaluation of a Script or Module, validate all of the early error rules of the productions used to parse that Script or Module. If any of the early error rules are violated the Script or Module is invalid and cannot be evaluated.
Windows_Protocols__2017_Dec_01_cfb
2 Structures
2.1 Compound File Sector Numbers and Types
Each sector, except for the header, is identified by a nonnegative, 32-bit sector number. The following sector numbers above 0xFFFFFFFA are reserved and MUST NOT be used to identify the location of a sector in a compound file.
Followings are definitions of SectIDs:
#define SID_MAXREG (0xfffffffa) #define SID_FUTURE ((SectID)(SID_MAXREG + 1)) #define SID_MSAT_SECTOR ((SectID)(SID_MAXREG + 2)) #define SID_SAT_SECTOR ((SectID)(SID_MAXREG + 3)) #define SID_END_OF_CHAIN ((SectID)(SID_MAXREG + 4)) #define SID_UNUSED_SECTOR ((SectID)(SID_MAXREG + 5)) /* [MS-CFB] or [MS-CFB] errata 2.9 Compound File Size Limits: ...4,096 bytes/sector x MAXREGSECT (0xFFFFFFFA) sectors... so SID_MAXREG is also a special ID. */ #define SID_IS_SPECIAL(sid) ((SectID)(sid) >= SID_MAXREG)
The following list contains the types of sectors that are allowed in a compound file:
Header: A single sector with fields that are needed to read the other structures of the compound file.For version 4 compound files, the header size (512 bytes) is less than the sector size (4,096 bytes), so the remaining part of the header (3,584 bytes) MUST be filled with all zeroes. We can take head_size as equals with sect_size. FAT: Sector Allocation Table(OpenOffice: SAT). DIFAT: Used to locate FAT sectors in the compound file(OpenOffice: MSAT). Mini FAT: FAT for short streams(OpenOffice: SSAT). Directory: User-defined Data: Unallocated Free: Range Lock:A single sector that is used to manage concurrent access to the compound file. This sector must cover file offset 0x7FFFFFFF(OpenOffice:Not used).
2.6 Compound File Directory Sectors
2.6.1 Compound File Directory Entry
The valid values for a stream ID, which are used in the Child ID, Right Sibling ID, and Left Sibling ID fields, are 0 through MAXREGSID (excluding).Directory Entry Name (64 bytes): storage and stream names are limited to 32 UTF-16 code points, including the terminating null character. When locating an object in the compound file except for the root storage, the directory entry name is compared by using a special case-insensitive uppercase mapping, described in Red-Black Tree. The following characters are illegal and MUST NOT be part of the name: '/', '\', ':', '!'. Directory Entry Name Length (2 bytes): This field MUST match the length of the Directory Entry Name Unicode string in bytes. The length MUST be a multiple of 2 and include the terminating null character in the count. A secured parser shall not use this field. Object Type (offset 66, 0x42): This field MUST be 0x00, 0x01, 0x02, or 0x05, depending on the actual type of object. All other values are not valid: 0 for Unknown or unallocated; 1 for Storage Object; 2 for Stream Object; 5 for Root Storage Object. Color Flag (offset 67, 0x43): This field MUST be 0x00 (red) or 0x01 (black). Left Sibling ID(offset 68, 0x44): This field contains the stream ID of the left sibling. If there is no left sibling, the field MUST be set to NOSTREAM (0xFFFFFFFF). Right Sibling ID (offset 72, 0x48): Child ID (offset 76, 0x4C): This field contains the stream ID of a child object. If there is no child object, the field MUST be set to NOSTREAM (0xFFFFFFFF). CLSID (offset 80, 0x50): This field contains an object class GUID(can be used as a parameter to start applications.), if this entry is a storage or root storage. If no object class GUID is set on this object, the field MUST be set to all zeroes. State Bits (offset 96, 0x60): This field contains the user-defined flags if this entry is a storage object or root storage object. If no state bits are set on the object, this field MUST be set to all zeroes. Creation Time(8 bytes):Modified Time (8 bytes): Starting Sector Location (offset 116, 0x74): This field contains the first sector location if this is a stream object. For a root storage object, this field MUST contain the first sector of the mini stream, if the mini stream exists. Stream Size (8 bytes): Streams whose size is less than the Cutoff value exist in the mini stream. Parsers must trust Stream Size to decide it's mini or standard stream, while maintains a size telling the size figured out through sector chain of this stream.
2.6.4 Red-Black Tree
According rbtree, followings are true:The root storage object MUST always be black. wo consecutive nodes MUST NOT both be red.(if one node is red, it's left/right must be black) The left sibling MUST always be less than the right sibling. (root object has const name, its name don't compare; root object has no left and right)
This sorting relationship is defined as follows:
A node that has a shorter name is less than a node that has a longer name. For each UTF-16 code point, convert to uppercase by using the Unicode Default Case Conversion Algorithm
Saturday, January 27, 2018
股票投资
https://wallstreetcn.com/articles/3052005
++++++++++++++++++++++++ 电动汽车 ++++++++++++++++++++++++ 谷歌旗下Waymo和Lyft 联手开发自动驾驶汽车技术 601777 力帆股份 特斯拉 腾讯一季度总收入495.52亿元人民币(71.82亿美元 ),同比增长55%;网络游戏收入增长34% 腾讯向美国游戏公司Pocket Gems追加9000万美元投资
Friday, January 26, 2018
Double Precision Floating's Encodings
double's Encodings are as fllowing
+Infinity 0 11..11 (1) 00..00 +Normals 0 11..10 (1) 11..11 the max is less than 1 SHL (2046-1023) * 2 = 1 SHL 1024 = 2 ^ 1024; intel manual says it's less than 2 ^ 1023, which is proved to be in-correct +Normals 0 00..01 (1) 00..00 the min is 2^-1022; checked with javascript's normal min and normal max +Denormals 0 00..00 (0) 11..11 the max is less than 1 SHL (1-1023) = 2 ^ -1022; Will explain later +Denormals 0 00..00 (0) 00..01 the min is 1 SHL (1-1023) SHR 52 = 2 ^ -1074; as Denormals.min's minimal Fraction is 00..01, not 00..00(00..00 is left for zero), so if assume Denormals.min's integer|J bit as 1, then it's Significand is 1.00..01. processing 1.00..01 is not convinient, so we let Denormals.min's Exponent to be -1022 instead of -1023, by doing this, Denormals.min can be caculated in above way; so does Denormals.max. +0: all zeros; -0 1 00..00 (0) 00..00 -Denormals 1 00..00 (0) 00..01 the max is (-1) * (+Denormals min) -Denormals 1 00..00 (0) 11..11 the min is (-1) * (+Denormals max) -Normals 1 the max is (-1) * (+Normals.min) -Normals 1 the min is (-1) * (+Normals.max) -Infinity
NaNs are not detailed here, but Numbers of NaNs is easy to get:
NaNs's Exponent parts are the same with Infinitys, so Numbers of NaNs = 2^53 - 2
CreateGoogleCloudPlatformProject
Login Google Cloud Platform, tt "Manage resources" page, select create project( one can create at most 12 free projects at the cloud )
Project name example: LilyJohnGoogle
Project ID(Project ID can have lowercase letters, digits or hyphens and must start with a lowercase letter): lily-trade-com-rev01
Wait for google to finish, if the right-upper-corner icon stop from waiting state and you still can't see the project, use F5 to refresh.
done, now you can use the project( I use it for a static website )
Thursday, January 18, 2018
ECMA404_Dec2017_JSON
JSON shares a small subset of ECMAScript’s syntax with all other programming languages.
A JSON value can be an object, array, number, string, true, false, or null. Note, ECMA value undefined is not a JSON value.
8 Numbers
Following is grammar for Numbers:
Note, Numeric values that cannot be represented as sequences of digits (such as Infinity and NaN) are not permitted.
Monday, January 15, 2018
Stop Out level
What is Stop Out
A certain required margin level (in percentage) at which your trading positions will start to automatically close in order to prevent further account losses into the negative territory. |
For example:
Your balance is $10,000. You open a trading position with $1,000 margin. If the loss on this position reaches $9,500, your account equity becomes: $10,000 — $9,500 = $500 (50% of your used margin) At that time, a Stop Out will be issued and your positions will start closing.( |
Sunday, January 7, 2018
BC省公平药物计划
介绍
Fair PharmaCare即传说中的公平药物计划,就是药费报销。
就好像车保险, Fair PharmaCare同样有一个Deductible, 不同收入的家庭, 这个扣除额不一样, 零收入家庭这一项为0 。过了扣除额的部分,FairPharma Care可以报销70%, 数额更高一点之后, 报销额度就是100%。
需要注意Fair PharmaCare也有不报的药物或医疗器械,即使是报的项目,也有一个限定,酱紫如果医生如果给你开很贵的药的时候,你就要小心了。
申请
第一步: 在 https://pharmacare.moh.hnet.bc.ca/ 注册。
第二步: Health Insurance BC 给回信 Re: Confirmation of FairPharma Care Assistance. 告诉你Reg Num(注册号格式是“大写字母-三个数字-三个数字-两个数字”).如果你有extended health benefits plan, 它可能要求你在报销的时候提供FairPharma Care信息(记得Manulife就要求客户填这一项信息)。
第三步: 填同意书. 因为HIBC 需要知道你的收入以决定报销额度,所以取得你的申请先, 尽快把这个同意书寄过去就行了。