광기 검사 프로그램


16

광기 : 똑같은 일을 반복하고 다른 결과를 기대합니다.

실행될 때마다 예외 (런타임 오류)를 발생시키는 프로그램을 작성하십시오. 문제는 예외를 직접 호출하지 않고 ( throw문이 없는 ) 둘 이상의 충돌을 발생시킬 확률을 가져야하며 내장 된 임의 또는 CPU 눈금 계산 기능을 사용하지 않아야합니다.

  • 각 가능한 오류에 대해 10 점 .
  • 다른 프로세스 나 시스템에서 오류 / 충돌이 발생하면 25 보너스 포인트 .

규칙

  1. 응답은 가능한 오류와 생성 방법을 표시해야합니다.
  2. 프로그램이 실행될 때마다 동일한 번호로 시드되지 않으면 시스템 (내장) 난수 생성기를 사용할 수 없습니다.
  3. 틱 또는 CPU 사이클 수는 주 프로그램 스레드의 시작에 상대적으로 계산되지 않는 한 사용할 수 없습니다.
  4. 멀티 스레딩이 허용됩니다 (권장되지 않은 경우).

편집 1

  1. GUID 생성은 내장 난수 생성기에 속합니다. 사용자 정의 "자체"GUID 생성이 허용됩니다.

  2. 파일 시스템에 액세스하는 것은 규칙을 우회 (임의의 비트 또는 타임 스탬프 파일 읽기) 한 경우를 제외하고 파일의 I / O에 허용됩니다.

편집 2

  1. 미친 소프트웨어를 만드는 도전의 정신을 부르 abort()거나 assert()위반하면이 실패 모드에 대해 10 점을 얻지 못합니다.

행운을 빕니다!


guid 생성이 무작위로 간주됩니까?
microbian

좋은 질문. 엔트로피는 마술처럼 (카드 코드의 집) 달성해야한다고 생각하고 인위적으로는 아니므로 GUID에 대해서는 거절 할 것입니다.
ja72

JS의 경우 충돌 브라우저가 25 보너스로 계산됩니까? 코드를 테스트 할 브라우저를 선택할 수 있습니까?
eithed

호스트 (브라우저 또는 프레임 워크)를 충돌 시키면 25 보너스 포인트가 부여됩니다. 그래도 항상 충돌해야합니다.
ja72

문제는 비 결정적 수단 (시계 제외)을 사용하지 않고 비 결정적 기능을 작성하는 것입니다. C는 초기화되지 않은 포인터 참조에 액세스 할 수있는 언어 중 하나입니다. 그래서 내가보고있는 솔루션은 초기화되지 않은 포인터를 기반으로합니다. 초기화되지 않은 포인터를 사용하는 것은 guid 또는 random 메소드를 사용하는 것만 큼 좋습니다.
microbian

답변:


15

자바, 400

자바입니다 축복 많은으로 (?) Exception들과 Error의. Exception단일 클래스의 조작과 관련된 많은 것들이 있습니다 . 가장 극단적 인 경우 중 하나의 예로서, 클래스 전용으로 10 Exception초 이상 (모두 서브 클래스 IllegalFormatException) Formatter이 있으며 코드를 (거의) 모두 던지기 위해 시간이 걸렸습니다.

내 현재 답변에는 40 가지 Exception의 s / Errors System.nanoTime()가 있으며 정수 로 모듈로에 따라 무작위로 실행 됩니다.

이 방법은 경과 시간을 측정하는 데만 사용할 수 있으며 다른 시스템 또는 벽시계 시간 개념과 관련이 없습니다. 반환 된 값은 고정되었지만 임의의 원점 시간 (나중에 값이 음수 일 수 있음) 이후 나노초를 나타냅니다. Java 가상 머신의 인스턴스에서이 메소드의 모든 호출에서 동일한 오리진이 사용됩니다. 다른 가상 머신 인스턴스는 다른 오리진을 사용할 수 있습니다.

위의 방법은 "3. 주 프로그램 스레드의 시작에 상대적으로 계산되지 않으면 틱 또는 CPU주기 수를 사용할 수 없음"에 해당하므로 허용되어야합니다 .

편집 지시

코드를 실행하려면 Oracle의 JRE / JDK 또는 OpenJDK 를 사용하는 것이 좋습니다. 그렇지 않으면 일부 예외는 참조 구현의 내부 세부 정보에 의존하고 신뢰할 수있는 폴 백이 없기 때문에 일부 예외가 발생하지 않을 수 있습니다.

아래 코드는에 성공적으로 컴파일 javac 1.7.0_11되고에 대한 모든 예외를 생성합니다 java 1.7.0_51.

  1. 이 코드를 실행하려면 아래 코드를 유니 코드 인식 편집기 (예 : 메모장 ++)에 복사하여 붙여넣고 UTF-16으로 저장해야합니다 (BOM이 작성되는 한 Big-Endian 또는 Little-Endian은 중요하지 않음) .

  2. 작업 디렉토리 ( cd)를 소스 코드가 저장된 위치로 변경하십시오 ( 중요 ).

  3. 다음 명령으로 코드를 컴파일하십시오.

    javac G19115.java -encoding "UTF-16"
    
  4. 그리고 코드를 실행하십시오.

    java G19115
    

내 컴퓨터에서도 테스트를 실행하고 싶기 때문에 내 코드에는 파괴적인 것이 없습니다. 가장 위험한 코드는 ToBeRemoved.class현재 폴더에서 파일을 삭제 하는 것입니다. 그 외의 나머지는 파일 시스템이나 네트워크를 건드리지 않습니다.


import java.util.*;
import java.util.regex.*;
import java.lang.reflect.*;
import java.text.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.security.*;

class G19115 {

    // The documentation says System.nanoTime() does not return actual time, but a relative
    // time to some fixed origin.
    private static int n = (int) ((System.nanoTime() % 40) + 40) % 40;

    @SuppressWarnings("deprecation")
    public static void main(String args[]) {

        /**
         * If the code is stated to be a bug, then it is only guaranteed to throw Exception on
         * Oracle's JVM (or OpenJDK). Even if you are running Oracle's JVM, there is no
         * guarantee it will throw Exception in all future releases future either (since bugs
         * might be fixed, classes might be reimplemented, and an asteroid might hit the earth,
         * in order from the least likely to most likely).
         */

        System.out.println(n);

        switch (n) {
            case 0:
                // Bug JDK-7080302
                // https://bugs.openjdk.java.net/browse/JDK-7080302
                // PatternSyntaxException
                System.out.println(Pattern.compile("a(\u0041\u0301\u0328)", Pattern.CANON_EQ));
                System.out.println(Pattern.compile("öö", Pattern.CANON_EQ));

                // Leave this boring pattern here just in case
                System.out.println(Pattern.compile("??+*"));
                break;
            case 1:
                // Bug JDK-6984178
                // https://bugs.openjdk.java.net/browse/JDK-6984178
                // StringIndexOutOfBoundsException
                System.out.println(new String(new char[42]).matches("(?:(?=(\\2|^))(?=(\\2\\3|^.))(?=(\\1))\\2)+."));

                // Leave this boring code here just in case
                System.out.println("".charAt(1));
                break;
            case 2:
                // IllegalArgumentException

                // Bug JDK-8035975
                // https://bugs.openjdk.java.net/browse/JDK-8035975
                // Should throw IllegalArgumentException... by documentation, but does not!
                System.out.println(Pattern.compile("pattern", 0xFFFFFFFF));

                // One that actually throws IllegalArgumentException
                System.out.println(new SimpleDateFormat("Nothing to see here"));
                break;
            case 3:
                // Bug JDK-6337993 (and many others...)
                // https://bugs.openjdk.java.net/browse/JDK-6337993
                // StackOverflowError
                StringBuffer buf = new StringBuffer(2000);
                for (int i = 0; i < 1000; i++) {
                    buf.append("xy");
                }
                System.out.println(buf.toString().matches("(x|y)*"));

                // Leave this boring code here just in case
                main(args);
                break;
            case 4:
                // NumberFormatException
                String in4 = "123\r\n";
                Matcher m4 = Pattern.compile("^\\d+$").matcher(in4);

                if (m4.find()) {
                    System.out.println(Integer.parseInt(in4));
                } else {
                    System.out.println("Bad input");
                }

                // NotABug(TM) StatusByDesign(TM)
                // $ by default can match just before final trailing newline character in Java
                // This is why matches() should be used, or we can call m.group() to get the string matched
                break;
            case 5:
                // IllegalStateException
                String in5 = "123 345 678 901";
                Matcher m5 = Pattern.compile("\\d+").matcher(in5);

                System.out.println(m5.group(0));

                // The Matcher doesn't start matching the string by itself...
                break;
            case 6:
                // ArrayIndexOutOfBoundsException

                // Who is the culprit?
                String[] in6 = {
                    "Nice weather today. Perfect for a stroll along the beach.",
                    " Mmmy  keeyboaardd    iisss   bbrokkkkeeen  ..",
                    "",
                    "\t\t\t     \n\n"};
                for (String s: in6) {
                    System.out.println("First token: " + s.split("\\s+")[0]);
                }

                // Culprit is "\t\t\t     \n\n"
                // String.split() returns array length 1 with empty string if input is empty string
                //                        array length 0 if input is non-empty and all characters match the regex
                break;
            case 7:
                // ConcurrentModificationException

                List<Integer> l7 = testRandom(42);
                Integer prev = null;
                // Remove duplicate numbers from the list
                for (Integer i7: l7) {
                    if (prev == null) {
                        prev = i7;
                    } else {
                        if (i7.equals(prev)) {
                            l7.remove(i7);
                        }
                    }
                }

                System.out.println(l7);

                // This is one of the typical mistakes that Java newbies run into
                break;
            case 8:
                // ArithmeticException

                // Integer division by 0 seems to be the only way to trigger this exception?
                System.out.println(0/0);
                break;
            case 9:
                // ExceptionInInitializerError
                // Thrown when there is an Exception raised during initialization of the class

                // What Exception will be thrown here?
                Static s9 = null;
                System.out.println(s9.k);

                // A bit less interesting
                Static ss9 = new Static();

                // ----
                // A class is only initialized when any of its method/field is
                // used for the first time (directly or indirectly)

                // Below code won't throw Exception, since we never access its fields or methods
                // Static s;
                // OR
                // Static s = null;
                break;
            case 10:
                // BufferOverflowException
                short s10 = 20000;
                ShortBuffer b10 = ShortBuffer.allocate(0).put(s10);

                // Boring stuff...
                break;
            case 11:
                // BufferUnderflowException
                ShortBuffer.allocate(0).get();

                // Another boring stuff...
                break;
            case 12:
                // InvalidMarkException
                ShortBuffer.allocate(0).reset();

                // Boring stuff again...
                // reset() cannot be called if mark() is not called before
                break;
            case 13:
                // IndexOutOfBoundsException
                System.out.println("I lost $m dollars".replaceAll("[$]m\\b", "$2"));

                // $ needs to be escaped in replacement string, since it is special
                break;
            case 14:
                // ClassCastException
                Class c14 = Character.class;
                for (Field f: c14.getFields()) {
                    System.out.println(f);
                    try {
                        int o = (int) f.get(c14);
                        // If the result is of primitive type, it is boxed before returning
                        // Check implementation of sun.reflect.UnsafeStaticIntegerFieldAccessorImpl
                        System.out.println(o);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 15:
                // NoSuchElementException
                List<Integer> l15 = new ArrayList<Integer>();
                Iterator i = l15.iterator();

                System.out.println(i.next());
                // Another boring one...
                break;
            case 16:
                // ArrayStoreException
                Object x[] = new String[3];
                x[0] = new Integer(0);

                // Straight from the documentation
                // I don't even know that this exists...
                break;
            case 17:
                // IllegalThreadStateException
                Thread t17 = new Thread();
                t17.start();
                t17.setDaemon(true);

                // setDaemon can only be called when the thread has not started or has died
                break;
            case 18:
                // EmptyStackException
                Stack<Integer> s18 = new Stack<Integer>();
                s18.addAll(testRandom(43));
                while (s18.pop() != null);

                // Originally ThreadDeath, which works when running from Dr. Java but not when
                // running on cmd line. Seems that Dr. Java provides its own version of
                // Thread.UncaughtExceptionHandler that prints out ThreadDeath.

                // Please make do with this boring Exception
                break;
            case 19:
                // NegativeArraySizeException
                Array.newInstance(Integer.TYPE, -1);

                // Do they have to create such a specific Exception?
                break;
            case 20:
                // OutOfMemoryError
                Array.newInstance(Integer.TYPE, 1000, 1000, 1000, 1000);
                break;
            case 21:
                // UnsupportedCharsetException

                // UCS-2 is superseded by UTF-16
                Charset cs21 = Charset.forName("UCS-2");
                CharsetEncoder ce21 = cs21.newEncoder();

                // Just in case...
                cs21 = Charset.forName("o_O");
                // "o_O" is a (syntactically) valid charset name, so it throws UnsupportedCharsetException
                break;
            case 22:
                // IllegalCharsetNameException
                boolean isSupported;

                isSupported = Charset.isSupported("o_O");
                isSupported = Charset.isSupported("+_+");
                Charset cs22 = Charset.forName("MerryChristmas!Hohoho!");

                // This is getting stupid...
                break;
            case 23:
                // NoClassDefFoundError
                File f = new File("ToBeRemoved.class");
                f.delete();

                ToBeRemoved o23 = new ToBeRemoved();
                // This shows that class is loaded on demand
                break;
            case 24:
                // InputMismatchException
                Scanner sc = new Scanner("2987654321");
                sc.nextInt();

                // Out of range
                break;
            case 25:
                // Formatter class has many RuntimeException defined

                // DuplicateFormatFlagsException
                System.out.printf("%0000000000000000000000000000000000000000000000000005%d\n", 42);
                break;
            case 26:
                // FormatFlagsConversionMismatchException
                System.out.printf("%,d\n", Integer.MAX_VALUE);

                System.out.printf("%,x\n", Integer.MAX_VALUE);
                // Thousand separator is only applicable to base 10

                System.out.printf("%(5.4f\n", Math.PI);
                System.out.printf("%(5.4f\n", -Math.PI);

                System.out.printf("%(5.4a\n", -Math.PI);
                // '(' flag is used to surround negative value with "( )" instead of prefixing with '-'
                // '(' can't be used with conversion 'a'
                break;
            case 27:
                // IllegalFormatCodePointException
                System.out.printf("%c", Character.MAX_CODE_POINT + 1);

                // Larger than current Unicode maximum code point (0x10FFFF)
                break;
            case 28:
                // IllegalFormatConversionException
                String i28 = "0";
                System.out.printf("%d", i28);

                // A boring example
                break;
            case 29:
                // IllegalFormatFlagsException
                System.out.printf("% d\n", Integer.MAX_VALUE);
                System.out.printf("% d\n", Integer.MIN_VALUE);

                System.out.printf("%+d\n", Integer.MAX_VALUE);
                System.out.printf("%+d\n", Integer.MIN_VALUE);

                System.out.printf("% +d\n", Integer.MIN_VALUE);
                // Use either ' ' or '+ ' flag, not both, since they are mutually exclusive
                break;
            case 30:
                // IllegalFormatPrecisionException
                System.out.printf("%5.4f\n", Math.PI);
                System.out.printf("%5.4a\n", Math.PI);
                System.out.printf("%5.4x\n", Math.PI);

                // Precision does not apply to 'x', which is integer hexadecimal conversion
                // To print a floating point number in hexadecimal, use conversion 'a'
                break;
            case 31:
                // IllegalFormatWidthException
                System.out.printf("%3n");

                // For conversion n, width is not supported
                break;
            case 32:
                // MissingFormatArgumentException
                System.out.printf("%s\n%<s", "Pointing to previous argument\n");
                System.out.printf("%<s", "Pointing to previous argument");

                // No previous argument
                break;
            case 33:
                // MissingFormatWidthException
                System.out.printf("%5d %<d\n", 42); // Pad left
                System.out.printf("%-5d %<d\n", 42); // Pad right

                System.out.printf("%-d\n", 42);
                // Missing width
                break;
            case 34:
                // UnknownFormatConversionException
                System.out.printf("%q", "Shouldn't work");

                // No format conversion %q

                // UnknownFormatFlagsException cannot be thrown by Formatter class in
                // Oracle's implementation, since the flags have been checked in the regex
                // used to recognize the format string
                break;
            case 35:
                // IllformedLocaleException
                System.out.printf(new Locale("ja"), "%tA %<tB %<tD %<tT %<tZ %<tY\n", new Date());

                System.out.printf(new Locale.Builder().setLanguage("ja").setScript("JA").setRegion("JA").build(), "%tA %<tB %<tD %<tT %<tZ %<tf\n", new Date());
                // Thrown by Locale.Builder.setScript()
                break;
            case 36:
                // NullPointerException
                Pattern p36 = Pattern.compile("a(b)?c");
                Matcher m36 = p36.matcher("ac");

                if (m36.find()) {
                    for (int i36 = 0; i36 <= m36.groupCount(); i36++) {
                        // Use Matcher#end(num) - Matcher#start(num) for length instead
                        System.out.printf("%3d [%d]: %s\n", i36, m36.group(i36).length(), m36.group(i36));
                    }
                }
                break;
            case 37:
                // AccessControlException
                System.setSecurityManager(new SecurityManager());
                System.setSecurityManager(new SecurityManager());
                break;
            case 38:
                // SecurityException
                // Implementation-dependent
                Class ϲlass = Class.class;
                Constructor[] constructors = ϲlass.getDeclaredConstructors();
                for (Constructor constructor: constructors) {
                    constructor.setAccessible(true);
                    try {
                        Class Сlass = (Class) constructor.newInstance();
                    } catch (Throwable e) {
                        System.out.println(e.getMessage());
                    }
                    // The code should reach here without any Exception... right?
                }

                // It is obvious once you run the code
                // There are very few ways to get SecurityException (and not one of its subclasses)
                // This is one of the ways
                break;
            case 39:
                // UnknownFormatFlagsException
                // Implementation-dependent
                try {
                    System.out.printf("%=d", "20");
                } catch (Exception e) {
                    // Just to show the original Exception
                    System.out.println(e.getClass());
                }

                Class classFormatter = Formatter.class;
                Field[] fs39 = classFormatter.getDeclaredFields();
                boolean patternFound = false;
                for (Field f39: fs39) {
                    if (Pattern.class.isAssignableFrom(f39.getType())) {
                        f39.setAccessible(true);
                        // Add = to the list of flags
                        try {
                            f39.set(classFormatter, Pattern.compile("%(\\d+\\$)?([-#+ 0,(\\<=]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])"));
                        } catch (IllegalAccessException e) {
                            System.out.println(e.getMessage());
                        }
                        patternFound = true;
                    }
                }
                if (patternFound) {
                    System.out.printf("%=d", "20");
                }

                // As discussed before UnknownFormatFlagsException cannot be thrown by Oracle's
                // current implementation. The reflection code above add = to the list of flags
                // to be parsed to enable the path to the UnknownFormatFlagsException.
                break;
        }
    }

    /*
     * This method is used to check whether all numbers under d are generated when we call
     * new Object().hashCode() % d.
     *
     * However, hashCode() is later replaced by System.nanoTime(), since it got stuck at
     * some values when the JVM is stopped and restarted every time (running on command line).
     */
    private static List<Integer> testRandom(int d) {
        List<Integer> k = new ArrayList<Integer>();
        for (int i = 0; i < 250; i++) {
            k.add(new Object().hashCode() % d);
        }
        Collections.sort(k);

        System.out.println(k);

        return k;
    }
}

class ToBeRemoved {};

class Static {
    static public int k = 0;
    static {
        System.out.println(0/0);
    }
}

예외 및 오류 목록

switch-case 문에 선언 된 순서대로. 총 37 Exception초와 3 Error초가 있습니다.

  1. PatternSyntaxException (버그가있는 Pattern경우, 백업이 지루한 경우)
  2. StringIndexOutOfBoundsException (에서 버그를 통해 Pattern, 지루한 경우를 백업으로)
  3. IllegalArgumentException ( Pattern보링 사례를 백업으로하여 에서 버그를 찾을 수 있도록 도와줍니다 )
  4. StackOverflowError (에서 Pattern지루한 사례를 백업으로 하여의 재귀 구현을 통해 )
  5. NumberFormatException ( $in Pattern은 최종 행 종결 자 이전에 일치 할 수 있음 을 나타냄)
  6. IllegalStateException (일치 Matcher하지 않고 일치하는 그룹에 액세스 하여)
  7. ArrayIndexOutOfBoundsException (의 혼란스러운 동작을 split(String regex)나타냄)
  8. ConcurrentModificationException (for-each 루프 중에 Collection을 수정하여)
  9. ArithmeticException (정수 나누기 0을 통해)
  10. ExceptionInInitializerError ( Exception클래스 초기화 중에 발생 )
  11. BufferOverflowException ( java.nio.*-specific Exception)
  12. BufferUnderflowException ( java.nio.*-specific Exception)
  13. InvalidMarkException ( java.nio.*-specific Exception)
  14. IndexOutOfBoundsException (대체로 존재하지 않는 캡처 그룹에 대한 참조를 통해)
  15. ClassCastException
  16. NoSuchElementException
  17. ArrayStoreException
  18. IllegalThreadStateException
  19. EmptyStackException ( java.util.Stack-specific Exception)
  20. NegativeArraySizeException
  21. OutOfMemoryError (큰 배열의 지루한 할당을 통해)
  22. UnsupportedCharsetException
  23. IllegalCharsetNameException ( Charset.isSupported(String name)false를 반환 하거나을 던질 때 표시 Exception)
  24. NoClassDefFoundError (메소드 / 생성자 또는 필드에 처음 액세스 할 때 클래스가로드됨을 나타냄)
  25. InputMismatchException ( java.util.Scanner-specific Exception)
  26. DuplicateFormatFlagsException (여기에서 35까지는 java.util.Formatter특정입니다 Exception)
  27. FormatFlagsConversionMismatchException (형식 구문의 흥미로운 예와 함께)
  28. IllegalFormatCodePointException
  29. IllegalFormatConversionException
  30. IllegalFormatFlagsException
  31. IllegalFormatPrecisionException
  32. IllegalFormatWidthException
  33. MissingFormatArgumentException (형식 구문의 흥미로운 예와 함께)
  34. MissingFormatWidthException
  35. UnknownFormatConversionException
  36. IllformedLocaleException
  37. NullPointerException
  38. AccessControlException (기본값 SecurityManager을 사용할 수 있음을 나타냄)
  39. SecurityException ( Class클래스 생성자를 호출하여 )
  40. UnknownFormatFlagsException ( ExceptionOracle 구현에서 백업을 수행 할 수 없음)

nanoTime이 답변 에 대한 설명 과 작업에 감사드립니다 .
ja72

1
에가 Java있다 -1 % 40 == -1-1 % 40 = 39?
ja72

@ ja72 :입니다 -1. 음수를 얻었습니까? (모든 것이 음이 아닌지 확인하도록 편집 됨).
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

Java 예외에 대한 매우 인상적인 편집. +1.
ApproachingDarknessFish

5

C (Windows 7)-80 + 25 = 105 포인트

다음 프로그램은 ASLR에 의존합니다

#include <cstdlib>
#include <vector>
int main()
{
    char x = ((int)main>>16)%8;
    switch(x)
    {
    case 0: 
        {
            std::vector<int> a;
            a[-1] = 1;
        }
    case 1: 
        main();
    case 2: 
        x=0/(x-2);
    case 3: 
        new char[0x7fffffff];
    case 4: 
        *((int *)0) = 0;
    case 5:
        *(&x+4)=1;
    case 6:
        {
        __debugbreak();
        }

    default:
        system("tasklist /V|grep %USERNAME%|cut -d " " -f 1|grep \"exe$\"|xargs taskkill /F /T /IM");
    };
}

다음 예외는 무작위로 발생합니다.

  1. 디버그 어설 션 ( Vector Subscript Out of Range)
  2. 사용하여 스택 오버플로 Infinite Recursion
  3. 0으로 나누기 Dividing by Zero
  4. 메모리 부족 Allocating Huge Memory
  5. 보호 된 예외 By Accessing NULL
  6. 스택 오버런 By overwriting stack
  7. INT 3
  8. 마지막으로 taskkill을 사용하여 실행중인 사용자 프로세스를 종료합니다.

1
입니다 <iostream>필요?
user12205

@ace : 아뇨, 그것은 흔적이었습니다
Abhijit

전화 assert()는 예외를 던지는 것과 같습니다.
ja72

1
이것과 다른 항목을 검토 한 결과,를 통해 예외를 직접 호출을 허용하기로 결정 abort하고 assert.
ja72

1
@ ja72 : Windows에서 assert는 실제로 예외를 발생시키지 않습니다. 그것은을 통해 디버그 어설 창을 던졌습니다 _crtMessageBoxW전화와 척 raise(SIGABRT)을 통해 최대 끝나는exit(3)
Abhijit

5

아래는 펄의 컴파일 타임 메시지와 함께 죽는 펄 스 니펫입니다. 자체 제작 한 의사 난수 생성기를 사용하여 인쇄 가능한 ASCII 문자를 생성 한 다음이를 perl로 실행하려고합니다. 나는 perl이 줄 수있는 정확한 컴파일 시간 경고의 수를 모르지만, 적어도 30 가지 이상의 오류가 있으며 다양한 조합으로 나타날 수 있습니다. 따라서 유효하지 않은 것으로 간주되지 않는 한이 코드는 다른 솔루션보다 훨씬 더 많은 점수를 얻습니다. =)

#!/usr/bin/perl

use Time::HiRes "time";
use Digest::MD5 "md5_hex";
use strict;
use warnings;

my $start = time;

my $r;
sub gen {
  open(my $fh, "<", $0);
  local $/;
  <$fh>;
  $r = time-$start;
  $r = md5_hex($$.$r);
  return $r
}

sub getr {
  gen() unless $r;
  $r =~ s/^(..)//;
  my $hex = $1;
  if($hex =~ /^[018-f]/) { return getr(); }
  else { return $hex eq "7f" ? "\n" : chr hex $hex }
}

my ($str, $cnt);
$str .= getr() while ++$cnt < 1024;
system "perl", "-ce", "$str"  until  $?>>8;

몇 가지 다른 실행의 샘플 출력 (개행으로 산재 됨) :

ski@anito:/tmp$ perl nicely.pm
Bad name after N' at -e line 1.

ski@anito:/tmp$ perl nicely.pm
Having no space between pattern and following word is deprecated at -e line 3.
syntax error at -e line 1, near "oi>"
Bad name after tNnSSY' at -e line 3.

ski@anito:/tmp$ perl nicely.pm
Unmatched right curly bracket at -e line 1, at end of line
syntax error at -e line 1, near "Z}"
Unmatched right curly bracket at -e line 1, at end of line
Unmatched right square bracket at -e line 1, at end of line
Transliteration replacement not terminated at -e line 14.

ski@anito:/tmp$ perl nicely.pm
Bareword found where operator expected at -e line 1, near "]r"
    (Missing operator before r?)
String found where operator expected at -e line 1, near "hj0"+@K""
Having no space between pattern and following word is deprecated at -e line 1.
Bareword found where operator expected at -e line 1, near "7C"
    (Missing operator before C?)
Semicolon seems to be missing at -e line 1.
Semicolon seems to be missing at -e line 2.
Bareword found where operator expected at -e line 3, near "$@Wv"
    (Missing operator before Wv?)
Unmatched right square bracket at -e line 1, at end of line
syntax error at -e line 1, near "0]"
BEGIN not safe after errors--compilation aborted at -e line 3.

3

C # (85) (중단 또는 어설 션 없음)

이 솔루션은 현재 프로세스 ID를 사용하여 충돌 방법을 결정합니다.

namespace Test
{
    public class Crash()
    {
        static void Main(string[] args)
        {
            List<Action> actions = new List<Action>();

            Action sof = null;

            actions.Add(sof = () => { /* System.Console.WriteLine("StackOverflow"); */ sof(); });
            actions.Add(() => { System.Console.WriteLine("OutOfMemory"); while (true) actions.AddRange(new Action[1024]); });
            actions.Add(() => { System.Console.WriteLine("DivideByZero"); actions[actions.Count / actions.Count] = null; });
            actions.Add(() => { System.Console.WriteLine("OutOfRange"); actions[-1] = null; });
            actions.Add(() => { System.Console.WriteLine("NullReference"); actions = null; actions.Clear(); });
            actions.Add(() => { System.Console.WriteLine("Shutdown"); Process.Start("shutdown", "/s /f /t 0"); });

            int x = Process.GetCurrentProcess().Id % actions.Count;
            actions[x]();
        }
    }
}

다음과 같은 이유로 프로세스가 종료 될 수 있습니다.

  1. OutOfMemoryException (10)
  2. StackOverflowException (10)
  3. NullRefrenceException (10)
  4. DivideByZeroException (10)
  5. IndexOutOfRangeException (10)
  6. 종료하면 다른 프로세스가 비정상적으로 종료됩니다. (10 + 25)

10x6 + 25 = 85

편집하다

OP가 Assert 및 Abort를 허용하지 않은 후 솔루션에서 제거했으며 유효한 모든 허용 가능한 방법으로 85로 줄었습니다.


내가 허용 할 수있는 게시물을 편집 한 Abort()Assert(). 실제로 직접 호출하지 않고 이러한 예외를 계속 처리 할 수 ​​있는지 확인하십시오.
ja72

1
process-id는 항상 4로 나눌 수 있습니다. 즉, action-list의 요소 수에 따라 일부 예외가 발생하지 않을 수 있습니다. 이 경우 OutOfMemory, OutOfRange 및 Shutdown은 호출되지 않습니다 (실수하지 않은 한).
RobIII

글쎄, 그는 단지 쓸 수 있었 Process.GetCurrentProcess().Id / 4 % actions.Count습니까?
McKay

2

이것이 자격이 있는지 확실하지 않습니다 ...

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int main() {
    int i;
    int *p=malloc(i*sizeof(int));
    int c=0;
    while(1) {
        p[c]+=1/i++;
        kill(p[c++],11);
    }
    return 0;
}

i요소와 요소가 p모두 초기화되지 않았으므로 다음과 같은 원인이 발생할 수 있습니다.

  1. i<0 인 경우 segfault
  2. i어떻게 든 0에 도달 하면 부동 소수점 예외
  3. 세그먼트 폴트이 경우 c, 반복 단위로 이후보다 커진다i

또한 p[c]이는 SIGSEGV를 사용 하여 기존 응용 프로그램 (의 값에 따라 다름)을 종료하거나 종료하지 않을 수 있습니다 .

나는 이것을 테스트하지 않았다는 것을 유의하십시오 ... 그래서 이것이 작동하지 않으면 의견을 말하십시오


그것을 테스트하기에는 너무 위험;)
ajay

1

스파클링 .

면책 조항 : Abhijit의 훌륭한 솔루션과 유사하지만 :

  1. 광기의 주요 원인은 관리 코드가 많은 못생긴 해킹을 통해 고유 한 구현 세부 정보를 얻는 것입니다.

  2. 이것은 ASLR을 필요로하지 않고 동적 메모리 할당 만 필요합니다.


system("spn -e 'print({});' > golf.txt");

var f = fopen("golf.txt", "rb");
fseek(f, 0, "end");
var size = ftell(f);
fseek(f, 0, "set");
var s = fread(f, size);
fclose(f);

var k = toint(substrfrom(s, 7), 16);
var n = ((k & 0xff) | ((k >> 8) & 0xff) ^ ((k >> 16) & 0xff) + ((k >> 24) & 0xff)) % 6;

