Skip to content

Instantly share code, notes, and snippets.

@HyP3r-
Created January 21, 2019 19:02
Show Gist options
  • Save HyP3r-/c52df206e0e75978835fbf3b0a051511 to your computer and use it in GitHub Desktop.
Save HyP3r-/c52df206e0e75978835fbf3b0a051511 to your computer and use it in GitHub Desktop.
// Simple Script for Patching a JavaScript Function while Runtime
// Copyright 2019 Andreas Fendt. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
before = function (i, j) {
var a = i,
b = j;
// this is a function with a comment
var c = a + b;
var d = "Hello";
var e = 'World';
console.log(d + ' ' + e);
console.log(c + 3);
}
function patchFunction(func, patch) {
// helper functions
function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === "[object Function]";
}
function slashEscape(contents) {
return contents
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/'/g, '\\\'')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
// check if handlers are functions
if (!isFunction(func) || !isFunction(patch)) {
throw "no function";
}
var s = func.toString();
// get offsets of the code
var offsetArgsStart = s.indexOf("("),
offsetArgsEnd = s.indexOf(")", offsetArgsStart),
offsetCodeStart = s.indexOf("{"),
offsetCodeEnd = s.lastIndexOf("}");
// get source and arguments of the function
var source = s.substring(offsetCodeStart + 1, offsetCodeEnd),
args = s.substring(offsetArgsStart + 1, offsetArgsEnd);
patchedFunction = patch({source: source, args: args});
// create helper function which is spawning a new patched function
var f = "return Function('" +
patchedFunction.args.replace(" ", "").split(",").join("','") + "','" +
slashEscape(patchedFunction.source) +
"')";
var helper = Function(f)();
return helper;
}
function patch(func) {
func.source = func.source.replace("3", "6").replace("a + b", "a - b").replace("Hello", "Welcome");
return func;
}
after = patchFunction(before, patch);
after(2, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment