Example #1
0
        public static unsafe CodeBlock FromPtr(IntPtr target, int count)
        {
            if (target == IntPtr.Zero)
            {
                throw new ArgumentException();
            }

            if (count <= 0)
            {
                throw new ArgumentException();
            }

            var code = new CodeBlock();
            var ptr  = (long *)target.ToPointer();

            for (int i = 0; i < count; i += 8, ++ptr)
            {
                var rem = count - i;
                if (rem < 8)
                {
                    var bytes = BitConverter.GetBytes(*ptr);
                    for (int j = 0; j < rem; ++j)
                    {
                        code.Append(bytes[j]);
                    }
                }
                else
                {
                    code.AppendLong(*ptr);
                }
            }
            return(code);
        }
Example #2
0
        // TODO: use CAS to write data
        public unsafe CodeBlock WriteTo(IntPtr target)
        {
            if (_code.Count == 0)
            {
                throw new InvalidOperationException();
            }

            using (new WritableMemoryBlock(target, _code.Count)) {
                var oldCode = new CodeBlock();
                var ptr     = (long *)target.ToPointer();
                for (int i = 0; i < _code.Count; i += 8, ++ptr)
                {
                    var code = GetInt64(_code, i);
                    var rem  = _code.Count - i;
                    if (rem < 8)
                    {
                        long mask  = (1L << (rem * 8)) - 1L;
                        long tmp   = *ptr;
                        *    ptr   = (code & mask) | (tmp & ~mask);
                        var  bytes = BitConverter.GetBytes(tmp);
                        for (int j = 0; j < rem; ++j)
                        {
                            oldCode.Append(bytes[j]);
                        }
                    }
                    else
                    {
                        oldCode.AppendLong(*ptr);
                        *ptr = code;
                    }
                }
                return(oldCode);
            }
        }