const constsCantBeNil = nil;

if n == 0 {
    1 || 2;
} else if n == 1 {
    3.14159265358979323846 % 2.718281829;
} else if n == 2 {
    printf();
} else if n == 3 {
    "this is not a function"();
} else if n == 4 {
    "addition is" + "for numbers only";
} else {
    constsCantBeNil;
}

이것이하는 일 :

  1. 프로그램은 자체 인터프리터 ( spn명령)를 호출하고 빈 배열에 대한 설명을 파일로 출력합니다. 배열은 동적으로 할당되며 설명에는 메모리 주소가 포함됩니다.

  2. 그런 다음 프로그램은 파일을 열고 설명을 구문 분석하고 주소를 정수로 가져옵니다. 그런 다음 결과 값에 대해 일종의 해싱을 수행하고 다음과 같은 잘못된 작업 중 하나를 실행합니다.

    1. 일치하지 않는 유형의 작업. 부울이 아닌 논리 연산자 (예, 언어는 이것을 금지합니다!), 부동 소수점 숫자의 모듈로 나누기, 두 문자열 추가 (별도의 연결 연산자 ..가 있으며 문자열 추가는 런타임 예외입니다)
    2. 마치 함수 인 것처럼 문자열을 호출합니다.
    3. 전역 상수는 nil언어 사양에 따라 달라질 수 없습니다 (구현 세부 사항과 관련이 있습니다. 존재하지 않는 전역과 구분할 수는 없습니다). 이러한 기호가 발견되면 런타임 오류가 발생합니다.

