30
\$\begingroup\$

Inspired by this comment...

Thanks to users Step Hen, Wheat-Wizard, and Dennis for helping my solidify the specification of this challenge before posting it!

This is the Robber's thread! For the Cops' thread, go here


In this challenge, you are tasked with running some code that makes it so that your language no longer satisfies our criteria of being a programming language. In that challenge, that means making it so that the language can no longer...

  • Take numerical input and output

  • Add two numbers together

  • Test if a certain number is a prime or not.

This is a challenge, where there are two different challenges with two different objectives: The Cops will try to write some code that makes the language mostly unusable, and the robbers will try to find the hidden workaround that allows the cops to recover their language.

The cops will write two snippets of code:

  1. One that makes their language mostly unusable, e.g. by removing built in functions for taking input/output and numerical operations. This code is not allowed to crash or exit. It should be possible to add code to the end of this snippet, and that code will get evaluated. And

  2. A snippet of code that takes two numbers as input, adds them together, and outputs their sum. This snippet must still correctly function even after running the first snippet. When the two snippets are combined together, they must form a full program that adds two numbers, or define a function that adds two numbers. This snippet will probably rely upon obscure behavior, and be hard to find.

The cops will also choose any standard method of input and output. However, they must reveal exactly which format (input and output) they are using. For you to crack their answer, you must follow the same input/output format, or your crack does not count.

A cops answer will always reveal

  • The first snippet (obviously not the second).

  • Language (including minor version, since most submissions will probably rely on strange edge-cases)

  • IO format, including whether it's a function or full program. Robbers must use the same format to be a valid crack.

  • Any strange edge cases required for their answer to work. For example, only runs on linux, or requires an Internet connection.

As a robber, you must look at one of the cops submissions, and attempt to crack it. You may crack it by writing any valid snippet that could work as snippet 2 (adding two numbers together after the language is made mostly unusable). This does not have to be the same snippet that the cop originally wrote. Once you have an answer cracked, post your code as an answer on this thread, and post a link to your answer as a comment on the cop's answer. Then, that post will be edited to indicate is has been cracked.

Here's an example. For the first snippet, you might see the following python 3 program as a cops answer:

Python 3

print=None

Takes input from STDIN and output to STDOUT

A valid second snippet could be

import sys
a,b=int(input()),int(input())
sys.stdout.write(a+b)

This is valid because it will take two numbers as input, and output their sum even if you join the two snippets together, e.g.

print=None
import sys
a,b=int(input()),int(input())
sys.stdout.write(a+b)

This is a valid crack to their answer.

If a cop's answer remains uncracked for one whole week, they may edit in their second snippet, and indicate that their answer is now safe. Once it is edited to be safe, you may no longer attempt to crack it. If they do not edit it as safe, you may continue to try to crack it until they do.

The winner of the robber's thread is the user who has cracked the most answers, with the tie-breaker being the time they reached N cracks. (so if two different users each have 5 cracks for example, the user who posted their 5th crack first is the winner) After sufficient time has passed, I will accept the winner's answer with the most votes.

Have fun!

Rule clarifications

  • The first snippet must run correctly without taking any input. It may output whatever you like, and this output will be ignored. As long as after the snippet is done, the second snippet runs correctly.

  • The second snippet must actually be executed for your answer to be valid. This means an answer like

    import sys
    sys.exit()
    

    is not valid because it doesn't break the language. It simply quits.

  • After being safe, your score is the byte count of both snippets.

  • This goes back to Please reveal any strange edge cases required for your answer to work... Your submission must contain enough information before being revealed to be reproducible after being revealed. This means that if your answer becomes safe, and then you edit in: Here's my answer. Oh ya, BTW this only works if you run it on Solaris, jokes on you! your answer is invalid and will be deleted and not considered eligible for winning.

  • The second snippet is allowed to crash after outputting the sum. As long as the output is still correct (for example, if you choose to output to STDERR, and then you get a bunch of crash information, this is invalid)

Leaderboard

Here is a list of every user with at least one crack, ordered by score and then name (alphabetical). If you submit a crack, please update your score accordingly.

#User                       #Score
Ilmari Karonen              8

Dennis                      5

Olivier Grégoire            4

Sisyphus                    3
Veedrac                     3

Arnold Palmer               2
Bruce Forte                 2
DJMcMayhem                  2
Dom Hastings                2
ppperry                     2

1bluston                    1
2012rcampion                1
Ben                         1
BlackCap                    1
Christian Sievers           1
Cody Gray                   1
HyperNeutrino               1
Joshua                      1
Kaz                         1
Mark                        1
Mayube                      1
Xnor                        1
zbw                         1
\$\endgroup\$
0

45 Answers 45

22
\$\begingroup\$

C (GCC/Linux) by Sisyphus

This snippet closes the provided function and starts a new one (classic code injection), which itself redefines close so that instead of closing the fd, runs our desired code.

}
int close(int x) {
  int a, b;
  scanf("%d %d", &a, &b);
  printf("%d\n", a + b);

  exit(0);
\$\endgroup\$
21
\$\begingroup\$

Python, Wheat Wizard's solution here

import sys
c="".join(open(__file__).read().split('\n')[4:])
if set(c)-set(' &)(,.:[]a`cdfijmonrt~')or"import"in c:sys.setrecursionlimit(1)
f=lambda\
:[]                                                      # my code starts here
sys.setrecursionlimit(1000)
print(int(input())+int(input()))

I mean, you can just set the recursion limit back, and nothing bad happens...

Works on TIO

Note

This is my first ever CnR submission, so if this breaks any rules, please tell me and I'll delete this.

\$\endgroup\$
8
  • 4
    \$\begingroup\$ I'm dumb for missing this \$\endgroup\$
    – Wheat Wizard
    Commented Jul 19, 2017 at 2:10
  • \$\begingroup\$ @WheatWizard :) \$\endgroup\$
    – hyperneutrino
    Commented Jul 19, 2017 at 2:11
  • \$\begingroup\$ @wheatwizard Don't reveal your intended solution yet. I'd looove to see a better cop with your original solution that fixes this problem. \$\endgroup\$
    – DJMcMayhem
    Commented Jul 19, 2017 at 2:12
  • \$\begingroup\$ @Djmcmayhem I'm probably going to repost with a del sys. \$\endgroup\$
    – Wheat Wizard
    Commented Jul 19, 2017 at 2:13
  • \$\begingroup\$ @WheatWizard Remember os.sys, if that makes a difference :P \$\endgroup\$
    – hyperneutrino
    Commented Jul 19, 2017 at 2:14
15
\$\begingroup\$

Haskell by Ben

import Prelude(getLine,print)
a=a
[]++s=s
(a:as)++s=a:(as++s)
r""=""
r(c:s)=(r s)++[c]
t(_:r)=r
ts l=l:ts(t l)
x[_](v:_)=v
x(_:r)(_:s)=x r s
d(a:_:_:_:_:_:_:_:_:_:r)=a:d r
(a:_)!!""=a
l!!(n:m)=d(x['0'..n](ts l))!!m
a+b=[[0..]!!a..]!!b
a-b=let n=[0..]!!a;m=[0..]!!b in
    case [n..m] of
      [] ->   x[m..n][0..]
      l  -> -(x l    [0..])
add('-':x)('-':y)= -(r x+r y)
add('-':x)y=r y-r x
add x('-':y)=r x-r y
add x y=x+y
main=do a<-getLine;b<-getLine;print(add a b)

I still have literal numbers and chars (I use 0, '0' and '-'), and [a..] and [a..b] which are very useful. And I have unary -, but I could do without.

I recreate ++ to implement r (reverse) and define t and ts which are tail and tails. x a b returns the nth element of b, where n is the length of a minus one. x could usually be defined as snd.last.zip. The function d takes a list and returns a list with the elements from those positions that are multiples of ten. l!!s returns the nth element of l, where s is the reversed string representation of n. + returns as integer the sum of two natural numbers given as reversed strings, likewise - for the difference. add returns as integer the sum of two possibly negative integers given as strings.

I wonder if this is somewhat similar to what Ben had in mind.

\$\endgroup\$
1
  • \$\begingroup\$ Yep, pretty much the same ideas. Pattern matching against literals to get equality tests and branching, list enumeration syntax to get a form of increment. I was quite surprised to find : was in scope even with NoImplicitPrelude and without importing anything. \$\endgroup\$
    – Ben
    Commented Jul 19, 2017 at 12:49
7
\$\begingroup\$

C (gcc) by Conor O'Brien


void post_main() __attribute__ ((destructor));

void post_main()
{
    int a, b;
    char sum[11];
    void *stdin = fdopen(0, "r");

    fscanf(stdin, "%u %u", &a, &b);
    sprintf(sum, "%u", a + b);
    write(1, sum, strlen(sum));
}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ ugggg I forgot to ban fscanf and a lot of those other functions >.> good job \$\endgroup\$ Commented Jul 19, 2017 at 3:47
7
\$\begingroup\$

Python 2 by Wheat Wizard (fourth iteration)

import sys
if set("".join(open(__file__).read().split('\n')[4:]))-set(' &)(,.:[]a`cdfijmonrt~'):sys.setrecursionlimit(1)
for m in sys.modules:sys.modules[m]=None
del sys;f=lambda\
c,d:(`int([]in[])`[:[]in[]]).join([((c)and`dict([((int([]in[])),(int([]in[])))])`[(int([]in[[]])):][(int([]in[[]]))].join([`dict([((int([]in[])),(int([]in[])))])`[(int([]in[]))],`dict([((int([]in[])),c)])`[(int([]in[[]])):][(int([]in[[]])):][(int([]in[[]])):][(int([]in[[]])):]])or`int([]in[])`[:[]in[]]).format((int([]in[]))),((d)and`dict([((int([]in[])),(int([]in[])))])`[(int([]in[[]])):][(int([]in[[]]))].join([`dict([((int([]in[])),(int([]in[])))])`[(int([]in[]))],`dict([((int([]in[])),d)])`[(int([]in[[]])):][(int([]in[[]])):][(int([]in[[]])):][(int([]in[[]])):]])or`int([]in[])`[:[]in[]]).format((int([]in[]))),`(int([]in[]))`]).rfind(`(int([]in[]))`)

Try it online!

No exploits, just a function to add using only characters ' &)(,.:[]a`cdfijmonrt~', as intended (actually only '(),.:[]`acdfijmnort').

I made no attempt to make it short; I just wrote subexpressions for intermediate values like 0 and the empty string and string-substituted those in.

def f(c,d):
	FALSE = []in[]
	TRUE = []in[[]]
	ZERO = int([]in[])
	ONE = int(TRUE)
	EMPTY = `int([]in[])`[:[]in[]]
	ZERO_STR = `ZERO`
	ONE_STR = `ONE`

	ZERO_DICT = dict([(ZERO,ZERO)])
	ZERO_DICT_STR = `ZERO_DICT`

	OPEN_BRACE = ZERO_DICT_STR[ZERO]
	COLON = ZERO_DICT_STR[ONE:][ONE]
	CLOSE_BRACE = ZERO_DICT_STR[ONE:][ONE:][ONE:][ONE:][ONE]

	C_STR = `c`
	D_STR = `d`

	FORMAT_STR_C = ''.join([OPEN_BRACE, ZERO_STR, COLON, C_STR, CLOSE_BRACE])
	FORMAT_STR_D = ''.join([OPEN_BRACE, ZERO_STR, COLON, D_STR, CLOSE_BRACE])

	LENGTH_C_STR = c and FORMAT_STR_C.format(ONE_STR) or EMPTY
	LENGTH_D_STR = d and FORMAT_STR_D.format(ONE_STR) or EMPTY

	TOTAL_STR = EMPTY.join([LENGTH_C_STR, LENGTH_D_STR, ZERO_STR])
	RESULT = TOTAL_STR.find(ZERO_STR)

	return RESULT

Try it online!

The core idea is that string format '{0:5}'.format('1') pads the number zero to a length of 5 like '1 '. By concatenation two such strings using ''.join, the sum of their length is the sum of the input numbers. Then, we tack on a 0 to the end and call .find() to the final position, which is the sum.

The string '{0:5}' to format is produced by extracting the {:} characters from string reprs of dictionaries, created with dict. The string repr of each successive summand is placed where the 5 would be. I wanted to use a dict like {0:5} itself, but its repr includes a space that messed it up.

Inputs of 0 mess up the process because the string sub has a minimum length of 1. We have those with an and/or to give the empty string in this case.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ This is quite different than what I had intended, I'd love to see an explanation. \$\endgroup\$
    – Wheat Wizard
    Commented Jul 19, 2017 at 13:12
  • \$\begingroup\$ You can golf all your int([]in[]) to simply int() as both will output 0. \$\endgroup\$
    – Value Ink
    Commented Jul 19, 2017 at 18:44
5
\$\begingroup\$

Haskell, by Laikoni

main=main--
 & ((+) <$> readLn <*> readLn >>= print)
i&o=o
\$\endgroup\$
5
\$\begingroup\$

x86 16-bit real-mode assembly, by Joshua

    int  0x3                  ; <---  this is the "robber" portion

    ; -- begin code to print numbers in real-mode asm using ROM BIOS video interrupts --
    add  dx, cx               ; add input values together
    mov  ax, dx               ; move result into AX
    push WORD 0xB800
    pop  ds                   ; DS == starting address of text-mode video buffer
    xor  cx, cx               ; digit counter
    xor  di, di               ; position counter
    mov  bx, 0xA              ; divisor

    test ax, ax               ; is number negative?
    jns  .GetDigits
    neg  ax                   ; convert negative number to positive
    mov  WORD ds:[di], 0x4F2D ; output leading negative sign, in white-on-red
    add  di, 2                ; increment position counter

.GetDigits:
    xor  dx, dx
    div  bx                   ; divide DX:AX by 10 (AX == quotient, DX == remainder)
    push dx                   ; push digit onto stack
    inc  cx                   ; increment digit counter
    test ax, ax
    jnz  .GetDigits           ; keep looping until we've got 'em all