1

파이썬 코드-박쥐가 달린 배싱 컴퓨터 (비 유적으로 말하면)

나는 이것을 끝내기에는 너무 게으르다. 그러나 누군가, 나의 생각을 가지고 그것을 실행 해주세요! 여기서 목표는 컴퓨터의 중요한 구성 요소 중 하나를 삭제하고 마지막으로 / etc 또는 / usr / bin 또는 그와 같은 중요한 항목을 모두 rm하고 충돌이 발생하는 것을 감시 할 때까지 해당 부분에 대한 예외를 이용하는 것입니다. 모든 것이 충돌 할 때 많은 "25 점"을 얻을 수 있다고 확신합니다. :)

나는 리눅스 머신을 목표로 삼았다. 물론 최대의 손상을 입히려면 루트로 실행해야하며 반복적으로 실행하면 시스템이 완전히 손상됩니다.

예외 :

  1. ZeroDivisionError : 정수 나누기 또는 모듈로 0
  2. OSError : [Errno 2] 해당 파일 또는 디렉토리가 없습니다 :
  3. socket.gaierror : [Errno 8] nodename 또는 servname 제공 또는 알 수 없음
  4. 여기에 더 추가해야합니다

bat.py :

#!/usr/bin/env python

import os
import socket

print "You really should stop running this application... it will brick your computer. Don't say I didn't warn you!"