.PrintDigits:
    pop  dx                   ; get digit off of stack
    dec  cx                   ; decrement digit counter
    mov  dh, 0x4F             ; high byte: color attribute (white-on-red)
    add  dl, 0x30             ; low  byte: convert to ASCII
    mov  WORD ds:[di], dx     ; output digit
    add  di, 2                ; increment position counter
    test cx, cx
    jnz  .PrintDigits         ; keep looping until we've printed 'em all

    cli
    hlt

screenshot of Debug dump of code, along with output in upper-left corner

Explanation:

The "breakage" introduced by Joshua's code is the setting of the trap flag (TF), which puts the CPU into single-step mode. This means that only a single instruction will be executed at a time, before the CPU stops (traps) with a type-1 interrupt. This is what allows debuggers to implement single-stepping of code—quite handy there, but a real PITA if you want to run the code outside the context of a debugger!

It is the following section of code that turns on the trap flag:

pushf               ; push the FLAGS register onto the top of the stack
mov bp, sp          ; load the pointer to the top of the stack into BP
or word [bp], 256   ; bitwise-OR the WORD at the top of the stack (the copy of FLAGS)
                    ;  with 0x100, which turns on bit 8 (TF)
popf                ; pop the modified flags back off the stack into FLAGS

The implementation of the trap flag means that we get a chance to execute exactly one instruction before the CPU traps—that is the one that comes immediately after the POPF here. So, we need to make this one count.

The trick is the INT 3 instruction, which invokes interrupt number 3. There are two reasons why this works to "unbreak" the code:

  1. The trap flag is cleared in interrupt handlers. This is just part of Intel's design, but it was presumably done for basic sanity reasons. Remember that the implementation of the trap flag is that a type-1 interrupt is invoked after execution of each instruction, so if TF wasn't cleared, INT 1 would itself trigger an interrupt—it would be interrupts all the way down. Also, having interrupts clear TF just makes it easier to debug the code, much like an IDE that automatically steps over calls to library functions.

  2. The way interrupts work is essentially the same as a far CALL. They invoke the interrupt handler whose address is stored at the corresponding position in the global interrupt vector table. Since this table begins at address 0x0000:0000, and is stored in a 4-byte segment:offset format, calculating the address is as simple as multiplying 4 by the interrupt vector/number. In this case, we invoke interrupt 3, so that would be 4×3=12.

    …and you'll notice that Joshua thoughtfully set this up for us. Prior to enabling the trap flag, he has the following code:

    mov  di, 12
    mov  [di], si
    mov  [di + 2], bp
    

    which sets 0x0000:000C (the interrupt handler for INT 3) to BP:SI. That means whenever INT 3 is invoked, it pushes the FLAGS register onto the stack, followed by the return address, and then branches to BP:SI, which allows us to start executing code again, in a context where the trap flag is turned off.

It's all downhill after INT 3. All we need to do is add two numbers together and print the result. Except that this isn't as simple in assembly language as it would be in other languages, so this is where the bulk of the code is spent.

Joshua is allowing the robber to specify any I/O mechanism (s)he wants, so I'm taking the simplistic approach of assuming that the values are passed in the DX and CX registers. That is reasonable, since these are not clobbered anywhere by his "prologue" code.

The output then is done by storing ASCII bytes directly into video memory. The video buffer starts at 0xB800:0000 on a text-mode CGA, EGA, and/or VGA, so we start printing there. The format is: character in the low byte, and color attribute in the high byte. That means each character is on a 2-byte offset. We just iterate through each of the digits in the number (base-10), converting them to ASCII and printing them one at a time to the screen. Yes, this is a lot of code. There are no library functions to help us in assembly language. This can almost certainly be optimized further, but I got tired of working on it...

After the output is displayed, the code is allowed to crash or do whatever, so we just clear interrupts and halt the CPU.

\$\endgroup\$
5
  • \$\begingroup\$ I'm puzzled; I can't figure out how this gets past the hlt instruction at BP:SP+1. \$\endgroup\$
    – Joshua
    Commented Jul 21, 2017 at 15:27
  • \$\begingroup\$ @Joshua Hmm, that's a good point. I didn't even think about that. Stepping through the code in Debug, I execute INT 3 and end up immediately back at the instruction following it, so I just went with it. Maybe has something to do with my testing environment? CLI would only disable hardware interrupts, but even if it got past the HLT, you'd think it would fall through and execute the code in l immediately thereafter. \$\endgroup\$
    – Cody Gray
    Commented Jul 21, 2017 at 16:10
  • \$\begingroup\$ Oh, you were single stepping. Yeah that would do it. I'm going to double check but I think I uploaded whacked code. \$\endgroup\$
    – Joshua
    Commented Jul 21, 2017 at 16:24
  • \$\begingroup\$ I also tested without single-stepping. No difference. This is on FreeDOS latest in VM Virtualbox. I have real hardware available, but didn't feel like powering it up. @Joshua \$\endgroup\$
    – Cody Gray
    Commented Jul 21, 2017 at 16:25
  • \$\begingroup\$ Well you clearly cracked it then. Maybe you found a way to raise that NMI. \$\endgroup\$
    – Joshua
    Commented Jul 21, 2017 at 16:50
5
\$\begingroup\$

Haskell by zbw