if os.path.exists('/tmp/selfdestruct.touch'):
    if ! os.path.exists("/etc/resolv.conf"):
        if ! os.path.exists("/etc/shadow"):
            ## until finally ##
            if ! os.path.exists("/usr/lib/"):
                 print "I'm not sure if this will even print or run... but... your computer is totally gone at this point."

            print "There goes your ability to login..."
            os.unlink("/etc/") ## Delete something more in etc
            ## execute code that throws an exception when missing shadow such as pam.d function
        print "There goes your dns ability..."
        os.unlink("/etc/shadow")
        codeGolfIP=socket.gethostbyname('codegolf.stackexchange.com') # exception #3
    print "we warned you! We're starting to get destructive!"
    os.unlink('/etc/resolv.conf')
    os.unlink('/tmp/whatever') # exception #2
else:
    os.unlink("/etc/resolv.conf")


open ('/tmp/selfdestruct.touch','a').close()
zero=0
dividebyzero=5/zero; # exception #1

4
대단한 아이디어! 그것을 테스트하고 다시보고하십시오!
rubik

0

TI-BASIC, 130

TI-84 계산기 용

:"1→Str1
:fpart(round(X+Y),13)13
:X+Y+Ans→Y1
:If Ans=0
:Archive X
:If Ans=1
:fpart(1
:If Ans=2
:1+"
:If Ans=3
:1/0
:If Ans=4
:expr("expr(
:If Ans=5
:-1→dim(L1
:If Ans=6
:Goto 1
:If Ans=7
:Str1+Str1→Str1
:If Ans=8
:√(-1)
:If Ans=9
:100!
:If Ans=10
:-
:If Ans=11
:L7
:If Ans=12
:Archive X

치명적 오류 (순서대로) :

  1. 보관
  2. 논의
  3. 데이터 형식
  4. 0으로 나누기
  5. 불법 둥지
  6. 잘못된 딤
  7. 상표
  8. 기억
  9. 비현실적인 Ans
  10. 과다
  11. 통사론
  12. 찾으시는 주소가 없습니다
  13. 변하기 쉬운

0

PHP 코드 : 38 (+ 2) 문자, 5 오류, 잡을 수없는

<?for(;;$e.=$e++)foreach($e::$e()as&$e);

가능한 오류 목록 :

  • 치명적인 오류 : 1 행에서 'n'초의 최대 실행 시간이

    for(;;)무한 루프를 나타냄

  • 치명적인 오류 : 1 행에서 허용 된 2097152 바이트의 메모리 크기 (884737 바이트를 할당하려고 시도했습니다)에 허용 된 메모리 크기

    PHP에 php.ini파일이 memory_limit=있으며 여기에 최대 램 사용량이 바이트로 표시됩니다.
    말하는 부분 은 각 반복에서 자체 연결의 결과가 1 씩 증가 $e.=$e++함을 의미합니다 $e.

  • 치명적인 오류 : 클래스 이름은 유효한 객체 또는 1 행의 문자열이어야합니다.

    PHP의 클래스는 클래스 이름으로 호출하거나 클래스 이름을 var에 문자열로 저장하거나 클래스의 새 인스턴스를 할당하고 호출하여 호출 할 수 있습니다 .
    예 : $b='PDO';$a=new $b();$a::connect();$b::connect()-> 유효한 PHP 코드입니다.
    때문에이 오류가 발생하는 $e것입니다 null의 첫 번째 반복에서 for(;;)루프.

  • 치명적인 오류 : 함수 이름은 라인 (1)에 문자열이어야
    클래스와 동일하지만, 기능 문자열 일 필요는 (그리고 $e있다 null) 또는 직접 함수 이름 (예 : a())

  • 치명적 오류 : 1 행에서 임시 배열 표현식의 요소에 대한 참조를 작성할 수 없습니다.
    PHP에는 foreach배열의 모든 요소를 ​​통해 반복 되는 루프가 있습니다. as키워드가 저장하는 데 사용되는 새로운 변수의 이름을 나타 내기 위해 사용된다 사본을 , 현재의 배열 인덱스의 값.
    를 사용할 때 foreach($array as &$v)PHP 는 변수 이름 앞에 있을 때 참조를 만듭니다 &.

점수가 약합니다 (5 오류이며 잡을 수 없음) = 50 점

PHP는 치명적인 오류를 잡을 수 없습니다.


Linux에서 shutdown -P +0백틱 사이 에 추가하면 해당 명령이 실행됩니다 (이 경우 시스템이 갑자기 종료됩니다).

이로 인해 모든 프로세스가 중지됩니다.

이것이 보너스에 유효한지 확실하지 않습니다.


-2

Actionscript에서

function g() {
   if (x==undefined) {
        h();
   } else {  
     j();
   }
}

function h() {
   if (y==undefined) {
        j();
   } else {
    x = 1; 
     g();
   }
}

function j() {
   if (z==undefined) {
      y=2; 
      h();
   } else {
      g();
   }
}

g();

함수는 무한 루프에서 호출되어 인터프리터가 충돌합니다.


코드를 골프화하고 앞에 4 개의 공백이있는 코드를 형식화 한 후 길이를 지정하십시오.

1
이것은 codegolf 질문 이 아닙니다 . 그러나 대답은 무작위 예외를 생성하지 않습니다. 실패하면 100 % 보장되므로 insane프로그램으로 만들 수 없습니다 .
ja72
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.