{-#OPTIONS_GHC -fth -w#-}
module M where

import Language.Haskell.TH.Syntax
import System.IO.Unsafe

a = $( runIO $ TupE[] <$
              do x <- readLn :: IO Integer
                 y <- readLn
                 print $ x + y )

Can't run code at run-time? Run it at compile time!

This was a lot of fun, I did not know template haskell before this challenge.

\$\endgroup\$
4
\$\begingroup\$

Python 2 by TwiNight


print input()+input() #

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Dammit! Forgot about this. Time for a new answer then. \$\endgroup\$
    – TwiN
    Commented Jul 19, 2017 at 2:49
4
\$\begingroup\$

Python 3, ppperry's 2nd Challenge

Wow, this was fun! I enjoyed solving this.

Edit: OK, I fixed it. It seems like the classes were at a different index in the subclass list on TIO than on my computer, so I made it work for both, and added a TIO.

import sys
for mod in sys.modules.values():mod.__dict__.clear()
1+1

# My code begins here
str = "Hello!".__class__
int = (37).__class__
object = str.__base__

def find_subclass(superclass, name):
	for cls in superclass.__subclasses__():
		if cls.__name__ == name:
			return cls

_io_IOBase      = find_subclass(object, '_IOBase')        # <class '_io._IOBase'>
_io_RawIOBase   = find_subclass(_io_IOBase, '_RawIOBase') # <class '_io._RawIOBase'>
_ioFileIO       = find_subclass(_io_RawIOBase, 'FileIO')  # <class '_io.FileIO'>
stdout = _ioFileIO('stdout', mode='w', opener=lambda name,flags: 1) # FD for stdout is 1
stdin  = _ioFileIO('stdin',  mode='r', opener=lambda name,flags: 0) # FD for stdin is 0
nums = str(stdin.read(), encoding='utf-8').split()
stdout.write(str(int(nums[0]) + int(nums[1])).encode('utf-8') + b'\n')
stdout.flush()

Try it online!

\$\endgroup\$
6
  • \$\begingroup\$ I get an error. sys.excepthook is missing? \$\endgroup\$
    – Riker
    Commented Jul 21, 2017 at 17:56
  • \$\begingroup\$ Hmm... works for me. What's the real error you're getting? (That's happening because ppperry's code destroyed pretty much everything, including knowing how to show exceptions, so that's the sys.excepthook, but there'll be a real cause listed somewhere in there.) \$\endgroup\$
    – zbw
    Commented Jul 21, 2017 at 17:59
  • \$\begingroup\$ Nevermind, the real error is IndexError('list index out of range',). It's on the line with the definition of _io_RawIOBase. \$\endgroup\$
    – Riker
    Commented Jul 21, 2017 at 18:01
  • \$\begingroup\$ The problem is that the order of the subclasses isn't fixed. _io_IOBase = [cls for cls in object.__subclasses__() if cls.__name__ == '_IOBase'][0] should work everywhere. \$\endgroup\$
    – Dennis
    Commented Jul 21, 2017 at 18:06
  • \$\begingroup\$ @Dennis Yep, I realized that and just fixed it. It works on TIO now! \$\endgroup\$
    – zbw
    Commented Jul 21, 2017 at 18:09
3
\$\begingroup\$

Java 8 by Olivier Grégoire

class A {
  public A() {
    String[] args = System.lineSeparator().split(",");
    System.out.print(Integer.parseInt(args[0]) + Integer.parseInt(args[1]));
  }
}

Try it online!

Since Olivier explicitly allowed passing input via properties set using VM arguments, I'll specify that the input should be given in the VM argument -Dline.separator=X,Y, where X and Y are the numbers to be added. That is, to e.g. add the numbers 17 and 25, the program should be invoked as:

java -Dline.separator=17,25 Main

I believe this should work on any system than can run Java programs on the command line. Even on systems that don't have a command line, any other equivalent mechanism for setting system properties could be used to pass the input to the VM.


Ps. Here's my earlier cracking attempt, which was deemed invalid due to using JVM-specific features:

class SecurityManager extends sun.awt.AWTSecurityManager {
  static {
    String[] args = System.getProperty("sun.java.command").split(" ");
    int a = Integer.parseInt(args[args.length-2]);
    int b = Integer.parseInt(args[args.length-1]);
    System.out.println(a+b);
  }
}

Try it online!

This turned out a lot less verbose than the previous one. The hard part was finding a subclass of SecurityManager that didn't live in a namespace beginning with "java.". I suspect this is still not the intended solution, but it works.*

*) On TIO, at least; the sun.awt.AWTSecurityManager class and the sun.java.command property don't seem to be officially documented, and may not be available on all JVMs.

\$\endgroup\$
3
  • \$\begingroup\$ Nice job! I tried this, but couldn't find a SecurityManager that was in scope... You could also read from System.in at this point, though, because it's not closed yet. \$\endgroup\$
    – zbw
    Commented Jul 20, 2017 at 21:12
  • \$\begingroup\$ Sorry, this is a platform-dependant answer on two regards: both sun.awt.SecurityManager and "sun.awt.command" are platform dependant and are not part of Java. \$\endgroup\$ Commented Jul 20, 2017 at 22:22
  • \$\begingroup\$ Yep, cracked! :) The intended solution was to go through the System.getProperties().get("blah") (since I only blocked the access to System.getProperty, not System.getProperties), but this is good enough! Well done! \$\endgroup\$ Commented Jul 21, 2017 at 12:23
3
\$\begingroup\$

Jelly by hyper neutrino


+

Super simple. The Newline causes the first link to not be called.

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ You could also adhere to the no newline rule like this \$\endgroup\$ Commented Jul 19, 2017 at 2:56
  • \$\begingroup\$ Yup, I thought this would be too easy. \$\endgroup\$
    – hyperneutrino
    Commented Jul 19, 2017 at 15:42
3
\$\begingroup\$

Python 2 by Wheat Wizard

import sys
c="".join(open(__file__).read().split('\n')[4:])
if set(c)-set(' &)(,.:[]a`cdfijmonrt~')or"import"in c:sys.setrecursionlimit(1)
sys.modules['sys'],sys.modules['os']=None,None;del sys;f=lambda\
a,b:a+b
__import__('sysconfig').__dict__['os'].__dict__['sys'].setrecursionlimit(1000)
print(f(1,2))

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ This is turning out to be more difficult than I thought. \$\endgroup\$
    – Wheat Wizard
    Commented Jul 19, 2017 at 4:14
3
\$\begingroup\$

Java by LordFarquaad

Blocking the access to the objects at the source level was really smart (and annoying when testing), well done!

public class java {
  public static void main(String[] s) {
    //there is no executable code in snippet one.
    //your code here.
    try {
      ClassLoader cl = ClassLoader.getSystemClassLoader();
      Object in = cl.loadClass("java.lang.System").getDeclaredField("in").get(null);
      Object out = cl.loadClass("java.lang.System").getDeclaredField("out").get(null);
      Object scanner = cl.loadClass("java.util.Scanner").getConstructor(cl.loadClass("java.io.InputStream")).newInstance(in);
      int i = (Integer)cl.loadClass("java.util.Scanner").getMethod("nextInt").invoke(scanner);
      int j = (Integer)cl.loadClass("java.util.Scanner").getMethod("nextInt").invoke(scanner);
      cl.loadClass("java.io.PrintStream").getMethod("println", Object.class).invoke(out, i+j);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  class Class {}
  class Method {}
  class System {}
  class FileDescriptor {}
  class Logger {}
  class Runtime {}
  class Scanner {}
}
\$\endgroup\$
2
  • \$\begingroup\$ Nice! What if ClassLoader had been shadowed? \$\endgroup\$
    – Jakob
    Commented Aug 2, 2017 at 4:12
  • 1
    \$\begingroup\$ @JakobCornell "".getClass().getClassLoader(). Shadowing is usually only a problem you have to think about once and then it's ok. You could even shadow Object, I'd still be able to solve this. Ok, you might force me into the 1kb solution, but it's possible. \$\endgroup\$ Commented Aug 2, 2017 at 6:18
3
\$\begingroup\$

Ruby by histocrat


BEGIN{exit(gets.to_i + gets.to_i)}

Try it online!

\$\endgroup\$
3
\$\begingroup\$

JavaScript by Daniel Franklin

location="data:text/html;base64,PHNjcmlwdD5jb25zb2xlLmxvZygxKnByb21wdCgpKzEqcHJvbXB0KCkpPC9zY3JpcHQ+"

This might be considered a slightly cheaty solution, but it does work for me on Chromium 59 / Linux, even if I do also receive a warning saying:

Upcoming versions will block content-initiated top frame navigations to data: URLs. For more information, see https://­goo.gl/BaZAea.

Ps. Here's another crack, this time without warnings:

Node.prototype.removeChild=function(){}
document.body.innerHTML='<iframe src="data:text/html;base64,PHNjcmlwdD5jb25zb2xlLmxvZygxKnByb21wdCgpKzEqcHJvbXB0KCkpPC9zY3JpcHQ+"/>'
\$\endgroup\$
1
  • \$\begingroup\$ I think prompt()- -prompt() saves two bytes \$\endgroup\$
    – Marie
    Commented Jul 20, 2017 at 20:06
3
\$\begingroup\$

Inform 7, by Ilmari Karonen

Blantant abuse of ambiguous nouns ... My code begins with factory is a room. The previous line is the cop's code. Type add 1 and 1 to get 2, for example.

For reading a command: Rule fails

factory is a room.
The adder one is a thing. The adder two is a thing. The adder one is in factory. The adder two is in factory.
Before reading a command: change the text of the player's command to "examine adder"

For printing a parser error: 
    if the player's command includes "add [number] ":
        let N be the number understood;
        if the player's command includes "and [number]":
            say the number understood plus N;
\$\endgroup\$
2
\$\begingroup\$

Java, Roman Gräf

public class Main {
    public static void main(String... args){
        System.setOut(null);
        System.setErr(null);

        System.setOut(new java.io.PrintStream(new java.io.FileOutputStream(java.io.FileDescriptor.out)));
        System.setErr(new java.io.PrintStream(new java.io.FileOutputStream(java.io.FileDescriptor.err)));
        System.out.println("This");
        System.err.println("works");
    }
}

Sets stdout and stderr back to their initial values.

I believe I am able to use the fully qualified name instead of an import, if I am wrong please correct me (this is my first post here.) This could probably be done using reflection as well.

Edit: here's a reflective solution using only java.lang.reflect.*:

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Test {
    public static void main(String... args) {
        System.setOut(null);
        System.setErr(null);

        try {
            Class<?> psClass = Class.forName("java.io.PrintStream");
            Class<?> fsClass = Class.forName("java.io.FileOutputStream");
            Class<?> osClass = Class.forName("java.io.OutputStream");
            Class<?> fdClass = Class.forName("java.io.FileDescriptor");
            Class<System> sClass = System.class;
            Constructor psCtor = psClass.getConstructor(osClass);
            Constructor fsCtor = fsClass.getConstructor(fdClass);

            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);

            Object sout = psCtor.newInstance(fsCtor.newInstance(fdClass.getDeclaredField("out").get(null)));
            Field outField = sClass.getDeclaredField("out");
            modifiersField.setInt(outField, outField.getModifiers() & ~Modifier.FINAL);
            outField.set(null, sout);

            Object serr = psCtor.newInstance(fsCtor.newInstance(fdClass.getDeclaredField("err").get(null)));
            Field errField = sClass.getDeclaredField("err");
            modifiersField.setInt(errField, outField.getModifiers() & ~Modifier.FINAL);
            errField.set(null, serr);

            System.out.println("This");
            System.err.println("works");
        } catch (Exception ignore) {
        }
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ Yep, stdin, stdout and stderr are stored elsewhere! You don't even need to use setOut and setErr as you can simply use the PrintStream directly. \$\endgroup\$ Commented Jul 19, 2017 at 9:20
  • \$\begingroup\$ Added reflective solution as well as I feel this was what was initially expected \$\endgroup\$
    – Salem
    Commented Jul 19, 2017 at 9:31
2
\$\begingroup\$

cQuents, Step Hen, 3 bytes

+BC

Try it online!

Took a lot of talking to Step Hen to figure out how the hell his weird language works, but in short:

His code was #|1,1:A. #|1,1 is the default input, meaning any input given to the program is appended by 2 1's. (IE if you pass a 47 and a 53, your input is [47, 53, 1, 1].

: simply sets the mode, which will output the nth item in the sequence if n is set, and otherwise output the entire sequence.

Finally A gets the first input.

Because we have 4 inputs [47, 53, 1, 1], adding BC to the end would also fetch the 2nd and 3rd input, and the 4th input implicitly becomes n.

Because our sequence is ABC, it's parsed algebraically, meaning it becomes A*B*C. We don't want that, but if we insert a + between A and B, it becomes A+B*C, where A and B are our inputs, and C is 1.

\$\endgroup\$
2
  • \$\begingroup\$ how the hell his weird language works maybe once I finish it it might make some more sense \$\endgroup\$
    – Stephen
    Commented Jul 19, 2017 at 16:04
  • \$\begingroup\$ @StepHen don't get me wrong it's a neat language, but weird as hell \$\endgroup\$
    – Mayube
    Commented Jul 19, 2017 at 16:10
2
\$\begingroup\$

RProgN2 by @ATaco

"+-/*÷^"{²[[\=};
{"D"=11{‹1D&¬\D›]"D"=}:]1\2\Š1{[\D‹|"D"=};D¬{1"D"=1\2\Š1{[D‹"D"=};}{[}?D}"~"={"d"="g"=g~d&gd~&|}"±"={"H"="I"=11{‹H1&I1&±\H›"H"=I›"I"=H¬¬I¬¬|}:1\2\Š1{[H‹|"H"=};H}"×"={"J"="K"=1{JK&‹JK×"K"=]"J"=}:JK|}"+"=

Try it online!

This is by far not the best answer I could've given, but it allows adding numbers together again. Had I actually went through and did proper stack handling, I could probably golf this quite a bit, but as of now I'm happy with the answer.

In ATaco's original post he effectively just reassigned all of the main arithmetic operators to destroy their inputs. To fix this problem I redefined what addition was in terms of its binary operations, which was a pain because RProgN2 doesn't have a binary negation operator or xor.

Note: If you want to test the input, numbers with more than one digit need to be in the form "XX..." n to be converted into an actual number since RProgN2 takes each character as is unless it's a concept or string. Edit: @ATaco noted that adding a '$' before a multidigit number will do the same thing.

EDIT: Here is the logic for my solution. As you can see, most definitely not the most refined code, but it works.

{"D"=11{‹1D&¬\D›]"D"=}:]1\2\Š1{[\D‹|"D"=};D¬{1"D"=1\2\Š1{[D‹"D"=};}{[}?D}"~"= # Defines the ~ operator which negates a number
{"D"=                                                                   }     # Remove the top of the stack and assign D with the popped value
     11                                                                       # Push 2 1's to the stack.  The first is used as a counter, the second if the initial truthy value for the loop
       {             }:                                                       # Start a while loop if the top of the stack (popped) is truthy (removes final falsey value)
        ‹                                                                     # Left shift the counter variable
         1D&¬                                                                 # Push negation of last bit of D
             \                                                                # Swap the counter (index 1) and the negated bit (index 0)
              D›]"D"=                                                         # Push D, right shift it, duplicate the value on the stack, then pop and assign the top to D
                       ]1\                                                    # Duplicate the counter, push 1, and swap the counter to the top of the stack
                          2\Š                                                 # Push 2, swap with the counter, then take the log (log_2(counter))
                             1{         };                                    # Run the for loop "for (i=1;i<=log_2(counter);i+=1)"
                               [\                                             # Pop off i, then swap the original counter with the next bit to append
                                 D‹|"D"=                                      # Left shift D, or it with the next bit, then assign D the new value
                                          D¬                                  # Need to check if D was 0 or not (in the case of 0b11...1~)
                                            {                     }{ }?       # Conditional on the truthiness of not D
                                             1"D"=                            # If D was 0, we assign it as 1, then start to bit shift it up
                                                  1\2\Š1{       };            # Same for loop as earlier since the original counter is still on the top of the stack
                                                         [D‹"D"=              # Pop off i, left shift D, then reassign it
                                                                    [         # Else D was non-zero, so just pop off the counter we've been carrying around
                                                                       D      # Push the final value to the top of the stack as a return
                                                                         "~"= # Assign the function between the {}'s to the character '~'

{"d"="g"=g~d&gd~&|}"±"=                                                       # Defines the ± operator which performs a single bit xor
{"d"="g"=         }                                                           # Assign d and g the first and second values on the stack respectively
         g~d&                                                                 # Push ~g&d to the top of the stack
             gd~&                                                             # Push g&~d to the top of the stack
                 |                                                            # Or the top 2 values giving us (~g&d)|(g&~d)
                   "±"=                                                       # Assign this function to the ± operator

{"H"="I"=11{‹H1&I1&±\H›"H"=I›"I"=H¬¬I¬¬|}:1\2\Š1{[H‹|"H"=};H}"×"=             # Defines the × operator which performs a full number xor
{"H"="I"=                                                   }                 # Store the top 2 stack values in H and I (in that order)
         11{                            }:                                    # Another while loop with the first one being a counter for later, and the second is our truthy value to start the loop
            ‹H1&I1&±                                                          # Left shift the counter, then push the bit xor of H's and I's lowest bit ((H&1)±(I&1) in infix notation)
                    \                                                         # Swap the calculated bit and the counter
                     H›"H"=I›"I"=                                             # Right shift both variables and store the values back in them
                                 H¬¬I¬¬|                                      # Effectively pushing the value (H!=0 | I != 0)
                                          1\2\Š1{        };                   # Same for loop as the ones above
                                                 [H‹|"H"=                     # Pop off the for loop counter, left shift H, or it with the next bit, and reassign
                                                           H                  # Push the final computed xor value to the top of the stack
                                                             "×"=             # Assign this whole function to the × operator

{"J"="K"=1{JK&‹JK×"K"=]"J"=}:JK|}"+"=                                         # Finally, a function redefining addition as the "+" operator
{"J"="K"=                       }                                             # Store the top 2 stack values in J and K respectively
         1{                }:                                                 # An initial truthy value to start the while loop and the loop itself
           JK&‹                                                               # Push (J&K)<<1 to the stack
               JK×                                                            # Compute the full xor of J and K (J^K in Python)
                  "K"=                                                        # Assign K the value of J xor K
                      ]"J"=                                                   # Duplicate (J&K)<<1 and assign 1 copy to J, leaving (J&K)<<1 as our while check (while ((J&K)<<1))
                             JK|                                              # Finally push the value J|K to the stack to get the addition
                                 "+"=                                         # Assign this function to the "+" operator, restoring it
\$\endgroup\$
4
  • \$\begingroup\$ Providing a $ before a sting of numbers also groups it as one number, e.g. 56$46$12 will push the numbers 5, 6, 46 and 12. I'll post my actual solution and such tommorow \$\endgroup\$
    – ATaco
    Commented Jul 20, 2017 at 13:06
  • \$\begingroup\$ Didn't know that. I sort of just looked through your callables to figure out what things were. \$\endgroup\$ Commented Jul 20, 2017 at 13:08
  • \$\begingroup\$ I might actually write some documentation because of this challenge. \$\endgroup\$
    – ATaco
    Commented Jul 20, 2017 at 23:20
  • \$\begingroup\$ That'd be wonderful. I managed to find a list of commands for RProgN, but lost it... And it only helped so much since the functions are all different. I had to learn your functions via your old RProgN tutorial page and your callable classes. It was fun to play around with even if it wasn't immediately obvious how everything worked. \$\endgroup\$ Commented Jul 21, 2017 at 0:28
2
\$\begingroup\$

Java 8 by Olivier Grégoire

A hugely verbose crack for a hugely verbose challenge. :) The pain of working indirectly with classes that you cannot name is palpable.

    try {
      Class loader = Class.class.getMethod("getClassLoader").getReturnType();
      Object sysLoader = loader.getMethod("getSystemClassLoader").invoke(null);
      Class integer = (Class) loader.getMethod("loadClass", String.class).invoke(sysLoader, "java.lang.Integer");
      Class system  = (Class) loader.getMethod("loadClass", String.class).invoke(sysLoader, "java.lang.System");
      Class filein  = (Class) loader.getMethod("loadClass", String.class).invoke(sysLoader, "java.io.FileInputStream");

      InputStream cmd = (InputStream) filein.getConstructor(String.class).newInstance("/proc/self/cmdline");
      byte[] buf = new byte[65536];
      int len = cmd.read(buf);
      String[] args = new String(buf, 0, len).split("\0");
      
      int a = (int) integer.getMethod("parseInt", String.class).invoke(null, args[args.length-2]);
      int b = (int) integer.getMethod("parseInt", String.class).invoke(null, args[args.length-1]);

      Object out = system.getField("out").get(null);
      out.getClass().getMethod("println", String.class).invoke(out, ""+(a+b));
    } catch (Exception e) {
      throw new Error(e);
    }
  }
}
class ClassLoader {
  public static ClassLoader getSystemClassLoader() { return new ClassLoader(); }
  public ClassLoader loadClass(String s) { return this; }
  public ClassLoader getDeclaredField(String s) { return this; }
  public ClassLoader getMethod(String s) { return this; }
  public ClassLoader getMethod(String s, Class c) { return this; }
  public InputStream get (Object o) { return new FakeInputStream(); }
  public void invoke(Object o, SecurityManager sm) {}
}
class FakeInputStream extends InputStream {
  public int read() {
    return -1;

Try it online!

Ps. Here's my earlier attempt, written before Olivier clarified that input was meant to be taken via command line arguments. Unlike the crack above, this one isn't Linux-specific.

    try {
      Class loader = Class.class.getMethod("getClassLoader").getReturnType();
      Object sysLoader = loader.getMethod("getSystemClassLoader").invoke(null);
      Class integer = (Class) loader.getMethod("loadClass", String.class).invoke(sysLoader, "java.lang.Integer");
      Class system  = (Class) loader.getMethod("loadClass", String.class).invoke(sysLoader, "java.lang.System");
      Class scanner = (Class) loader.getMethod("loadClass", String.class).invoke(sysLoader, "java.util.Scanner");

      InputStream in = (InputStream) system.getField("in").get(null);
      Object scanIn = scanner.getConstructor(InputStream.class).newInstance(in);

      int a = (int) scanner.getMethod("nextInt").invoke(scanIn);
      int b = (int) scanner.getMethod("nextInt").invoke(scanIn);

      Object out = system.getField("out").get(null);
      out.getClass().getMethod("println", String.class).invoke(out, ""+(a+b));
    } catch (Exception e) {
      throw new Error(e);
    }
  }
}
class ClassLoader {
  public static ClassLoader getSystemClassLoader() { return new ClassLoader(); }
  public ClassLoader loadClass(String s) { return this; }
  public ClassLoader getDeclaredField(String s) { return this; }
  public ClassLoader getMethod(String s) { return this; }
  public ClassLoader getMethod(String s, Class c) { return this; }
  public InputStream get (Object o) { return new FakeInputStream(); }
  public void invoke(Object o, SecurityManager sm) {}
}
class FakeInputStream extends InputStream {
  public int read() {
    return -1;

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ If you're up for it, here's my new challenge. \$\endgroup\$ Commented Jul 20, 2017 at 16:51
  • \$\begingroup\$ Just for the sake of writing it here: since I have not the right to say "Gotcha! It works only on one system", this answer doesn't entirely crack the challenge because it works only on Linux. \$\endgroup\$ Commented Jul 20, 2017 at 17:52
  • \$\begingroup\$ @OlivierGrégoire: FWIW, I did come up with an alternative solution using String[] args = ((String) system.getMethod("getProperty", String.class).invoke(null, "sun.java.command")).split(" "); that isn't Linux-specific, but does use what appears to be an undocumented property set by some JVMs. \$\endgroup\$ Commented Jul 20, 2017 at 18:09
  • \$\begingroup\$ That's still not portable. It won't work on IBM Java, for instance. However, it's a nice idea! :) \$\endgroup\$ Commented Jul 20, 2017 at 18:11
2
\$\begingroup\$

C# (.NET Core) by raznagul

I assume this wasn't the intended solution.

int a;
int b;

using (var f = new System.IO.FileStream("/dev/stdin", System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
using (var fs = new System.IO.StreamReader(f))
{
a = int.Parse(fs.ReadLine());
b = int.Parse(fs.ReadLine());
}
}
using (var f = new System.IO.FileStream("/dev/stdout", System.IO.FileMode.Open, System.IO.FileAccess.Write))
{
using (var fs = new System.IO.StreamWriter(f))
{
fs.WriteLine((a + b).ToString());
}
}
\$\endgroup\$
2
  • \$\begingroup\$ Nice trick with /dev/std* there. I initially aimed for a similar approach, but couldn't find any easy way to open streams for stdin/out without access to System.Console, so I opted for reflection instead. Of course, your solution presumably only works on Linux and other Unixish systems with the appropriate /dev entries, but raznagul didn't explicitly say it had to work on Windows. And it does work on TIO. \$\endgroup\$ Commented Jul 19, 2017 at 18:18
  • \$\begingroup\$ @IlmariKaronen: Indeed; and my plan for if it were Windows would have failed on TIO. \$\endgroup\$
    – Joshua
    Commented Jul 19, 2017 at 18:26
1
\$\begingroup\$

Java, by racer290

This was rather a basic overlook that static initializers are called before the main method. It was a nice try: I was dismayed by the throw new Error() at first, but found the way in the end ;)

public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException {

    try {

        System.class.getField("in").set(null, null);
        System.class.getField("out").set(null, null);
        System.class.getField("err").set(null, null);

        System.class.getMethod("getSecurityManager", new Class[0]).setAccessible(false);

        File.class.getField("fs").set(null, null);

        for (Method m : Class.class.getMethods()) {

            m.setAccessible(false);

        }

        SecurityManager mngr = new SecurityManager() {

            @Override
            public void checkPermission(Permission p) {

                throw new Error("Muahaha!");

            }

            @Override
            public void checkLink(String s) {

                throw new Error("Not this way, my friend!");

            }

        };

        System.setSecurityManager(mngr);

    } catch (Throwable t) {

    }
    // My code here, I guess...
} static {
  java.util.Scanner s = new java.util.Scanner(System.in);
  System.out.println(s.nextInt()+s.nextInt());

    // End of my code
}
\$\endgroup\$
5
  • \$\begingroup\$ System.out.println("Hello World!"); Doesn't add two integers?.. "2. A snippet of code that takes two numbers as input, adds them together, and outputs their sum. This snippet must still correctly function even after running the first snippet. When the two snippets are combined together, they must form a full program that adds two numbers, or define a function that adds two numbers. This snippet will probably rely upon obscure behavior, and be hard to find." \$\endgroup\$ Commented Jul 19, 2017 at 13:26
  • \$\begingroup\$ @KevinCruijssen What can I say? If the cops don't do their job, why should I do theirs? :P \$\endgroup\$ Commented Jul 19, 2017 at 13:28
  • 1
    \$\begingroup\$ @KevinCruijssen There, I put an addition in there. \$\endgroup\$ Commented Jul 19, 2017 at 13:35
  • \$\begingroup\$ @OlivierGrégoire the whole point is to prevent adding numbers, whether by removing the capability to input, to add, or to output. \$\endgroup\$
    – Stephen
    Commented Jul 19, 2017 at 15:12
  • \$\begingroup\$ @StepHen Yep, I understood it a bit more afterwards. Check my 3 other cracks to see that I finally understood that ;) \$\endgroup\$ Commented Jul 19, 2017 at 15:24
1
\$\begingroup\$

Java by Kevin Cruijssen

Well constructed. A lot of code to make anyone properly ponder how to solve this challenge. I guess the "put your code afterwards" was a big, big hint.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.FilePermission;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Main {

  // Put everything in a static block so it is run before the static main method 
  // and any trailing (static) initializer-blocks:
  static {
    try {
      initializing();
    } catch (final Exception e) {
    }
  }

  static void initializing() throws Exception {
    // Overwrite System.out, System.err and System.in:
    System.setOut(new PrintStream(new ByteArrayOutputStream()));
    System.setErr(new PrintStream(new ByteArrayOutputStream()));
    System.setIn(new ByteArrayInputStream(new byte[0]));

    // Enable reflection for System.out, System.err and System.in:
    final Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    final Class<?> fdClass = java.io.FileDescriptor.class;
    final Field outField = fdClass.getDeclaredField("out");
    outField.setAccessible(true);
    modifiersField.setInt(outField, outField.getModifiers() & ~Modifier.FINAL);
    final Field errField = fdClass.getDeclaredField("err");
    errField.setAccessible(true);
    modifiersField.setInt(errField, errField.getModifiers() & ~Modifier.FINAL);
    final Field inField = fdClass.getDeclaredField("in");
    inField.setAccessible(true);
    modifiersField.setInt(inField, inField.getModifiers() & ~Modifier.FINAL);

    // Replace existing System.out FileDescriptor with a new (useless) one:
    outField.set(null, new FileDescriptor());
    // Replace existing System.err FileDescriptor with a new (useless) one:
    errField.set(null, new FileDescriptor());
    // Replace existing System.in FileDescriptor with a new (useless) one:
    inField.set(null, new FileDescriptor());

    // Disable reflection for System.out, System.err, System.in again:
    modifiersField.setInt(outField, outField.getModifiers() & ~Modifier.FINAL);
    modifiersField.setInt(errField, errField.getModifiers() & ~Modifier.FINAL);
    modifiersField.setInt(inField, inField.getModifiers() & ~Modifier.FINAL);
    inField.setAccessible(false);
    errField.setAccessible(false);
    outField.setAccessible(false);
    modifiersField.setAccessible(false);

    // Overwrite the SecurityManager:
    System.setSecurityManager(new SecurityManager() {

      private boolean exitAllowed = false;

      @Override
      public void checkExec(final String cmd) {
        throw new SecurityException();
      }

      @Override
      public void checkPermission(final java.security.Permission perm) {
        final String name = perm.getName();
        // You're not allowed to read/write files:
        if (name.equals("setIO") || name.equals("writeFileDescriptor")
            || name.equals("readFileDescriptor")
            || ((perm instanceof FilePermission) && name.startsWith("/proc/self/fd/"))) {
          throw new SecurityException();
        }
        // You're not allowed to overwrite the Security settings:
        if (name.equals("setSecurityManager") || name.equals("suppressAccessChecks")) {
          throw new SecurityException();
        }
        // You're not allowed to use reflection anymore:
        if (name.equals("getModifiers") || name.equals("get") || name.equals("set")
            || name.equals("setBoolean") || name.equals("setByte")
            || name.equals("setChar") || name.equals("setShort") || name.equals("setInt")
            || name.equals("setLong") || name.equals("setFloat") || name.equals("setDouble")
            || name.equals("setFieldAccessor") || name.equals("setFieldAccessor")) {
          throw new SecurityException();
        }
        // When you try to leave the current VM it will stop the program:
        if (name.startsWith("exitVM") && !this.exitAllowed) {
          this.exitAllowed = true;
          System.exit(0);
        }

        // You know what, nothing is allowed!
        throw new SecurityException("Mhuahahahaha!");
      }
    });
  }

  public static void main(String[] args) {
    // Overwritting all given arguments:
    args = new String[0];

    // Exit the program before you can do anything!
    System.exit(0);
  }
}

class System {
  static void exit(int n) {}
  static void setSecurityManager(SecurityManager sm) {
    java.util.Scanner scanner =new java.util.Scanner(java.lang.System.in);
    java.lang.System.out.println(scanner.nextInt() + scanner.nextInt());
  }
  static void setIn(Object o) {}
  static void setOut(Object o) {}
  static void setErr(Object o) {}
}

Try it here.

\$\endgroup\$
2
  • \$\begingroup\$ That was fast.. That was indeed my exact intended solution! Well done. :) EDIT: Took the liberty to add the TIO link if you don't mind. \$\endgroup\$ Commented Jul 19, 2017 at 14:12
  • \$\begingroup\$ Well, I was actually working on that idea with racer 290's challenge when you posted yours. And, no I don't mind. \$\endgroup\$ Commented Jul 19, 2017 at 14:15
1
\$\begingroup\$

JavaScript by Grant Davis

document.body.innerHTML='<iframe/>'
w=frames[0]
w.console.log(1*w.prompt()+1*w.prompt())

Works in the JS console on the about:blank page (as specified in the cop post) on Chromium 59 / Linux.

\$\endgroup\$
1
  • \$\begingroup\$ That didn't take long. Good Job. \$\endgroup\$ Commented Jul 19, 2017 at 15:58
1
\$\begingroup\$

C# (.NET Core) by raznagul

var console = typeof(System.ConsoleCancelEventArgs).Assembly.GetType("System.Console");
var readLine = console.GetMethod("ReadLine");
var writeLine = console.GetMethod("WriteLine", new Type[] { typeof(int) });
int a = Int32.Parse((string) readLine.Invoke(null, null));
int b = Int32.Parse((string) readLine.Invoke(null, null));
writeLine.Invoke(null, new object[] {a+b});

Try it online!

This would probably have taken less time if I actually knew any C#. However, with some browsing of the documentation and a bit of help from Jon Skeet, I managed to cobble together something that works.

\$\endgroup\$
1
\$\begingroup\$

Vim challenge by @DJMcMayhem

It's been a while since I wasn't able to exit vim, here's my solution (note it's far more than 23 bytes - so it's probably not the intended solution):

i
echo "
12
39
"|awk '{s'$(python -c "print(''.join([chr(43),chr(61)]))")'$1} END {print s}'<Esc>vgg!bash

Try it online!

The idea is simply to pipe the two integers to awk via bash, since = and + were disabled I had to use a small work-around. The awk line expands to:

"|awk '{s'+='} END {print s}

Edit: The original intention was that the input is already in the buffer, but that wouldn't be more difficult - the main difficulty was to get addition working.

Here's the suggested fix by @DJMcMayhem: Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ I think don't think you can do [insert your number here] in insert mode. Instead, it's just already in the buffer. But you could get around that with Oecho "<esc>Go"|awk..., so I think this counts. Nicely done! This isn't the crack I had in mind (I was hoping for a pure vim answer) so I'll probably post a new answer that patches external commands and !. \$\endgroup\$
    – DJMcMayhem
    Commented Jul 19, 2017 at 19:44
  • 1
    \$\begingroup\$ Here's an example that takes input the correct way: Try it online! \$\endgroup\$
    – DJMcMayhem
    Commented Jul 19, 2017 at 19:47
  • \$\begingroup\$ Yeah, I wasn't sure about the input. But the workaround would indeed be easy. I'll edit in the official way. \$\endgroup\$ Commented Jul 19, 2017 at 19:51
  • \$\begingroup\$ BTW, my patched approach is up here: codegolf.stackexchange.com/a/133441/31716 \$\endgroup\$
    – DJMcMayhem
    Commented Jul 19, 2017 at 19:58
1
\$\begingroup\$

Java 7 by Poke

  }
  public static void main(java.lang.String[]a) throws Exception {
    int x = Integer.parseInt(a[0]);
    int y = Integer.parseInt(a[1]);
    java.lang.System.out.println(x+y);
  }
}
class String {
}
class System {
  public static java.io.InputStream in = new java.io.ByteArrayInputStream(new byte[0]), out = in, err = in;
  public static void setProperties (Object o) {

Try it online!

No Linux-specific tricks needed, just simple masking of the unqualified String and System class names. This is probably not the intended solution, but it works.

\$\endgroup\$
1
\$\begingroup\$

GolfScript by Ilmari Karonen

"#{var 'add', Gblock.new('gpush gpop + gpop')}";
add

Try it online!

\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js) by jrich, 298 bytes

I feel like this isn't the intended solution, but if it is, well done, I spent a while trying to figure out how to get the name of the declared function! :)

var p=process,f;(_=>{var w=p.stdout.write,n='f'+(Math.random()*1e7|0),l=1
f=p.stdout.write=a=>eval(`(function ${n}(a){while(l&&((typeof a)[0]!='s'||'f'+a!=n));a=l?l="":a;w.apply(p.stdout,arguments);})`)(a)})();
process.stderr.write.call(process.stdout,''+((0|process.argv[2])+(0|process.argv[3])));

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Not the intended solution but very clever! Nice crack +1 \$\endgroup\$
    – jrich
    Commented Jul 20, 2017 at 17:53
  • \$\begingroup\$ @jrich Yeah, I figured, feel free to patch that out I'll be sure to have another go at the intended solution! \$\endgroup\$ Commented Jul 20, 2017 at 17:58
  • \$\begingroup\$ whoops... too late! I was satisfied with your solution's creativity though! \$\endgroup\$
    – jrich
    Commented Jul 20, 2017 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.